ng2-pdfjs-viewer 26.3.0 → 26.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1 @@
1
- /**
2
- * @licstart The following is the entire license notice for the
3
- * JavaScript code in this page
4
- *
5
- * Copyright 2024 Mozilla Foundation
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the "License");
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
18
- *
19
- * @licend The above is the entire license notice for the
20
- * JavaScript code in this page
21
- */
22
- const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[1/0,1/0,-1/0,-1/0],i=new Float32Array(e),s=[.001,0,0,.001,0,0],n=1.35,a="http://www.w3.org/2000/svg",r=1,o=2,l=4,h=16,c=32,d=64,u=128,p=256,g={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},m="pdfjs_internal_id_",f="pdfjs_internal_editor_",b={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},y={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},v={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},A=0,w=1,x=2,C=3,S=3,T=4,E={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},_={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},k=1,M=2,D=3,P=4,I=5,F={ERRORS:0,WARNINGS:1,INFOS:5},B={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,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},L=0,R=1,O=2,N=3,H=4,U={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let z=F.WARNINGS;function G(t){Number.isInteger(t)&&(z=t)}function $(){return z}function j(t){z>=F.INFOS&&console.info(`Info: ${t}`)}function W(t){z>=F.WARNINGS&&console.warn(`Warning: ${t}`)}function V(t){throw new Error(t)}function K(t,e){t||V(e)}function X(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=decodeURIComponent(escape(t))}catch{}}const s=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s)?s:null}function q(t,e,i=!1){const s=URL.parse(t);return s?(s.hash=e,s.href):i&&X(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function Y(t){return t.substring(t.lastIndexOf("/")+1)}function Q(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}const J=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class Z extends J{constructor(t,e){super(t,"PasswordException"),this.code=e}}class tt extends J{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class et extends J{constructor(t){super(t,"InvalidPDFException")}}class it extends J{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class st extends J{constructor(t){super(t,"FormatError")}}class nt extends J{constructor(t){super(t,"AbortException")}}function at(t){"string"!=typeof t&&V("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let s=0;s<e;++s)i[s]=255&t.charCodeAt(s);return i}class rt{static get isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return Q(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return Q(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return Q(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return Q(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return Q(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return Q(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):"undefined"!=typeof document&&(t=document.createElement("canvas").getContext("2d")),Q(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){if("undefined"==typeof document)return Q(this,"isAlphaColorInputSupported",!1);const t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080",Q(this,"isAlphaColorInputSupported","#ff0000"!==t.value)}}class ot{static get hexNums(){return Q(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,i){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[i]}`}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 multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const s=t[i],n=t[i+1];t[i]=s*e[0]+n*e[2]+e[4],t[i+1]=s*e[1]+n*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*s+c*a+o,t[i+e+1]=h*n+c*r+l}}static applyInverseTransform(t,e){const i=t[0],s=t[1],n=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-s*e[2]+e[2]*e[5]-e[4]*e[3])/n,t[1]=(-i*e[1]+s*e[0]+e[4]*e[1]-e[5]*e[0])/n}static axialAlignedBoundingBox(t,e,i){const s=e[0],n=e[1],a=e[2],r=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=s*h+o,g=p,m=s*d+o,f=m,b=r*c+l,y=b,v=r*u+l,A=v;if(0!==n||0!==a){const t=n*h,e=n*d,i=a*c,s=a*u;p+=i,f+=i,m+=s,g+=s,b+=t,A+=t,v+=e,y+=e}i[0]=Math.min(i[0],p,m,g,f),i[1]=Math.min(i[1],b,v,y,A),i[2]=Math.max(i[2],p,m,g,f),i[3]=Math.max(i[3],b,v,y,A)}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,e){const i=t[0],s=t[1],n=t[2],a=t[3],r=i**2+s**2,o=i*n+s*a,l=n**2+a**2,h=(r+l)/2,c=Math.sqrt(h**2-(r*l-o**2));e[0]=Math.sqrt(h+c||1),e[1]=Math.sqrt(h-c||1)}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 i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)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:[i,n,s,a]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,s,n){n[0]=Math.min(n[0],t,i),n[1]=Math.min(n[1],e,s),n[2]=Math.max(n[2],t,i),n[3]=Math.max(n[3],e,s)}static#t(t,e,i,s,n,a,r,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*s,g=c*(c*(c*n+3*l*a)+3*d*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,a,r,o,l,h,c,d){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,a,r,o,-c/h,d));const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,a,r,o,(-h+p)/g,d),this.#t(t,e,i,s,n,a,r,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,s,n,a,r,o,l){l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o),this.#e(t,i,n,r,e,s,a,o,3*(3*(i-n)-t+r),6*(t-2*i+n),3*(i-t),l),this.#e(t,i,n,r,e,s,a,o,3*(3*(s-a)-e+o),6*(e-2*s+a),3*(s-e),l)}}let lt=null,ht=null;function ct(t){return lt||(lt=/([\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,ht=new Map([["ſt","ſt"]])),t.replaceAll(lt,(t,e,i)=>e?e.normalize("NFKC"):ht.get(i))}function dt(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),function(t){"object"==typeof t&&void 0!==t?.length||V("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const s=[];for(let n=0;n<e;n+=i){const a=Math.min(n+i,e),r=t.subarray(n,a);s.push(String.fromCharCode.apply(null,r))}return s.join("")}(t)}const ut=()=>[],pt=()=>new Map,gt=()=>Object.create(null);function mt(t,e,i){return Math.min(Math.max(t,e),i)}class ft{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=s,this.offsetX=n,this.offsetY=a,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,m,f;switch((s%=360)<0&&(s+=360),s){case 180:h=-1,c=0,d=0,u=1;break;case 90:h=0,c=1,d=1,u=0;break;case 270:h=0,c=-1,d=-1,u=0;break;case 0:h=1,c=0,d=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(d=-d,u=-u),0===h?(p=Math.abs(l-t[1])*i+n,g=Math.abs(o-t[0])*i+a,m=(t[3]-t[1])*i,f=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+n,g=Math.abs(l-t[1])*i+a,m=(t[2]-t[0])*i,f=(t[3]-t[1])*i),this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return Q(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:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new ft({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){const i=[t,e];return ot.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];ot.applyTransform(e,this.transform);const i=[t[2],t[3]];return ot.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return ot.applyInverseTransform(i,this.transform),i}}class bt{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let s=null;const n=i.name;if("#text"===n)s=i.value;else{if(!bt.shouldBuildText(n))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class yt{static setupStorage(t,e,i,s,n){const a=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===n)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===n)break;t.addEventListener("change",t=>{s.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=>{s.setValue(e,{value:t.target.value})})}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})})}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${s}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&n.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",a=document.createElement(s.name);s.attributes&&this.setAttributes({html:a,element:s,intent:n,linkService:i});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 l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);a.append(t),r&&bt.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,a]];for(;h.length>0;){const[t,s,a]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);if(a.append(d),o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:i}),o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&bt.shouldBuildText(c)&&l.push(t),d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}static getPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style;return new ft({viewBox:[0,0,parseInt(s,10),parseInt(n,10)],userUnit:1,scale:e,rotation:i})}}class vt{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function At(t,e="text"){if(_t(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"blob":return i.blob();case"bytes":return i.bytes();case"json":return i.json()}return i.text()}return new Promise((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="bytes"===e?"arraybuffer":e,n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"bytes":return void i(new Uint8Array(n.response));case"blob":case"json":return void i(n.response)}i(n.responseText)}},n.send(null)})}class wt extends J{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function xt(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function Ct(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function St(t){return[t]=t.split(/[#?]/,1),Y(t)}function Tt(t,e="document.pdf"){if("string"!=typeof t)return e;if(xt(t))return W('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const i=(t=>{try{return new URL(t)}catch{}try{return new URL(decodeURIComponent(t))}catch{}try{return new URL(t,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{}return null})(t);if(!i)return e;const s=t=>{try{let e=decodeURIComponent(t);return e.includes("/")&&(e=Y(e),4===e.length&&n.test(e))?t:e}catch{return t}},n=/\.pdf$/i,a=Y(i.pathname);if(n.test(a))return s(a);if(i.searchParams.size>0){const t=t=>[...t].findLast(t=>n.test(t)),e=t(i.searchParams.values())??t(i.searchParams.keys());if(e)return s(e)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return s(t[0])}return e}class Et{#i=new Map;times=[];time(t){this.#i.has(t)&&W(`Timer is already running for ${t}`),this.#i.set(t,Date.now())}timeEnd(t){this.#i.has(t)||W(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#i.get(t),end:Date.now()}),this.#i.delete(t)}toString(){const t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).join("")}}function _t(t,e){const i=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(i?.protocol??"")}function kt(t){t.preventDefault()}function Mt(t){t.preventDefault(),t.stopPropagation()}class Dt{static#s;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#s||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#s.exec(t);if(!e)return null;const i=parseInt(e[1],10);let s=parseInt(e[2],10);s=s>=1&&s<=12?s-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 l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;return c=c>=0&&c<=59?c:0,"-"===l?(a+=h,r+=c):"+"===l&&(a-=h,r-=c),new Date(Date.UTC(i,s,n,a,r,o))}}function Pt(t){if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[e,i,s]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,i,s,1]}if(t.startsWith("rgba(")){const e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function It(t){const e=Pt(t);return e?e.slice(0,3):(W(`Not a valid color format: "${t}"`),[0,0,0])}function Ft(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform();return[e,i,s,n,a,r]}function Bt(t){const{a:e,b:i,c:s,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,i,s,n,a,r]}function Lt(t,e,i=!1,s=!0){if(e instanceof ft){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:a}=t,r=`round(down, var(--total-scale-factor) * ${s}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-y))`;i&&e.rotation%180!=0?(a.width=o,a.height=r):(a.width=r,a.height=o)}s&&t.setAttribute("data-main-rotation",e.rotation)}class Rt{constructor(){const{pixelRatio:t}=Rt;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,s,n=-1){let a=1/0,r=1/0,o=1/0;(i=Rt.capPixels(i,n))>0&&(a=Math.sqrt(i/(t*e))),-1!==s&&(r=s/t,o=s/e);const l=Math.min(a,r,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const Ot=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class Nt{static get isDarkMode(){return Q(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class Ht{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);const{color:i}=window.getComputedStyle(t);return t.remove(),Q(this,"commentForegroundColor",It(i))}}function Ut(t,e){const i=255*(1-(e=mt(e??1,0,1)));return t.map(t=>Math.round(t*e+i))}function zt(t,e){const i=t[0]/255,s=t[1]/255,n=t[2]/255,a=Math.max(i,s,n),r=Math.min(i,s,n),o=(a+r)/2;if(a===r)e[0]=e[1]=0;else{const t=a-r;switch(e[1]=o<.5?t/(a+r):t/(2-a-r),a){case i:e[0]=60*((s-n)/t+(s<n?6:0));break;case s:e[0]=60*((n-i)/t+2);break;case n:e[0]=60*((i-s)/t+4)}}e[2]=o}function Gt(t,e){const i=t[0],s=t[1],n=t[2],a=(1-Math.abs(2*n-1))*s,r=a*(1-Math.abs(i/60%2-1)),o=n-a/2;switch(Math.floor(i/60)){case 0:e[0]=a+o,e[1]=r+o,e[2]=o;break;case 1:e[0]=r+o,e[1]=a+o,e[2]=o;break;case 2:e[0]=o,e[1]=a+o,e[2]=r+o;break;case 3:e[0]=o,e[1]=r+o,e[2]=a+o;break;case 4:e[0]=r+o,e[1]=o,e[2]=a+o;break;case 5:case 6:e[0]=a+o,e[1]=o,e[2]=r+o}}function $t(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function jt(t,e,i){Gt(t,i),i.map($t);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];Gt(e,i),i.map($t);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];return s>n?(s+.05)/(n+.05):(n+.05)/(s+.05)}const Wt=new Map;function Vt(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let s=Wt.get(i);if(s)return s;const n=new Float32Array(9),a=n.subarray(0,3),r=n.subarray(3,6);zt(t,r);const o=n.subarray(6,9);zt(e,o);const l=o[2]<.5,h=l?12:4.5;if(r[2]=l?Math.sqrt(r[2]):1-Math.sqrt(1-r[2]),jt(r,o,a)<h){let t,e;l?(t=r[2],e=1):(t=0,e=r[2]);const i=.005;for(;e-t>i;){const i=r[2]=(t+e)/2;l===jt(r,o,a)<h?t=i:e=i}r[2]=l?e:t}return Gt(r,a),s=ot.makeHexColor(Math.round(255*a[0]),Math.round(255*a[1]),Math.round(255*a[2])),Wt.set(i,s),s}function Kt({html:t,dir:e,className:i},s){const n=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const s=t.split(/\r\n?|\n/);for(let t=0,e=s.length;t<e;++t){const n=s[t];i.append(document.createTextNode(n)),t<e-1&&i.append(document.createElement("br"))}n.append(i)}else yt.render({xfaHtml:t,div:n,intent:"richText"});n.firstElementChild.classList.add("richText",i),s.append(n)}function Xt(t){const e=new Path2D;if(!t)return e;for(let i=0,s=t.length;i<s;)switch(t[i++]){case L:e.moveTo(t[i++],t[i++]);break;case R:e.lineTo(t[i++],t[i++]);break;case O:e.bezierCurveTo(t[i++],t[i++],t[i++],t[i++],t[i++],t[i++]);break;case N:e.quadraticCurveTo(t[i++],t[i++],t[i++],t[i++]);break;case H:e.closePath();break;default:W(`Unrecognized drawing path operator: ${t[i-1]}`)}return e}class qt{#n=null;#a=null;#r;#o=null;#l=null;#h=null;#c=null;#d=null;static#u=null;constructor(t){this.#r=t,qt.#u||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#n=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",kt,{signal:e}),t.addEventListener("pointerdown",qt.#p,{signal:e}));const i=this.#o=document.createElement("div");i.className="buttons",t.append(i);const s=this.#r.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#n}static#p(t){t.stopPropagation()}#g(t){this.#r._focusEventsAllowed=!1,Mt(t)}#m(t){this.#r._focusEventsAllowed=!0,Mt(t)}#f(t){const e=this.#r._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#g.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#m.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",kt,{signal:e}),!0)}hide(){this.#n.classList.add("hidden"),this.#a?.hideDropdown()}show(){this.#n.classList.remove("hidden"),this.#l?.shown(),this.#h?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.classList.add("basic","deleteButton"),i.tabIndex=0,i.setAttribute("data-l10n-id",qt.#u[t]),this.#f(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#o.append(i)}get#b(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#f(e),this.#o.append(e,this.#b),this.#l=t}addComment(t,e=null){if(this.#h)return;const i=t.renderForToolbar();if(!i)return;this.#f(i);const s=this.#c=this.#b;e?(this.#o.insertBefore(i,e),this.#o.insertBefore(s,e)):this.#o.append(i,s),this.#h=t,t.toolbar=this}addColorPicker(t){if(this.#a)return;this.#a=t;const e=t.renderButton();this.#f(e),this.#o.append(e,this.#b)}async addEditSignatureButton(t){const e=this.#d=await t.renderEditButton(this.#r);this.#f(e),this.#o.append(e,this.#b)}removeButton(t){if("comment"===t)this.#h?.removeToolbarCommentButton(),this.#h=null,this.#c?.remove(),this.#c=null}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;const s=this.#o.querySelector(i);s&&"comment"===t&&this.addComment(e,s)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#n.remove(),this.#a?.destroy(),this.#a=null}}class Yt{#o=null;#n=null;#y;constructor(t){this.#y=t}#v(){const t=this.#n=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#y._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",kt,{signal:e});const i=this.#o=document.createElement("div");return i.className="buttons",t.append(i),this.#y.hasCommentManager()&&this.#A("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#y.commentSelection("floating_button")}),this.#A("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#y.highlightSelection("floating_button")}),t}#w(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(t<i)continue;const a=n.x+(e?n.width:0);t>i?(s=a,i=t):e?a>s&&(s=a):a<s&&(s=a)}return[e?1-s:s,i]}show(t,e,i){const[s,n]=this.#w(e,i),{style:a}=this.#n||=this.#v();t.append(this.#n),a.insetInlineEnd=100*s+"%",a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#n.remove()}#A(t,e,i,s){const n=document.createElement("button");n.classList.add("basic",t),n.tabIndex=0,n.setAttribute("data-l10n-id",e);const a=document.createElement("span");n.append(a),a.className="visuallyHidden",a.setAttribute("data-l10n-id",i);const r=this.#y._signal;r instanceof AbortSignal&&!r.aborted&&(n.addEventListener("contextmenu",kt,{signal:r}),n.addEventListener("click",s,{signal:r})),this.#o.append(n)}}const Qt=Object.freeze({internal:"a0babde2-53ef-4493-91fe-62dfc3177bcf"});function Jt(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class Zt{static#x=NaN;static#C=null;static#S=NaN;static#T=null;static initializeAndAddPointerId(t){(Zt.#C||=new Set).add(t)}static setPointer(t,e){Zt.#x||=e,Zt.#T??=t}static setTimeStamp(t){Zt.#S=t}static isSamePointerId(t){return Zt.#x===t}static isSamePointerIdOrRemove(t){return Zt.#x===t||(Zt.#C?.delete(t),!1)}static isSamePointerType(t){return Zt.#T===t}static isInitializedAndDifferentPointerType(t){return null!==Zt.#T&&!Zt.isSamePointerType(t)}static isSameTimeStamp(t){return Zt.#S===t}static isUsingMultiplePointers(){return Zt.#C?.size>=1}static clearPointerType(){Zt.#T=null}static clearPointerIds(){Zt.#x=NaN,Zt.#C=null}static clearTimeStamp(){Zt.#S=NaN}}class te{#E=0;get id(){return`${f}${this.#E++}`}}class ee{#_=dt();#E=0;#k=null;static get _isSVGFittingCanvas(){const t=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${a}"><rect width="1" height="1" style="fill:red;"/></svg>`,e=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;return Q(this,"_isSVGFittingCanvas",i.decode().then(()=>(e.drawImage(i,0,0,1,1,0,0,1,3),0===new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0])))}async#M(t,e){this.#k||=new Map;let i=this.#k.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#_}_${this.#E++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await At(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=ee._isSVGFittingCanvas,s=new FileReader,n=new Image,a=new Promise((t,a)=>{n.onload=()=>{i.bitmap=n,i.isSvg=!0,t()},s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=s.onerror=a});s.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){W(t),i=null}return this.#k.set(t,i),i&&this.#k.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#M(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#M(t,t)}async getFromBlob(t,e){const i=await e;return this.#M(t,i)}async getFromId(t){this.#k||=new Map;const e=this.#k.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#k||=new Map;let i=this.#k.get(t);if(i?.bitmap)return i.refCounter+=1,i;const s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#_}_${this.#E++}`,refCounter:1,isSvg:!1},this.#k.set(t,i),this.#k.set(i.id,i),i}getSvgUrl(t){const e=this.#k.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#k||=new Map;const e=this.#k.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#_}_`)}}class ie{#D=[];#P=!1;#I;#F=-1;constructor(t=128){this.#I=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(s&&t(),this.#P)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#F)return this.#D.length>0&&(this.#D.length=0),this.#F=0,void this.#D.push(o);if(a&&this.#D[this.#F].type===n)return r&&(o.undo=this.#D[this.#F].undo),void(this.#D[this.#F]=o);const l=this.#F+1;l===this.#I?this.#D.splice(0,1):(this.#F=l,l<this.#D.length&&this.#D.splice(l)),this.#D.push(o)}undo(){if(-1===this.#F)return;this.#P=!0;const{undo:t,post:e}=this.#D[this.#F];t(),e?.(),this.#P=!1,this.#F-=1}redo(){if(this.#F<this.#D.length-1){this.#F+=1,this.#P=!0;const{cmd:t,post:e}=this.#D[this.#F];t(),e?.(),this.#P=!1}}hasSomethingToUndo(){return-1!==this.#F}hasSomethingToRedo(){return this.#F<this.#D.length-1}cleanType(t){if(-1!==this.#F){for(let e=this.#F;e>=0;e--)if(this.#D[e].type!==t)return this.#D.splice(e+1,this.#F-e),void(this.#F=e);this.#D.length=0,this.#F=-1}}destroy(){this.#D=null}}class se{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=rt.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:s,options:n}),this.allKeys.add(t.split("+").at(-1)))}}#B(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 i=this.callbacks.get(this.#B(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:a=[],checker:r=null}}=i;r&&!r(t,e)||(s.bind(t,...a,e)(),n||Mt(e))}}class ne{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",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,It(s))}e.remove()}(t),Q(this,"_colors",t)}convert(t){const e=It(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ne._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?ot.makeHexColor(...e):t}}class ae{#L=new AbortController;#R=null;#O=null;#N=new Map;#H=new Map;#U=null;#z=null;#G=null;#$=null;#j=new ie;#W=null;#V=null;#K=null;#X=0;#q=new Set;#Y=null;#Q=null;#J=new Set;_editorUndoBar=null;#Z=!1;#tt=!1;#et=!1;#it=null;#st=null;#nt=null;#at=null;#rt=!1;#ot=null;#lt=new te;#ht=!1;#ct=!1;#dt=!1;#ut=null;#pt=null;#gt=null;#mt=null;#ft=null;#bt=b.NONE;#yt=new Set;#vt=null;#At=null;#wt=null;#xt=null;#Ct=null;#St={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Tt=[0,0];#Et=null;#_t=null;#kt=null;#Mt=null;#Dt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=ae.prototype,e=t=>t.#_t.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return Q(this,"_keyboardManager",new se([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["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:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,i,s,n,a,r,o,l,h,c,d,u,p,g,m){const f=this._signal=this.#L.signal;this.#_t=t,this.#kt=e,this.#Mt=i,this.#z=s,this.#W=n,this.#At=a,this.#Ct=o,this._eventBus=r;const b={signal:f,...Qt};r.on("editingaction",this.onEditingAction.bind(this),b),r.on("pagechanging",this.onPageChanging.bind(this),b),r.on("scalechanging",this.onScaleChanging.bind(this),b),r.on("rotationchanging",this.onRotationChanging.bind(this),b),r.on("setpreference",this.onSetPreference.bind(this),b),r.on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),b),window.addEventListener("pointerdown",()=>{this.#ct=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#ct=!1},{capture:!0,signal:f}),window.addEventListener("beforeunload",this.#Pt.bind(this),{capture:!0,signal:f}),this.#It(),this.#Ft(),this.#Bt(),this.#G=o.annotationStorage,this.#it=o.filterFactory,this.#wt=l,this.#at=h||null,this.#Z=c,this.#tt=d,this.#et=u,this.#ft=p||null,this.viewParameters={realScale:vt.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,n?.setSidebarUiManager(this)}destroy(){this.#Dt?.resolve(),this.#Dt=null,this.#L?.abort(),this.#L=null,this._signal=null;for(const t of this.#H.values())t.destroy();this.#H.clear(),this.#N.clear(),this.#J.clear(),this.#mt?.clear(),this.#R=null,this.#yt.clear(),this.#j.destroy(),this.#z?.destroy(),this.#W?.destroy(),this.#At?.destroy(),this.#ot?.hide(),this.#ot=null,this.#gt?.destroy(),this.#gt=null,this.#O=null,this.#st&&(clearTimeout(this.#st),this.#st=null),this.#Et&&(clearTimeout(this.#Et),this.#Et=null),this._editorUndoBar?.destroy(),this.#Ct=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ft}get useNewAltTextFlow(){return this.#tt}get useNewAltTextWhenAddingImage(){return this.#et}get hcmFilter(){return Q(this,"hcmFilter",this.#wt?this.#it.addHCMFilter(this.#wt.foreground,this.#wt.background):"none")}get direction(){return Q(this,"direction",getComputedStyle(this.#_t).direction)}get _highlightColors(){return Q(this,"_highlightColors",this.#at?new Map(this.#at.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return Q(this,"highlightColors",null);const e=new Map,i=!!this.#wt;for(const[s,n]of t){const t=s.endsWith("_HCM");i&&t?e.set(s.replace("_HCM",""),n):i||t||e.set(s,n)}return Q(this,"highlightColors",e)}get highlightColorNames(){return Q(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#K=t}setMainHighlightColorPicker(t){this.#gt=t}editAltText(t,e=!1){this.#z?.editAltText(this,t,e)}hasCommentManager(){return!!this.#W}editComment(t,e,i,s){this.#W?.showDialog(this,t,e,i,s)}selectComment(t,e){const i=this.#H.get(t),s=i?.getEditorByUID(e);s?.toggleComment(!0,!0)}updateComment(t){this.#W?.updateComment(t.getData())}updatePopupColor(t){this.#W?.updatePopupColor(t)}removeComment(t){this.#W?.removeComments([t.uid])}deleteComment(t,e){const i=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,"comment"),this.toggleComment(null),t.comment=null},undo:i,mustExec:!0})}toggleComment(t,e,i=void 0){this.#W?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#W?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#W?.dialogElement||null}async waitForEditorsRendered(t){if(this.#H.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),s=i=>{i.pageNumber===t&&(this._eventBus.off("editorsrendered",s),e())};this._eventBus.on("editorsrendered",s),await i}getSignature(t){this.#At?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#At}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#et=e}onPageChanging({pageNumber:t}){this.#X=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#H.delete(t),this.#X===t&&(this.#X=0)}focusMainContainer(){this.#_t.focus()}findParent(t,e){for(const i of this.#H.values()){const{x:s,y:n,width:a,height:r}=i.div.getBoundingClientRect();if(t>=s&&t<=s+a&&e>=n&&e<=n+r)return i}return null}disableUserSelect(t=!1){this.#kt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#J.add(t)}removeShouldRescale(t){this.#J.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*vt.PDF_TO_CSS_UNITS;for(const t of this.#J)t.onScaleChanging();this.#K?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#Lt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Rt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#H.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:s,anchorOffset:n,focusNode:a,focusOffset:r}=i,o=i.toString(),l=this.#Lt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const c=this.#Rt(l),d=this.#bt===b.NONE,u=()=>{const i=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:n,focusNode:a,focusOffset:r,text:o});d&&this.showAllEditors("highlight",!0,!0),e&&i?.editComment()};d?this.switchToMode(b.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Pt(t){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Ot(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Lt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#ot||=new Yt(this),this.#ot.show(e,i,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#G)return null;const e=`${f}${t}`,i=this.#G.getRawValue(e);return i&&this.#G.remove(e),i}addToAnnotationStorage(t){t.isEmpty()||!this.#G||this.#G.has(t.id)||this.#G.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Mt;i&&(i.setAttribute("data-l10n-id",t),e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args"))}#Nt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#vt&&(this.#ot?.hide(),this.#vt=null,this.#Ht({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#vt)return;const i=this.#Lt(t).closest(".textLayer");if(i){if(this.#ot?.hide(),this.#vt=e,this.#Ht({hasSelectedText:!0}),(this.#bt===b.HIGHLIGHT||this.#bt===b.NONE)&&(this.#bt===b.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#rt=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#bt===b.HIGHLIGHT?this.#Rt(i):null;if(t?.toggleDrawing(),this.#ct){const e=new AbortController,i=this.combinedSignal(e),s=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Ut("main_toolbar"))};window.addEventListener("pointerup",s,{signal:i}),window.addEventListener("blur",s,{signal:i})}else t?.toggleDrawing(!0),this.#Ut("main_toolbar")}}else this.#vt&&(this.#ot?.hide(),this.#vt=null,this.#Ht({hasSelectedText:!1}))}#Ut(t=""){this.#bt===b.HIGHLIGHT?this.highlightSelection(t):this.#Z&&this.#Ot()}#It(){document.addEventListener("selectionchange",this.#Nt.bind(this),{signal:this._signal})}#zt(){if(this.#nt)return;this.#nt=new AbortController;const t=this.combinedSignal(this.#nt);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Gt(){this.#nt?.abort(),this.#nt=null}blur(){if(this.isShiftKeyDown=!1,this.#rt&&(this.#rt=!1,this.#Ut("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#yt)if(e.div.contains(t)){this.#pt=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#pt)return;const[t,e]=this.#pt;this.#pt=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Bt(){if(this.#ut)return;this.#ut=new AbortController;const t=this.combinedSignal(this.#ut);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#$t(){this.#ut?.abort(),this.#ut=null}#jt(){if(this.#V)return;this.#V=new AbortController;const t=this.combinedSignal(this.#V);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Wt(){this.#V?.abort(),this.#V=null}#Ft(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Bt(),this.setEditingState(!0)}removeEditListeners(){this.#$t(),this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#Q)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#Q)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#R?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#yt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#Q)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void W(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#Vt(e);this.#Kt(t)},n=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:n,mustExec:!0})}catch(t){W(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#bt===b.NONE||this.isEditorHandlingKeyboard||ae._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#rt&&(this.#rt=!1,this.#Ut("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const i=this.#U.get(t);i&&(i.pageIndex=e,this.#H.set(e,i),this.#ht?i.enable():i.disable())}startUpdatePages(){this.#U=new Map(this.#H),this.#H.clear()}endUpdatePages(){this.#U=null}clonePage(t,e){for(const i of this.getEditors(t)){const t=i.serialize(i.mode!==b.HIGHLIGHT);t&&(t.pageIndex=e,t.id=this.getId(),t.isClone=!0,delete t.popupRef,this.#G.setValue(t.id,t))}}findClonesForPage(t){const e=[],{pageIndex:i}=t;for(const[s,n]of this.#G)n.pageIndex===i&&n.isClone&&(this.#G.remove(s),e.push(t.deserialize(n).then(e=>{e&&(e.isClone=!0,t.addOrRebuild(e))})));return Promise.all(e)}#Ht(t){Object.entries(t).some(([t,e])=>this.#St[t]!==e)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#St,t)}),this.#bt===b.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Xt([[y.HIGHLIGHT_FREE,!0]]))}#Xt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#zt(),this.#jt(),this.#Ht({isEditing:this.#bt!==b.NONE,isEmpty:this.#qt(),hasSomethingToUndo:this.#j.hasSomethingToUndo(),hasSomethingToRedo:this.#j.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Gt(),this.#Wt(),this.#Ht({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#Q){this.#Q=t;for(const t of this.#Q)this.#Xt(t.defaultPropertiesToUpdate)}}getId(){return this.#lt.id}get currentLayer(){return this.#H.get(this.#X)}getLayer(t){return this.#H.get(t)}get currentPageIndex(){return this.#X}addLayer(t){this.#H.set(t.pageIndex,t),this.#ht?t.enable():t.disable()}removeLayer(t){this.#H.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,s=!1,n=!1,a=!1){if(this.#bt!==t&&(!this.#Dt||(await this.#Dt.promise,this.#Dt))){if(this.#Dt=Promise.withResolvers(),this.#K?.commitOrRemove(),this.#bt===b.POPUP&&this.#W?.hideSidebar(),this.#W?.destroyPopup(),this.#bt=t,t===b.NONE){this.setEditingState(!1),this.#Yt();for(const t of this.#N.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#Dt.resolve()}for(const t of this.#N.values())t.addStandaloneCommentButton();t===b.SIGNATURE&&await(this.#At?.loadSignatures()),i&&Zt.clearPointerType(),this.setEditingState(!0),await this.#Qt(),this.unselectAll();for(const e of this.#H.values())e.updateMode(t);if(t===b.POPUP){this.#O||=await this.#Ct.getAnnotationsByType(new Set(this.#Q.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#N.values()){const{annotationElementId:s,hasComment:n,deleted:a}=i;s&&t.add(s),n&&!a&&e.push(i.getData())}for(const i of this.#O){const{id:s,popupRef:n,contentsObj:a}=i;n&&a?.str&&!t.has(s)&&!this.#q.has(s)&&e.push(i)}this.#W?.showSidebar(e)}if(!e)return s&&this.addNewEditorFromKeyboard(),void this.#Dt.resolve();for(const t of this.#N.values())t.uid===e?(this.setSelected(t),a?t.editComment():n?t.enterInEditMode():t.focus()):t.unselect();this.#Dt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#bt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#Q){switch(t){case y.CREATE:return void this.currentLayer.addNewEditor(e);case y.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#xt||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#yt)i.updateParams(t,e);else for(const i of this.#Q)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#N.values())i.editorType===t&&i.show(e);(this.#xt?.get(y.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Xt([[y.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#dt!==t){this.#dt=t;for(const e of this.#H.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#Qt(){if(!this.#ht){this.#ht=!0;const t=[];for(const e of this.#H.values())t.push(e.enable());await Promise.all(t);for(const t of this.#N.values())t.enable()}}#Yt(){if(this.unselectAll(),this.#ht){this.#ht=!1;for(const t of this.#H.values())t.disable();for(const t of this.#N.values())t.disable()}}*getEditors(t){for(const e of this.#N.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#N.get(t)}addEditor(t){this.#N.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#st&&clearTimeout(this.#st),this.#st=setTimeout(()=>{this.focusMainContainer(),this.#st=null},0)),this.#N.delete(t.id),t.annotationElementId&&this.#mt?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#q.has(t.annotationElementId)||this.#G?.remove(t.id)}addDeletedAnnotationElement(t){this.#q.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#q.has(t)}removeDeletedAnnotationElement(t){this.#q.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#Vt(t){const e=this.#H.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#R!==t&&(this.#R=t,t&&this.#Xt(t.propertiesToUpdate))}get#Jt(){let t=null;for(t of this.#yt);return t}updateUI(t){this.#Jt===t&&this.#Xt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Xt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#yt.has(t))return this.#yt.delete(t),t.unselect(),void this.#Ht({hasSelectedEditor:this.hasSelection});this.#yt.add(t),t.select(),this.#Xt(t.propertiesToUpdate),this.#Ht({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#K?.commitOrRemove();for(const e of this.#yt)e!==t&&e.unselect();this.#W?.destroyPopup(),this.#yt.clear(),this.#yt.add(t),t.select(),this.#Xt(t.propertiesToUpdate),this.#Ht({hasSelectedEditor:!0})}isSelected(t){return this.#yt.has(t)}get firstSelectedEditor(){return this.#yt.values().next().value}unselect(t){t.unselect(),this.#yt.delete(t),this.#Ht({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#yt.size}get isEnterHandled(){return 1===this.#yt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#j.undo(),this.#Ht({hasSomethingToUndo:this.#j.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#qt()}),this._editorUndoBar?.hide()}redo(){this.#j.redo(),this.#Ht({hasSomethingToUndo:!0,hasSomethingToRedo:this.#j.hasSomethingToRedo(),isEmpty:this.#qt()})}addCommands(t){this.#j.add(t),this.#Ht({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#qt()})}cleanUndoStack(t){this.#j.cleanType(t)}#qt(){if(0===this.#N.size)return!0;if(1===this.#N.size)for(const t of this.#N.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#yt],i=()=>{for(const t of e)this.#Vt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#R?.commitOrRemove()}hasSomethingToControl(){return this.#R||this.hasSelection}#Kt(t){for(const t of this.#yt)t.unselect();this.#yt.clear();for(const e of t)e.isEmpty()||(this.#yt.add(e),e.select());this.#Ht({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#yt)t.commit();this.#Kt(this.#N.values())}unselectAll(){if((!this.#R||(this.#R.commitOrRemove(),this.#bt===b.NONE))&&!this.#K?.commitOrRemove()&&(this.#W?.destroyPopup(),this.hasSelection)){for(const t of this.#yt)t.unselect();this.#yt.clear(),this.#Ht({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#Tt[0]+=t,this.#Tt[1]+=e;const[s,n]=this.#Tt,a=[...this.#yt];this.#Et&&clearTimeout(this.#Et),this.#Et=setTimeout(()=>{this.#Et=null,this.#Tt[0]=this.#Tt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#N.has(t.id)&&(t.translateInPage(s,n),t.translationDone())},undo:()=>{for(const t of a)this.#N.has(t.id)&&(t.translateInPage(-s,-n),t.translationDone())},mustExec:!1})},1e3);for(const i of a)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#Y=new Map;for(const t of this.#yt)this.#Y.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#Y)return!1;this.disableUserSelect(!1);const t=this.#Y;this.#Y=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},a]of t)a.newX=i,a.newY=s,a.newPageIndex=n,e||=i!==a.savedX||s!==a.savedY||n!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,s)=>{if(this.#N.has(t.id)){const n=this.#H.get(s);n?t._setParentAndPosition(n,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:n,newPageIndex:a}]of t)i(e,s,n,a)},undo:()=>{for(const[e,{savedX:s,savedY:n,savedPageIndex:a}]of t)i(e,s,n,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#Y)for(const i of this.#Y.keys())i.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.#yt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#R===t}getActive(){return this.#R}getMode(){return this.#bt}isEditingMode(){return this.#bt!==b.NONE}get imageManager(){return Q(this,"imageManager",new ee)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i<s;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:s,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-s)/a,y:1-(t+r-i)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/n,y:1-(e+o-s)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-s)/a,y:(t-i)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-i)/n,y:(e-s)/a,width:r/n,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:s,height:n}of i.getClientRects())0!==s&&0!==n&&o.push(r(t,e,s,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#$||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#$?.delete(t)}renderAnnotationElement(t){const e=this.#$?.get(t.data.id);if(!e)return;const i=this.#G.getRawValue(e);i&&(this.#bt!==b.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const s=this.#mt?.get(t);s&&(s.setCanvas(e,i),this.#mt.delete(t))}addMissingCanvas(t,e){(this.#mt||=new Map).set(t,e)}}class re{#l=null;#Zt=!1;#te=null;#ee=null;#ie=null;#se=null;#ne=!1;#ae=null;#r=null;#re=null;#oe=null;#le=!1;static#he=null;static _l10n=null;constructor(t){this.#r=t,this.#le=t._uiManager.useNewAltTextFlow,re.#he||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){re._l10n??=t}async render(){const t=this.#te=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#ee=document.createElement("span");t.append(e),this.#le?(t.classList.add("new"),t.setAttribute("data-l10n-id",re.#he.missing),e.setAttribute("data-l10n-id",re.#he["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#r._uiManager._signal;t.addEventListener("contextmenu",kt,{signal:i}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const s=t=>{t.preventDefault(),this.#r._uiManager.editAltText(this.#r),this.#le&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ce}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ne=!0,s(e))},{signal:i}),await this.#de(),t}get#ce(){return(this.#l?"added":null===this.#l&&this.guessedText&&"review")||"missing"}finish(){this.#te&&(this.#te.focus({focusVisible:this.#ne}),this.#ne=!1)}isEmpty(){return this.#le?null===this.#l:!this.#l&&!this.#Zt}hasData(){return this.#le?null!==this.#l||!!this.#re:this.isEmpty()}get guessedText(){return this.#re}async setGuessedText(t){null===this.#l&&(this.#re=t,this.#oe=await re._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#de())}toggleAltTextBadge(t=!1){if(!this.#le||this.#l)return this.#ae?.remove(),void(this.#ae=null);if(!this.#ae){const t=this.#ae=document.createElement("div");t.className="noAltTextBadge",this.#r.div.append(t)}this.#ae.classList.toggle("hidden",!t)}serialize(t){let e=this.#l;return t||this.#re!==e||(e=this.#oe),{altText:e,decorative:this.#Zt,guessedText:this.#re,textWithDisclaimer:this.#oe}}get data(){return{altText:this.#l,decorative:this.#Zt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){i&&(this.#re=i,this.#oe=s),this.#l===t&&this.#Zt===e||(n||(this.#l=t,this.#Zt=e),this.#de())}toggle(t=!1){this.#te&&(!t&&this.#se&&(clearTimeout(this.#se),this.#se=null),this.#te.disabled=!t)}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ce}})}destroy(){this.#te?.remove(),this.#te=null,this.#ee=null,this.#ie=null,this.#ae?.remove(),this.#ae=null}async#de(){const t=this.#te;if(!t)return;if(this.#le){if(t.classList.toggle("done",!!this.#l),t.setAttribute("data-l10n-id",re.#he[this.#ce]),this.#ee?.setAttribute("data-l10n-id",re.#he[`${this.#ce}-label`]),!this.#l)return void this.#ie?.remove()}else{if(!this.#l&&!this.#Zt)return t.classList.remove("done"),void this.#ie?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#ie;if(!e){this.#ie=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#r.id}`;const i=100,s=this.#r._uiManager._signal;s.addEventListener("abort",()=>{clearTimeout(this.#se),this.#se=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#se=setTimeout(()=>{this.#se=null,this.#ie.classList.add("show"),this.#r._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:s}),t.addEventListener("mouseleave",()=>{this.#se&&(clearTimeout(this.#se),this.#se=null),this.#ie?.classList.remove("show")},{signal:s})}this.#Zt?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#l),e.parentNode||t.append(e);const i=this.#r.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class oe{#ue=null;#pe=null;#ge=!1;#r=null;#me=null;#fe=null;#be=null;#ye=null;#ve=!1;#Ae=null;constructor(t){this.#r=t}renderForToolbar(){const t=this.#pe=document.createElement("button");return t.className="comment",this.#v(t,!1)}renderForStandalone(){const t=this.#ue=document.createElement("button");t.className="annotationCommentButton";const e=this.#r.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#r._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const s=this.#r.commentButtonColor;s&&(i.backgroundColor=s)}return this.#v(t,!0)}focusButton(){setTimeout(()=>{(this.#ue??this.#pe)?.focus()},0)}onUpdatedColor(){if(!this.#ue)return;const t=this.#r.commentButtonColor;t&&(this.#ue.style.backgroundColor=t),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#ue?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#Ae)return this.#Ae;if(!this.#ue)return null;const{x:t,y:e,height:i}=this.#ue.getBoundingClientRect(),{x:s,y:n,width:a,height:r}=this.#r.parent.boundingClientRect;return[(t-s)/a,(e+i-n)/r]}set commentPopupPositionInLayer(t){this.#Ae=t}hasDefaultPopupPosition(){return null===this.#Ae}removeStandaloneCommentButton(){this.#ue?.remove(),this.#ue=null}removeToolbarCommentButton(){this.#pe?.remove(),this.#pe=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#ue&&(this.#ue.classList.toggle("selected",t),this.#ue.ariaExpanded=e)}#v(t,e){if(!this.#r._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const i=this.#r._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",kt,{signal:i}),e&&(t.addEventListener("focusin",t=>{this.#r._focusEventsAllowed=!1,Mt(t)},{capture:!0,signal:i}),t.addEventListener("focusout",t=>{this.#r._focusEventsAllowed=!0,Mt(t)},{capture:!0,signal:i})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const s=e=>{e.preventDefault(),t===this.#pe?this.edit():this.#r.toggleComment(!0)};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#ge=!0,s(e))},{signal:i}),t.addEventListener("pointerenter",()=>{this.#r.toggleComment(!1,!0)},{signal:i}),t.addEventListener("pointerleave",()=>{this.#r.toggleComment(!1,!1)},{signal:i}),t}edit(t){const e=this.commentPopupPositionInLayer;let i,s;if(e)[i,s]=e;else{[i,s]=this.#r.commentButtonPosition;const{width:t,height:e,x:n,y:a}=this.#r;i=n+i*t,s=a+s*e}const n=this.#r.parent.boundingClientRect,{x:a,y:r,width:o,height:l}=n;this.#r._uiManager.editComment(this.#r,a+i*o,r+s*l,{...t,parentDimensions:n})}finish(){this.#pe&&(this.#pe.focus({focusVisible:this.#ge}),this.#ge=!1)}isDeleted(){return this.#ve||""===this.#be}isEmpty(){return null===this.#be}hasBeenEdited(){return this.isDeleted()||this.#be!==this.#me}serialize(){return this.data}get data(){return{text:this.#be,richText:this.#fe,date:this.#ye,deleted:this.isDeleted()}}set data(t){if(t!==this.#be&&(this.#fe=null),null===t)return this.#be="",void(this.#ve=!0);this.#be=t,this.#ye=new Date,this.#ve=!1}restoreData({text:t,richText:e,date:i}){this.#be=t,this.#fe=e,this.#ye=i,this.#ve=!1}setInitialText(t,e=null){this.#me=t,this.data=t,this.#ye=null,this.#fe=e}shown(){}destroy(){this.#pe?.remove(),this.#pe=null,this.#ue?.remove(),this.#ue=null,this.#be="",this.#fe=null,this.#ye=null,this.#r=null,this.#ge=!1,this.#ve=!1}}class le{#_t;#we=!1;#xe=null;#Ce;#Se;#Te;#Ee;#_e=null;#ke;#Me=null;#De;#Pe=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#_t=t,this.#xe=i,this.#Ce=e,this.#Se=s,this.#Te=n,this.#Ee=a,this.#De=new AbortController,this.#ke=AbortSignal.any([r,this.#De.signal]),t.addEventListener("touchstart",this.#Ie.bind(this),{passive:!1,signal:this.#ke})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Rt.pixelRatio}#Ie(t){if(this.#Ce?.())return;if(1===t.touches.length){if(this.#_e)return;const t=this.#_e=new AbortController,e=AbortSignal.any([this.#ke,t.signal]),i=this.#_t,s={capture:!0,signal:e,passive:!1},n=t=>{"touch"===t.pointerType&&(this.#_e?.abort(),this.#_e=null)};return i.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(Mt(t),n(t))},s),i.addEventListener("pointerup",n,s),void i.addEventListener("pointercancel",n,s)}if(!this.#Pe){this.#Pe=new AbortController;const t=AbortSignal.any([this.#ke,this.#Pe.signal]),e=this.#_t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Fe.bind(this),i);const s=this.#Be.bind(this);e.addEventListener("touchend",s,i),e.addEventListener("touchcancel",s,i),i.capture=!0,e.addEventListener("pointerdown",Mt,i),e.addEventListener("pointermove",Mt,i),e.addEventListener("pointercancel",Mt,i),e.addEventListener("pointerup",Mt,i),this.#Se?.()}if(Mt(t),2!==t.touches.length||this.#xe?.())return void(this.#Me=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#Me={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Fe(t){if(!this.#Me||2!==t.touches.length)return;Mt(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:a,screenY:r}=i,o=this.#Me,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=a-s,m=r-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#we&&Math.abs(b-f)<=le.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=s,o.touch0Y=n,o.touch1X=a,o.touch1Y=r,!this.#we)return void(this.#we=!0);const y=[(s+a)/2,(n+r)/2];this.#Te?.(y,b,f)}#Be(t){t.touches.length>=2||(this.#Pe&&(this.#Pe.abort(),this.#Pe=null,this.#Ee?.()),this.#Me&&(Mt(t),this.#Me=null,this.#we=!1))}destroy(){this.#De?.abort(),this.#De=null,this.#_e?.abort(),this.#_e=null}}class he{#Le=null;#Re=null;#l=null;#h=null;#ue=null;#Oe=!1;#Ne=null;#He="";#Ue=null;#ze=null;#Ge=null;#$e=null;#je=null;#We="";#Ve=!1;#Ke=null;#Xe=!1;#qe=!1;#Ye=!1;#Qe=null;#Je=0;#Ze=0;#ti=null;#ei=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#ii=!1;#si=he._zIndex++;static _borderLineWidth=-1;static _colorManager=new ne;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=he.prototype._resizeWithKeyboard,e=ae.TRANSLATE_SMALL,i=ae.TRANSLATE_BIG;return Q(this,"_resizerKeyboardManager",new se([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],he.prototype._stopResizingWithKeyboard]]))}constructor(t){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,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],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}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Q(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new ce({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(he._l10n??=t,he._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),he._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==he._borderLineWidth)return;const i=getComputedStyle(document.documentElement);he._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){V("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ii}set _isDraggable(t){this.#ii=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}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.#si}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#ni(),this.#$e?.remove(),this.#$e=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ve?this.#Ve=!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.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/n,this.y=(e+s)/a,this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone)return void delete this.isClone;const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s),this._onTranslated()}#ai([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#ai(this.parentDimensions,t,e)}translateInPage(t,e){this.#Ke||=[this.x,this.y,this.width,this.height],this.#ai(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Ke||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;if(this.x+=t/s,this.y+=e/n,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:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o,r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`,h.top=`${(100*r).toFixed(2)}%`,this._onTranslating(a,r),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Ke&&(this.#Ke[0]!==this.x||this.#Ke[1]!==this.y)}get _hasBeenResized(){return!!this.#Ke&&(this.#Ke[2]!==this.width||this.#Ke[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=he,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:a,width:r,height:o}=this;if(r*=i,o*=s,n*=i,a*=s,this._mustFixPosition)switch(t){case 0:n=mt(n,0,i-r),a=mt(a,0,s-o);break;case 90:n=mt(n,0,i-o),a=mt(a,r,s);break;case 180:n=mt(n,r,i),a=mt(a,o,s);break;case 270:n=mt(n,o,i),a=mt(a,0,s-r)}this.x=n/=i,this.y=a/=s;const[l,h]=this.getBaseTranslation();n+=l,a+=h,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#ri(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return he.#ri(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return he.#ri(t,e,360-this.parentRotation)}#oi(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,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#li(){if(this.#Ue)return;this.#Ue=document.createElement("div"),this.#Ue.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 i of t){const t=document.createElement("div");this.#Ue.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#hi.bind(this,i),{signal:e}),t.addEventListener("contextmenu",kt,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#Ue)}#hi(t,e){e.preventDefault();const{isMac:i}=rt.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#l?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1,this.#ze=[e.screenX,e.screenY];const n=new AbortController,a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#ci.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",Mt,{passive:!1,signal:a}),window.addEventListener("contextmenu",kt,{signal:a}),this.#Ge={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#l?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=r,this.div.style.cursor=o,this.#di()};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}#ui(t,e,i,s){this.width=i,this.height=s,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#di(){if(!this.#Ge)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#Ge;this.#Ge=null;const n=this.x,a=this.y,r=this.width,o=this.height;n===t&&a===e&&r===i&&o===s||this.addCommands({cmd:this.#ui.bind(this,n,a,r,o),undo:this.#ui.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#ci(t,e){const[i,s]=this.parentDimensions,n=this.x,a=this.y,r=this.width,o=this.height,l=he.MIN_SIZE/i,h=he.MIN_SIZE/s,c=this.#oi(this.rotation),d=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],u=this.#oi(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(r,o),y=g(r,o);let v=d(...y);const A=he._round(n+v[0]),w=he._round(a+v[1]);let x,C,S=1,T=1;if(e.fromKeyboard)({deltaX:x,deltaY:C}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#ze;[x,C]=this.screenToPageTranslation(t-s,i-n),this.#ze[0]=t,this.#ze[1]=i}var E,_;if([x,C]=(E=x/i,_=C/s,[u[0]*E+u[2]*_,u[1]*E+u[3]*_]),m){const t=Math.hypot(r,o);S=T=Math.max(Math.min(Math.hypot(y[0]-b[0]-x,y[1]-b[1]-C)/t,1/r,1/o),l/r,h/o)}else f?S=mt(Math.abs(y[0]-b[0]-x),l,1)/r:T=mt(Math.abs(y[1]-b[1]-C),h,1)/o;const k=he._round(r*S),M=he._round(o*T);v=d(...g(k,M));const D=A-v[0],P=w-v[1];this.#Ke||=[this.x,this.y,this.width,this.height],this.width=k,this.height=M,this.x=D,this.y=P,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#l?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#qe)return this._editToolbar;this._editToolbar=new qt(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#l?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#l||(re.initialize(he._l10n),this.#l=new re(this),this.#Le&&(this.#l.data=this.#Le,this.#Le=null)),this.#l}get altTextData(){return this.#l?.data}set altTextData(t){this.#l&&(this.#l.data=t)}get guessedAltText(){return this.#l?.guessedText}async setGuessedAltText(t){await(this.#l?.setGuessedText(t))}serializeAltText(t){return this.#l?.serialize(t)}hasAltText(){return!!this.#l&&!this.#l.isEmpty()}hasAltTextData(){return this.#l?.hasData()??!1}focusCommentButton(){this.#h?.focusButton()}addCommentButton(){return this.canAddComment?this.#h||=new oe(this):null}addStandaloneCommentButton(){this._uiManager.hasCommentManager()&&(this.#ue?this._uiManager.isEditingMode()&&this.#ue.classList.remove("hidden"):this.hasComment&&(this.#ue=this.#h.renderForStandalone(),this.div.append(this.#ue)))}removeStandaloneCommentButton(){this.#h.removeStandaloneCommentButton(),this.#ue=null}hideStandaloneCommentButton(){this.#ue?.classList.add("hidden")}get comment(){if(!this.#h)return null;const{data:{richText:t,text:e,date:i,deleted:s}}=this.#h;return{text:e,richText:t,date:i,deleted:s,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#h||=new oe(this),"object"==typeof t&&null!==t?this.#h.restoreData(t):this.#h.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;if(this.#h||=new oe(this),this.#h.setInitialText(t,i),!this.annotationElementId)return;const s=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);s&&this.updateFromAnnotationLayer(s)}get hasEditedComment(){return this.#h?.hasBeenEdited()}get hasDeletedComment(){return this.#h?.isDeleted()}get hasComment(){return!!this.#h&&!this.#h.isEmpty()&&!this.#h.isDeleted()}async editComment(t){this.#h||=new oe(this),this.#h.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#h.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,s]=t.rect,[n]=this.pageDimensions,[a]=this.pageTranslation,r=a+n+1,o=s-i,l=r+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[r,o,l,s]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#h.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#Oe?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#pi();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[s,n]=this.getInitialTranslation();return this.translate(s,n),Jt(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ei||=new le({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#gi.bind(this),onPinching:this.#mi.bind(this),onPinchEnd:this.#fi.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#gi(){this.#Ge={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#l?.toggle(!1),this.parent.togglePointerEvents(!1)}#mi(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#oi(this.rotation),a=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[r,o]=this.parentDimensions,l=this.x,h=this.y,c=this.width,d=this.height,u=he.MIN_SIZE/r,p=he.MIN_SIZE/o;s=Math.max(Math.min(s,1/c,1/d),u/c,p/d);const g=he._round(c*s),m=he._round(d*s);if(g===c&&m===d)return;this.#Ke||=[l,h,c,d];const f=a(c/2,d/2),b=he._round(l+f[0]),y=he._round(h+f[1]),v=a(g/2,m/2);this.x=b-v[0],this.y=y-v[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#fi(){this.#l?.toggle(!0),this.parent.togglePointerEvents(!0),this.#di()}pointerdown(t){const{isMac:e}=rt.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#Ve=!0,this._isDraggable?this.#bi(t):this.#yi(t))}#yi(t){const{isMac:e}=rt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#bi(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),a={capture:!0,passive:!1,signal:n},r=t=>{s.abort(),this.#Ne=null,this.#Ve=!1,this._uiManager.endDragSession()||this.#yi(t),i&&this._onStopDragging()};e&&(this.#Je=t.clientX,this.#Ze=t.clientY,this.#Ne=t.pointerId,this.#He=t.pointerType,window.addEventListener("pointermove",t=>{i||(i=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#Ne)return void Mt(t);const[a,r]=this.screenToPageTranslation(e-this.#Je,s-this.#Ze);this.#Je=e,this.#Ze=s,this._uiManager.dragSelectedEditors(a,r)},a),window.addEventListener("touchmove",Mt,a),window.addEventListener("pointerdown",t=>{t.pointerType===this.#He&&(this.#ei||t.isPrimary)&&r(t),Mt(t)},a));const o=t=>{this.#Ne&&this.#Ne!==t.pointerId?Mt(t):r(t)};window.addEventListener("pointerup",o,{signal:n}),window.addEventListener("blur",o,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Qe&&clearTimeout(this.#Qe),this.#Qe=setTimeout(()=>{this.#Qe=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/s,h=e/s,c=this.x*n,d=this.y*a,u=this.width*n,p=this.height*a;switch(i){case 0:return[c+l+r,a-d-h-p+o,c+l+u+r,a-d-h+o];case 90:return[c+h+r,a-d+l+o,c+h+p+r,a-d+l+u+o];case 180:return[c-l-u+r,a-d+h+o,c-l+r,a-d+h+p+o];case 270:return[c-h-p+r,a-d-l-u+o,c-h+r,a-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,a]=t,r=n-i,o=a-s;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-s,o,r];case 180:return[n,e-s,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&he._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#h?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:s,deleted:n,richText:a},uid:r,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:r,pageIndex:o,rect:this.getPDFRect(),richText:a,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!n,color:e,opacity:s}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#qe=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#qe=!1,!0)}isInEditMode(){return this.#qe}shouldGetKeyboardEvents(){return this.#Ye}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:a}=window;return e<a&&s>0&&t<n&&i>0}#pi(){if(this.#je||!this.div)return;this.#je=new AbortController;const t=this._uiManager.combinedSignal(this.#je);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#pi()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:i.getId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});s.rotation=t.rotation,s.#Le=t.accessibilityData,s._isCopy=t.isCopy||!1;const[n,a]=s.pageDimensions,[r,o,l,h]=s.getRectInCurrentCoords(t.rect,a);return s.x=r/n,s.y=o/a,s.width=l/n,s.height=h/a,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#je?.abort(),this.#je=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#Qe&&(clearTimeout(this.#Qe),this.#Qe=null),this.#ni(),this.removeEditToolbar(),this.#ti){for(const t of this.#ti.values())clearTimeout(t);this.#ti=null}this.parent=null,this.#ei?.destroy(),this.#ei=null,this.#$e?.remove(),this.#$e=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#li(),this.#Ue.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,s,n,a]=this.getPDFRect();return[he._round(i+(n-i)*t),he._round(s+(a-s)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#h.commentPopupPositionInLayer}set commentPopupPosition(t){this.#h.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#h.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#h.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#h?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#Ge={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Ue.children;if(!this.#Re){this.#Re=Array.from(e);const t=this.#vi.bind(this),i=this.#Ai.bind(this),s=this._uiManager._signal;for(const e of this.#Re){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#wi.bind(this,n),{signal:s}),e.setAttribute("data-l10n-id",he._l10nResizer[n])}}const i=this.#Re[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Re.length/4);if(n!==s){if(n<s)for(let t=0;t<s-n;t++)this.#Ue.append(this.#Ue.firstElementChild);else if(n>s)for(let t=0;t<n-s;t++)this.#Ue.firstElementChild.before(this.#Ue.lastElementChild);let t=0;for(const i of e){const e=this.#Re[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",he._l10nResizer[e])}}this.#xi(0),this.#Ye=!0,this.#Ue.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#vi(t){he._resizerKeyboardManager.exec(this,t)}#Ai(t){this.#Ye&&t.relatedTarget?.parentNode!==this.#Ue&&this.#ni()}#wi(t){this.#We=this.#Ye?t:""}#xi(t){if(this.#Re)for(const e of this.#Re)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Ye&&this.#ci(this.#We,{deltaX:t,deltaY:e,fromKeyboard:!0})}#ni(){this.#Ye=!1,this.#xi(-1),this.#di()}_stopResizingWithKeyboard(){this.#ni(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#l?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#Ue?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#l?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Xe}set isEditing(t){this.#Xe=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}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.#ti||=new Map;const{action:e}=t;let i=this.#ti.get(e);return i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#ti.delete(e),0===this.#ti.size&&(this.#ti=null)},he._telemetryTimeout),void this.#ti.set(e,i)}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.#Oe=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Oe=!0}updateFakeAnnotationElement(t){if(this.#$e||this.deleted)return this.deleted?(this.#$e.remove(),void(this.#$e=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#$e.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#$e=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;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{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class ce extends he{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const de=3285377520,ue=4294901760,pe=65535;class ge{constructor(t){this.h1=t?4294967295&t:de,this.h2=t?4294967295&t:de}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,n=t.length;s<n;s++){const n=t.charCodeAt(s);n<=255?e[i++]=n:(e[i++]=n>>>8,e[i++]=255&n)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const s=i>>2,n=i-4*s,a=new Uint32Array(e.buffer,0,s);let r=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<s;t++)1&t?(r=a[t],r=r*c&ue|r*u&pe,r=r<<15|r>>>17,r=r*d&ue|r*p&pe,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*c&ue|o*u&pe,o=o<<15|o>>>17,o=o*d&ue|o*p&pe,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,n){case 3:r^=e[4*s+2]<<16;case 2:r^=e[4*s+1]<<8;case 1:r^=e[4*s],r=r*c&ue|r*u&pe,r=r<<15|r>>>17,r=r*d&ue|r*p&pe,1&s?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&ue|36045*t&pe,e=4283543511*e&ue|(2950163797*(e<<16|t>>>16)&ue)>>>16,t^=e>>>1,t=444984403*t&ue|60499*t&pe,e=3301882366*e&ue|(3120437893*(e<<16|t>>>16)&ue)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const me=Object.freeze({map:null,hash:"",transfer:void 0});class fe{#Ci=!1;#Si=null;#Ti=null;#Ei=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const i=this.#Ei.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ei.get(t)}remove(t){const e=this.#Ei.get(t);void 0!==e&&(e instanceof he&&this.#Ti.delete(e.annotationElementId),this.#Ei.delete(t),0===this.#Ei.size&&this.resetModified(),this.#Ei.values().some(t=>t instanceof he)||this.onAnnotationEditor?.(null))}setValue(t,e){const i=this.#Ei.get(t);let s=!1;if(void 0!==i)for(const[t,n]of Object.entries(e))i[t]!==n&&(s=!0,i[t]=n);else s=!0,this.#Ei.set(t,e);s&&this.#_i(),e instanceof he&&((this.#Ti||=new Map).set(e.annotationElementId,e),this.onAnnotationEditor?.(e.constructor._type))}has(t){return this.#Ei.has(t)}get size(){return this.#Ei.size}#_i(){this.#Ci||(this.#Ci=!0,this.onSetModified?.())}resetModified(){this.#Ci&&(this.#Ci=!1,this.onResetModified?.())}get print(){return new be(this)}get serializable(){if(0===this.#Ei.size)return me;const t=new Map,e=new ge,i=[],s=Object.create(null);let n=!1;for(const[i,a]of this.#Ei){const r=a instanceof he?a.serialize(!1,s):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),n||=!!r.bitmap)}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:me}get editorStats(){let t=null;const e=new Map;let i=0,s=0;for(const n of this.#Ei.values()){if(!(n instanceof he)){n.popup&&(n.popup.deleted?s+=1:i+=1);continue}n.isCommentDeleted?s+=1:n.hasEditedComment&&(i+=1);const a=n.telemetryFinalData;if(!a)continue;const{type:r}=a;e.has(r)||e.set(r,Object.getPrototypeOf(n).constructor),t||=Object.create(null);const o=t[r]||=new Map;for(const[t,e]of Object.entries(a)){if("type"===t)continue;const i=o.getOrInsertComputed(t,pt);i.set(e,(i.get(e)??0)+1)}}if((s>0||i>0)&&(t||=Object.create(null),t.comments={deleted:s,edited:i}),!t)return null;for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Si=null}updateEditor(t,e){const i=this.#Ti?.get(t);return!!i&&(i.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#Ti?.get(t)||null}get modifiedIds(){if(this.#Si)return this.#Si;const t=[];if(this.#Ti)for(const e of this.#Ti.values())e.serialize()&&t.push(e.annotationElementId);let e="";if(t.length){const i=new ge;i.update(t.join(",")),e=i.hexdigest()}return this.#Si={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#Ei.entries()}}class be extends fe{#ki=me;constructor(t){super();const{serializable:e}=t;if(e===me)return;const{map:i,hash:s,transfer:n}=e,a=structuredClone(i,n?{transfer:n}:null);this.#ki={map:a,hash:s,transfer:[]}}get print(){V("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ki}get modifiedIds(){return Q(this,"modifiedIds",{ids:new Set,hash:""})}}const ye="__forcedDependency",{floor:ve,ceil:Ae}=Math;function we(t,e,i,s,n,a){t[4*e+0]=Math.min(t[4*e+0],i),t[4*e+1]=Math.min(t[4*e+1],s),t[4*e+2]=Math.max(t[4*e+2],n),t[4*e+3]=Math.max(t[4*e+3],a)}const xe=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class Ce{#Mi;#Di;constructor(t,e){this.#Mi=t,this.#Di=e}get length(){return this.#Mi.length}isEmpty(t){return this.#Mi[t]===xe}minX(t){return this.#Di[4*t+0]/256}minY(t){return this.#Di[4*t+1]/256}maxX(t){return(this.#Di[4*t+2]+1)/256}maxY(t){return(this.#Di[4*t+3]+1)/256}}const Se=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class Te{#Pi=[[1,0,0,1,0,0]];#Ii=[-1/0,-1/0,1/0,1/0];#Fi=new Float64Array(e);_pendingBBoxIdx=-1;#Bi;#Li;#Ri;#Mi;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#Bi=t.width,this.#Li=t.height,this.#Oi(e)}growOperationsCount(t){t>=this.#Mi.length&&this.#Oi(t,this.#Mi)}#Oi(t,e){const i=new ArrayBuffer(4*t);this.#Ri=new Uint8ClampedArray(i),this.#Mi=new Uint32Array(i),e&&e.length>0?(this.#Mi.set(e),this.#Mi.fill(xe,e.length)):this.#Mi.fill(xe)}get clipBox(){return this.#Ii}save(t){return this.#Ii={__proto__:this.#Ii},this._savesStack.push(t),this}restore(t,e){const i=Object.getPrototypeOf(this.#Ii);if(null===i)return this;this.#Ii=i;const s=this._savesStack.pop();return void 0!==s&&(e?.(s,t),this.#Mi[t]=this.#Mi[s]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const i=this._savesStack.pop();return void 0!==i&&(e?.(i,t),this.#Mi[t]=this.#Mi[i]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,e){const i=this._markedContentStack.pop();return void 0!==i&&(e?.(i,t),this.#Mi[t]=this.#Mi[i]),this}pushBaseTransform(t){return this.#Pi.push(ot.multiplyByDOMMatrix(this.#Pi.at(-1),t.getTransform())),this}popBaseTransform(){return this.#Pi.length>1&&this.#Pi.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#Fi.set(e,0)),this}recordClipBox(t,i,s,n,a,r){const o=ot.multiplyByDOMMatrix(this.#Pi.at(-1),i.getTransform()),l=e.slice();ot.axialAlignedBoundingBox([s,a,n,r],o,l);const h=ot.intersect(this.#Ii,l);return h?(this.#Ii[0]=h[0],this.#Ii[1]=h[1],this.#Ii[2]=h[2],this.#Ii[3]=h[3]):(this.#Ii[0]=this.#Ii[1]=1/0,this.#Ii[2]=this.#Ii[3]=-1/0),this}recordBBox(t,i,s,n,a,r){const o=this.#Ii;if(o[0]===1/0)return this;const l=ot.multiplyByDOMMatrix(this.#Pi.at(-1),i.getTransform());if(o[0]===-1/0)return ot.axialAlignedBoundingBox([s,a,n,r],l,this.#Fi),this;const h=e.slice();return ot.axialAlignedBoundingBox([s,a,n,r],l,h),this.#Fi[0]=mt(h[0],o[0],this.#Fi[0]),this.#Fi[1]=mt(h[1],o[1],this.#Fi[1]),this.#Fi[2]=mt(h[2],this.#Fi[2],o[2]),this.#Fi[3]=mt(h[3],this.#Fi[3],o[3]),this}recordFullPageBBox(t){return this.#Fi[0]=Math.max(0,this.#Ii[0]),this.#Fi[1]=Math.max(0,this.#Ii[1]),this.#Fi[2]=Math.min(this.#Bi,this.#Ii[2]),this.#Fi[3]=Math.min(this.#Li,this.#Ii[3]),this}recordOperation(t,e=!1,i){if(this._pendingBBoxIdx!==t)return this;const s=ve(256*this.#Fi[0]/this.#Bi),n=ve(256*this.#Fi[1]/this.#Li),a=Ae(256*this.#Fi[2]/this.#Bi),r=Ae(256*this.#Fi[3]/this.#Li);if(we(this.#Ri,t,s,n,a,r),i)for(const e of i)for(const i of e)i!==t&&we(this.#Ri,i,s,n,a,r);return e||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#Ii[0]=Math.max(this.#Ii[0],this.#Fi[0]),this.#Ii[1]=Math.max(this.#Ii[1],this.#Fi[1]),this.#Ii[2]=Math.min(this.#Ii[2],this.#Fi[2]),this.#Ii[3]=Math.min(this.#Ii[3],this.#Fi[3])),this}take(){return new Ce(this.#Mi,this.#Ri)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,i,s=1,n=0,a=0,r){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class Ee{#Ni={__proto__:null};#Hi={__proto__:null,transform:[],moveText:[],sameLineText:[],[ye]:[]};#Ui=new Map;#zi=new Set;#Gi=new Map;#$i;#ji;#Wi;constructor(t,e=!1){this.#Wi=t,e&&(this.#$i=new Map,this.#ji=(t,e)=>{Se(this.#$i,e).dependencies.add(t)})}get clipBox(){return this.#Wi.clipBox}growOperationsCount(t){this.#Wi.growOperationsCount(t)}save(t){return this.#Ni={__proto__:this.#Ni},this.#Hi={__proto__:this.#Hi,transform:{__proto__:this.#Hi.transform},moveText:{__proto__:this.#Hi.moveText},sameLineText:{__proto__:this.#Hi.sameLineText},[ye]:{__proto__:this.#Hi[ye]}},this.#Wi.save(t),this}restore(t){this.#Wi.restore(t,this.#ji);const e=Object.getPrototypeOf(this.#Ni);return null===e||(this.#Ni=e,this.#Hi=Object.getPrototypeOf(this.#Hi)),this}recordOpenMarker(t){return this.#Wi.recordOpenMarker(t,this.#ji),this}getOpenMarker(){return this.#Wi.getOpenMarker()}recordCloseMarker(t){return this.#Wi.recordCloseMarker(t,this.#ji),this}beginMarkedContent(t){return this.#Wi.beginMarkedContent(t),this}endMarkedContent(t){return this.#Wi.endMarkedContent(t,this.#ji),this}pushBaseTransform(t){return this.#Wi.pushBaseTransform(t),this}popBaseTransform(){return this.#Wi.popBaseTransform(),this}recordSimpleData(t,e){return this.#Ni[t]=e,this}recordIncrementalData(t,e){return this.#Hi[t].push(e),this}resetIncrementalData(t,e){return this.#Hi[t].length=0,this}recordNamedData(t,e){return this.#Ui.set(t,e),this}recordSimpleDataFromNamed(t,e,i){this.#Ni[t]=this.#Ui.get(e)??i}recordFutureForcedDependency(t,e){return this.recordIncrementalData(ye,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ni&&this.recordFutureForcedDependency(e,this.#Ni[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#zi)this.recordFutureForcedDependency(ye,t);return this}resetBBox(t){return this.#Wi.resetBBox(t),this}recordClipBox(t,e,i,s,n,a){return this.#Wi.recordClipBox(t,e,i,s,n,a),this}recordBBox(t,e,i,s,n,a){return this.#Wi.recordBBox(t,e,i,s,n,a),this}recordCharacterBBox(t,e,i,s=1,n=0,a=0,r){const o=i.bbox;let l,h;if(o&&(l=o[2]!==o[0]&&o[3]!==o[1]&&this.#Gi.get(i),!1!==l&&(h=[0,0,0,0],ot.axialAlignedBoundingBox(o,i.fontMatrix,h),1===s&&0===n&&0===a||function(t,e,i,s,n){let a;t?(t<0&&(a=n[0],n[0]=n[2],n[2]=a),n[0]*=t,n[2]*=t,e<0&&(a=n[1],n[1]=n[3],n[3]=a),n[1]*=e,n[3]*=e):n.fill(0),n[0]+=i,n[1]+=s,n[2]+=i,n[3]+=s}(s,-s,n,a,h),l)))return this.recordBBox(t,e,h[0],h[2],h[1],h[3]);if(!r)return this.recordFullPageBBox(t);const c=r();return o&&h&&void 0===l&&(l=h[0]<=n-c.actualBoundingBoxLeft&&h[2]>=n+c.actualBoundingBoxRight&&h[1]<=a-c.actualBoundingBoxAscent&&h[3]>=a+c.actualBoundingBoxDescent,this.#Gi.set(i,l),l)?this.recordBBox(t,e,h[0],h[2],h[1],h[3]):this.recordBBox(t,e,n-c.actualBoundingBoxLeft,n+c.actualBoundingBoxRight,a-c.actualBoundingBoxAscent,a+c.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#Wi.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#Ni[t]}recordDependencies(t,e){const i=this.#zi,s=this.#Ni,n=this.#Hi;for(const t of e)t in this.#Ni?i.add(s[t]):t in n&&n[t].forEach(i.add,i);return this}recordNamedDependency(t,e){return this.#Ui.has(e)&&this.#zi.add(this.#Ui.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[ye]),this.#$i){const e=Se(this.#$i,t),{dependencies:i}=e;this.#zi.forEach(i.add,i),this.#Wi._savesStack.forEach(i.add,i),this.#Wi._markedContentStack.forEach(i.add,i),i.delete(t),e.isRenderingOperation=!0}const i=!e&&t===this.#Wi._pendingBBoxIdx;return this.#Wi.recordOperation(t,e,[this.#zi,this.#Wi._savesStack,this.#Wi._markedContentStack]),i&&this.#zi.clear(),this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#zi);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){const i=!e&&t===this.#Wi._pendingBBoxIdx;return this.#Wi.bboxToClipBoxDropOperation(t),i&&this.#zi.clear(),this}take(){return this.#Gi.clear(),this.#Wi.take()}takeDebugMetadata(){return this.#$i}}class _e{#Vi;#Ki;#Xi;#qi=0;#Yi=0;constructor(t,e,i){if(t instanceof _e&&t.#Xi===!!i)return t;this.#Vi=t,this.#Ki=e,this.#Xi=!!i}get clipBox(){return this.#Vi.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#Yi++,this.#Vi.save(this.#Ki),this}restore(t){return this.#Yi>0&&(this.#Vi.restore(this.#Ki),this.#Yi--),this}recordOpenMarker(t){return this.#qi++,this}getOpenMarker(){return this.#qi>0?this.#Ki:this.#Vi.getOpenMarker()}recordCloseMarker(t){return this.#qi--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#Vi.pushBaseTransform(t),this}popBaseTransform(){return this.#Vi.popBaseTransform(),this}recordSimpleData(t,e){return this.#Vi.recordSimpleData(t,this.#Ki),this}recordIncrementalData(t,e){return this.#Vi.recordIncrementalData(t,this.#Ki),this}resetIncrementalData(t,e){return this.#Vi.resetIncrementalData(t,this.#Ki),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this.#Vi.recordSimpleDataFromNamed(t,e,this.#Ki),this}recordFutureForcedDependency(t,e){return this.#Vi.recordFutureForcedDependency(t,this.#Ki),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#Vi.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#Vi.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#Xi||this.#Vi.resetBBox(this.#Ki),this}recordClipBox(t,e,i,s,n,a){return this.#Xi||this.#Vi.recordClipBox(this.#Ki,e,i,s,n,a),this}recordBBox(t,e,i,s,n,a){return this.#Xi||this.#Vi.recordBBox(this.#Ki,e,i,s,n,a),this}recordCharacterBBox(t,e,i,s,n,a,r){return this.#Xi||this.#Vi.recordCharacterBBox(this.#Ki,e,i,s,n,a,r),this}recordFullPageBBox(t){return this.#Xi||this.#Vi.recordFullPageBBox(this.#Ki),this}getSimpleIndex(t){return this.#Vi.getSimpleIndex(t)}recordDependencies(t,e){return this.#Vi.recordDependencies(this.#Ki,e),this}recordNamedDependency(t,e){return this.#Vi.recordNamedDependency(this.#Ki,e),this}recordOperation(t){return this.#Vi.recordOperation(this.#Ki,!0),this}recordShowTextOperation(t){return this.#Vi.recordShowTextOperation(this.#Ki,!0),this}bboxToClipBoxDropOperation(t){return this.#Xi||this.#Vi.bboxToClipBoxDropOperation(this.#Ki,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const ke=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],Me=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],De=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],Pe=["filter","fillColor","fillAlpha"],Ie=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],Fe=["transform"],Be=["transform","fillColor"];class Le{#Bi;#Li;#Qi=4;#Ji=0;#Di=new Le.#Zi(6*this.#Qi);static#Zi=rt.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Bi=t.width,this.#Li=t.height}record(t,i,s,n){if(this.#Ji===this.#Qi){this.#Qi*=2;const t=new Le.#Zi(6*this.#Qi);t.set(this.#Di),this.#Di=t}const a=Ft(t);let r;if(n[0]!==1/0){const t=e.slice();ot.axialAlignedBoundingBox([0,-s,i,0],a,t);const o=ot.intersect(n,t);if(!o)return;const[l,h,c,d]=o;if(l!==t[0]||h!==t[1]||c!==t[2]||d!==t[3]){const t=Math.atan2(a[1],a[0]),e=Math.abs(Math.sin(t)),i=Math.abs(Math.cos(t));if(e<1e-6||i<1e-6||Math.abs(e-i)<1e-6)r=[l,h,l,d,c,h];else{const t=c-l,s=d-h,n=e*e,a=i*i,o=i*e,u=a-n,p=(s*a-t*o)/u;r=[l+(s*o-t*n)/u,h,l,h+p,c,d-p]}}}r||(r=[0,-s,0,0,i,-s],ot.applyTransform(r,a,0),ot.applyTransform(r,a,2),ot.applyTransform(r,a,4)),r[0]/=this.#Bi,r[1]/=this.#Li,r[2]/=this.#Bi,r[3]/=this.#Li,r[4]/=this.#Bi,r[5]/=this.#Li,this.#Di.set(r,6*this.#Ji),this.#Ji++}take(){return this.#Di.subarray(0,6*this.#Ji)}}class Re{#ts=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.#ts.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#ts.has(t.loadedName)){if(K(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:s,style:n}=t,a=new FontFace(e,s,n);this.addNativeFontFace(a);try{await a.load(),this.#ts.add(e),i?.(t)}catch{W(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}V("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(i){throw W(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return Q(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return Q(this,"isSyncFontLoadingSupported",t||rt.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(K(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return Q(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let n,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=s(c,976,h.length,h);const d=1482184792;let u=i(c,16);for(n=0,a=h.length-3;n<a;n+=4)u=u-d+i(h,n)|0;var p;n<h.length&&(u=u-d+i(h+"XXX",n)|0),c=s(c,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));const g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(c)});`}}`;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,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return W("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,()=>{m.remove(),e.complete()})}}class Oe{compiledGlyphs=Object.create(null);#es;constructor(t,e=null,i,s){this.#es=t,this._inspectFont=e,i&&(this.charProcOperatorList=i),s&&Object.assign(this,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=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){W(`getPathGenerator - ignoring character: "${t}".`)}const n=Xt(s?.path);return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=n}get black(){return this.#es.black}get bold(){return this.#es.bold}get disableFontFace(){return this.#es.disableFontFace}set disableFontFace(t){Q(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#es.fontExtraProperties}get isInvalidPDFjsFont(){return this.#es.isInvalidPDFjsFont}get isType3Font(){return this.#es.isType3Font}get italic(){return this.#es.italic}get missingFile(){return this.#es.missingFile}get remeasure(){return this.#es.remeasure}get vertical(){return this.#es.vertical}get ascent(){return this.#es.ascent}get defaultWidth(){return this.#es.defaultWidth}get descent(){return this.#es.descent}get bbox(){return this.#es.bbox}get fontMatrix(){return this.#es.fontMatrix}get fallbackName(){return this.#es.fallbackName}get loadedName(){return this.#es.loadedName}get mimetype(){return this.#es.mimetype}get name(){return this.#es.name}get data(){return this.#es.data}clearData(){this.#es.clearData()}get cssFontInfo(){return this.#es.cssFontInfo}get systemFontInfo(){return this.#es.systemFontInfo}get defaultVMetrics(){return this.#es.defaultVMetrics}}class Ne{static strings=["fontFamily","fontWeight","italicAngle"]}class He{static strings=["css","loadedName","baseFontName","src"]}class Ue{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class ze{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class Ge{#is;#ss=new TextDecoder;#ns;constructor(t){this.#is=t,this.#ns=new DataView(t)}#as(t){K(t<Ne.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#ns.getUint32(e)+4;const i=this.#ns.getUint32(e);return this.#ss.decode(new Uint8Array(this.#is,e+4,i))}get fontFamily(){return this.#as(0)}get fontWeight(){return this.#as(1)}get italicAngle(){return this.#as(2)}}class $e{#is;#ss=new TextDecoder;#ns;constructor(t){this.#is=t,this.#ns=new DataView(t)}get guessFallback(){return 0!==this.#ns.getUint8(0)}#as(t){K(t<He.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#ns.getUint32(e)+4;const i=this.#ns.getUint32(e);return this.#ss.decode(new Uint8Array(this.#is,e+4,i))}get css(){return this.#as(0)}get loadedName(){return this.#as(1)}get baseFontName(){return this.#as(2)}get src(){return this.#as(3)}get style(){let t=1;t+=4+this.#ns.getUint32(t);const e=this.#ns.getUint32(t),i=this.#ss.decode(new Uint8Array(this.#is,t+4,e));t+=4+e;const s=this.#ns.getUint32(t);return{style:i,weight:this.#ss.decode(new Uint8Array(this.#is,t+4,s))}}}class je{#is;#ss=new TextDecoder;#ns;constructor({buffer:t,extra:e}){this.#is=t,this.#ns=new DataView(t),e&&Object.assign(this,e)}#rs(t){K(t<Ue.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,s=this.#ns.getUint8(e)>>i&3;return 0===s?void 0:2===s}get black(){return this.#rs(0)}get bold(){return this.#rs(1)}get disableFontFace(){return this.#rs(2)}get fontExtraProperties(){return this.#rs(3)}get isInvalidPDFjsFont(){return this.#rs(4)}get isType3Font(){return this.#rs(5)}get italic(){return this.#rs(6)}get missingFile(){return this.#rs(7)}get remeasure(){return this.#rs(8)}get vertical(){return this.#rs(9)}#os(t){return K(t<Ue.numbers.length,"Invalid number index"),this.#ns.getFloat64(Ue.OFFSET_NUMBERS+8*t)}get ascent(){return this.#os(0)}get defaultWidth(){return this.#os(1)}get descent(){return this.#os(2)}#ls(t,e,i,s){const n=this.#ns.getUint8(t);if(0===n)return;K(n===e,"Invalid array length."),t+=1;const a=new Array(n);for(let e=0;e<n;e++)a[e]=this.#ns[i](t,!0),t+=s;return a}get bbox(){return this.#ls(Ue.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#ls(Ue.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#ls(Ue.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#as(t){K(t<Ue.strings.length,"Invalid string index");let e=Ue.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#ns.getUint32(e)+4;const i=this.#ns.getUint32(e);return this.#ss.decode(new Uint8Array(this.#is,e+4,i))}get fallbackName(){return this.#as(0)}get loadedName(){return this.#as(1)}get mimetype(){return this.#as(2)}get name(){return this.#as(3)}#hs(){let t=Ue.OFFSET_STRINGS;t+=4+this.#ns.getUint32(t);t+=4+this.#ns.getUint32(t);t+=4+this.#ns.getUint32(t);return{offset:t,length:this.#ns.getUint32(t)}}get data(){const{offset:t,length:e}=this.#hs();return 0===e?void 0:new Uint8Array(this.#is,t+4,e)}clearData(){const{offset:t,length:e}=this.#hs();0!==e&&(this.#ns.setUint32(t,0),this.#is=new Uint8Array(this.#is,0,t+4).slice().buffer,this.#ns=new DataView(this.#is))}get cssFontInfo(){let t=Ue.OFFSET_STRINGS;t+=4+this.#ns.getUint32(t);t+=4+this.#ns.getUint32(t);const e=this.#ns.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#is,t+4,e)),new Ge(i.buffer)}get systemFontInfo(){let t=Ue.OFFSET_STRINGS;t+=4+this.#ns.getUint32(t);const e=this.#ns.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#is,t+4,e)),new $e(i.buffer)}}class We{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){const t=this.view,i=this.data[ze.KIND],s=!!this.data[ze.HAS_BBOX],n=!!this.data[ze.HAS_BACKGROUND],a=t.getUint32(ze.N_COORD,!0),r=t.getUint32(ze.N_COLOR,!0),o=t.getUint32(ze.N_STOP,!0);let l=20;const h=new Float32Array(this.buffer,l,2*a);l+=8*a;const c=new Uint8Array(this.buffer,l,4*r);l+=4*r;const d=[];for(let e=0;e<o;++e){const e=t.getFloat32(l,!0);l+=4;const i=t.getUint32(l,!0);l+=4,d.push([e,`#${i.toString(16).padStart(6,"0")}`])}let u=null;if(s){u=[];for(let e=0;e<4;++e)u.push(t.getFloat32(l,!0)),l+=4}let p=null;if(n&&(p=new Uint8Array(this.buffer,l,3),l+=3),1===i)return["RadialAxial","axial",u,d,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===i)return["RadialAxial","radial",u,d,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===i){const t=this.data[ze.SHADING_TYPE];let i=null;if(h.length>0){i=e.slice();for(let t=0,e=h.length;t<e;t+=2)ot.pointBoundingBox(h[t],h[t+1],i)}return["Mesh",t,h,c,a,i,u,p]}throw new Error(`Unsupported pattern kind: ${i}`)}}class Ve{#is;constructor(t){this.#is=t}get path(){return rt.isFloat16ArraySupported?new Float16Array(this.#is):new Float32Array(this.#is)}}function Ke(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const Xe=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,qe=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[s,n,...a]=i;if(!t(s)&&!Number.isInteger(s))return!1;if(!e(n))return!1;const r=a.length;let o=!0;switch(n.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;o=!1;break;default:return!1}for(const t of a)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,Xe,t=>"object"==typeof t&&"string"==typeof t?.name);class Ye{#cs=new Map;#ds=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#ds.then(()=>{for(const[t]of this.#cs)t.call(this,i)})}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted)return void W("LoopbackPort - cannot use an `aborted` signal.");const a=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",a),n.addEventListener("abort",a)}this.#cs.set(e,s)}removeEventListener(t,e){const i=this.#cs.get(e);i?.(),this.#cs.delete(e)}terminate(){for(const[,t]of this.#cs)t?.();this.#cs.clear()}}const Qe=1,Je=2,Ze=1,ti=2,ei=3,ii=4,si=5,ni=6,ai=7,ri=8;function oi(){}function li(t){if(t instanceof nt||t instanceof et||t instanceof Z||t instanceof it||t instanceof tt)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||V('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new nt(t.message);case"InvalidPDFException":return new et(t.message);case"PasswordException":return new Z(t.message,t.code);case"ResponseException":return new it(t.message,t.status,t.missing);case"UnknownErrorException":return new tt(t.message,t.details)}return new tt(t.message,t.toString())}class hi{#us=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,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),i.addEventListener("message",this.#ps.bind(this),{signal:this.#us.signal})}#ps({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#gs(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Qe)i.resolve(t.data);else{if(t.callback!==Je)throw new Error("Unexpected callback case");i.reject(li(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;return void Promise.try(e,t.data).then(function(e){n.postMessage({sourceName:i,targetName:s,callback:Qe,callbackId:t.callbackId,data:e})},function(e){n.postMessage({sourceName:i,targetName:s,callback:Je,callbackId:t.callbackId,reason:li(e)})})}t.streamId?this.#ms(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[n].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:ni,streamId:n,desiredSize:t.desiredSize}),e.promise},cancel:t=>{K(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:Ze,streamId:n,reason:li(t)}),e.promise}},i)}#ms(t){const e=t.streamId,i=this.sourceName,s=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:i,targetName:s,stream:ii,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:ei,streamId:e}),delete a.streamSinks[e])},error(t){K(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:i,targetName:s,stream:si,streamId:e,reason:li(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,Promise.try(r,t.data,o).then(function(){n.postMessage({sourceName:i,targetName:s,stream:ri,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:ri,streamId:e,reason:li(t)})})}#gs(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case ri:t.success?a.startCall.resolve():a.startCall.reject(li(t.reason));break;case ai:t.success?a.pullCall.resolve():a.pullCall.reject(li(t.reason));break;case ni:if(!r){n.postMessage({sourceName:i,targetName:s,stream:ai,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,Promise.try(r.onPull||oi).then(function(){n.postMessage({sourceName:i,targetName:s,stream:ai,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:ai,streamId:e,reason:li(t)})});break;case ii:if(K(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case ei:if(K(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#fs(a,e);break;case si:K(a,"error should have stream controller"),a.controller.error(li(t.reason)),this.#fs(a,e);break;case ti:t.success?a.cancelCall.resolve():a.cancelCall.reject(li(t.reason)),this.#fs(a,e);break;case Ze:if(!r)break;const o=li(t.reason);Promise.try(r.onCancel||oi,o).then(function(){n.postMessage({sourceName:i,targetName:s,stream:ti,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:ti,streamId:e,reason:li(t)})}),r.sinkCapability.reject(o),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#fs(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#us?.abort(),this.#us=null}}class ci{#bs=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:i=null}){this.cMapUrl=t,this.standardFontDataUrl=e,this.wasmUrl=i}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:V(`Not implemented: ${t}`)}const i=this[t];if(!i)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const s=`${i}${e}`;return this._fetch(s,t).catch(e=>{throw new Error(`Unable to load ${this.#bs[t]} data at: ${s}`)})}async _fetch(t,e){V("Abstract method `_fetch` called.")}}class di extends ci{async _fetch(t,e){const i="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",s=await At(t,i);return s instanceof Uint8Array?s:at(s)}}class ui{#ys=!1;constructor({enableHWA:t=!1}){this.#ys=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#ys})}}reset({canvas:t},e,i){if(!t)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.width=e,t.height=i}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){V("Abstract method `_createCanvas` called.")}}class pi extends ui{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class gi{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}addSelectionHCMFilter(t,e){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(t=null){return null}destroy(t=!1){}}class mi extends gi{#vs;#As;#ws;#xs;#Cs;#Ss;#E=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#xs=t,this.#Cs=e}get#k(){return this.#As||=new Map}get#Ts(){return this.#Ss||=new Map}get#Es(){if(!this.#ws){const t=this.#Cs.createElement("div"),{style:e}=t;e.colorScheme="only light",e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#Cs.createElementNS(a,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#ws=this.#Cs.createElementNS(a,"defs"),t.append(i),i.append(this.#ws),this.#Cs.body.append(t)}return this.#ws}#_s(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=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]=i[t]/255,r[t]=s[t]/255;return[n.join(","),a.join(","),r.join(",")]}#ks(t){if(void 0===this.#vs){this.#vs="";const t=this.#Cs.URL;t!==this.#Cs.baseURI&&(xt(t)?W('#createUrl: ignore "data:"-URL for performance reasons.'):this.#vs=q(t,""))}return`url(${this.#vs}#${t})`}addFilter(t){if(!t)return"none";let e=this.#k.get(t);if(e)return e;const[i,s,n]=this.#_s(t),a=1===t.length?i:`${i}${s}${n}`;if(e=this.#k.get(a),e)return this.#k.set(t,e),e;const r=`g_${this.#xs}_transfer_map_${this.#E++}`,o=this.#ks(r);this.#k.set(t,o),this.#k.set(a,o);const l=this.#Ms(r);return this.#Ds(i,s,n,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Ts.get(s);if(n?.key===i)return n.url;if(n?(n.filter?.remove(),n.key=i,n.url="none",n.filter=null):(n={key:i,url:"none",filter:null},this.#Ts.set(s,n)),!t||!e)return n.url;const a=this.#Ps(t);t=ot.makeHexColor(...a);const r=this.#Ps(e);if(e=ot.makeHexColor(...r),this.#Es.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 l=o.join(","),h=`g_${this.#xs}_hcm_filter`,c=n.filter=this.#Ms(h);this.#Ds(l,l,l,c),this.#Is(c);const d=(t,e)=>{const i=a[t]/255,s=r[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};return this.#Ds(d(0,5),d(1,5),d(2,5),c),n.url=this.#ks(h),n.url}addSelectionHCMFilter(t,e){return this.addHighlightHCMFilter("selection",t,e,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){const e=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return"none"!==e&&rt.platform.isFirefox?{"backdrop-filter":e,"background-color":"transparent"}:null}addAlphaFilter(t){let e=this.#k.get(t);if(e)return e;const[i]=this.#_s([t]),s=`alpha_${i}`;if(e=this.#k.get(s),e)return this.#k.set(t,e),e;const n=`g_${this.#xs}_alpha_map_${this.#E++}`,a=this.#ks(n);this.#k.set(t,a),this.#k.set(s,a);const r=this.#Ms(n);return this.#Fs(i,r),a}addLuminosityFilter(t){let e,i,s=this.#k.get(t||"luminosity");if(s)return s;if(t?([e]=this.#_s([t]),i=`luminosity_${e}`):i="luminosity",s=this.#k.get(i),s)return this.#k.set(t,s),s;const n=`g_${this.#xs}_luminosity_map_${this.#E++}`,a=this.#ks(n);this.#k.set(t,a),this.#k.set(i,a);const r=this.#Ms(n);return this.#Bs(r),t&&this.#Fs(e,r),a}addKnockoutFilter(t=0){const e=t>0?Math.min(1/t,1e6):1e6,i=`knockout_${e}`,s=this.#k.get(i);if(s)return s;const n=`g_${this.#xs}_knockout_filter_${this.#E++}`,r=this.#ks(n);this.#k.set(i,r);const o=this.#Ms(n),l=this.#Cs.createElementNS(a,"feComponentTransfer");o.append(l);const h=this.#Cs.createElementNS(a,"feFuncA");return h.setAttribute("type","linear"),h.setAttribute("slope",`${e}`),h.setAttribute("intercept","0"),l.append(h),r}addHighlightHCMFilter(t,e,i,s,n){const a=`${e}-${i}-${s}-${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||!i)return r.url;const[o,l]=[e,i].map(this.#Ps.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[s,n].map(this.#Ls.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]),this.#Es.style.color="";const p=(t,e,i)=>{const s=new Array(256),n=(c-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=a+t*r;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#xs}_hcm_${t}_filter`,m=r.filter=this.#Ms(g);return this.#Is(m),this.#Ds(p(d[0],u[0],5),p(d[1],u[1],5),p(d[2],u[2],5),m),r.url=this.#ks(g),r.url}destroy(t=!1){t&&this.#Ss?.size||(this.#ws?.parentNode.parentNode.remove(),this.#ws=null,this.#As?.clear(),this.#As=null,this.#Ss?.clear(),this.#Ss=null,this.#E=0)}#Bs(t){const e=this.#Cs.createElementNS(a,"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)}#Is(t){const e=this.#Cs.createElementNS(a,"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)}#Ms(t){const e=this.#Cs.createElementNS(a,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#Es.append(e),e}#Rs(t,e,i){const s=this.#Cs.createElementNS(a,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#Ds(t,e,i,s){const n=this.#Cs.createElementNS(a,"feComponentTransfer");s.append(n),this.#Rs(n,"feFuncR",t),this.#Rs(n,"feFuncG",e),this.#Rs(n,"feFuncB",i)}#Fs(t,e){const i=this.#Cs.createElementNS(a,"feComponentTransfer");e.append(i),this.#Rs(i,"feFuncA",t)}#Ps(t){return this.#Es.style.color=t,It(getComputedStyle(this.#Es).getPropertyValue("color"))}#Os(t){return this.#Es.style.color=t,Pt(getComputedStyle(this.#Es).getPropertyValue("color"))}#Ls(t){const[e,i,s,n]=this.#Os(t);if(1===n)return[e,i,s];const[a,r,o]=this.#Ps("Canvas");return[fi(e,a,n),fi(i,r,n),fi(s,o,n)]}}function fi(t,e,i){return Math.round(i*t+(1-i)*e)}t&&W("Please use the `legacy` build in Node.js environments.");class bi extends gi{}class yi extends ui{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class vi extends ci{async _fetch(t,e){return async function(t){const e=process.getBuiltinModule("fs/promises"),i=await e.readFile(t);return new Uint8Array(i)}(t)}}const Ai=new class{#Ns=null;#Hs=null;#Us=null;#zs=null;async#Gs(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();return!!t&&(this.#zs=navigator.gpu.getPreferredCanvasFormat(),this.#Hs=await t.requestDevice(),!0)}catch{return!1}}init(){return this.#Ns||=this.#Gs()}get isReady(){return null!==this.#Hs}loadMeshShader(){if(!this.#Hs||this.#Us)return;const t=this.#Hs.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#Us=this.#Hs.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#zs}]},primitive:{topology:"triangle-list"}})}draw(t,e,i,s,n,a,r,o){this.loadMeshShader();const l=this.#Hs,{offsetX:h,offsetY:c,scaleX:d,scaleY:u}=s,p=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(p,0,t);const g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,0,e);const m=l.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([h,c,d,u,a,r,o,0]));const f=l.createBindGroup({layout:this.#Us.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(a,r),y=b.getContext("webgpu");y.configure({device:l,format:this.#zs,alphaMode:n?"opaque":"premultiplied"});const v=n?{r:n[0]/255,g:n[1]/255,b:n[2]/255,a:1}:{r:0,g:0,b:0,a:0},A=l.createCommandEncoder(),w=A.beginRenderPass({colorAttachments:[{view:y.getCurrentTexture().createView(),clearValue:v,loadOp:"clear",storeOp:"store"}]});return i>0&&(w.setPipeline(this.#Us),w.setBindGroup(0,f),w.setVertexBuffer(0,p),w.setVertexBuffer(1,g),w.draw(i)),w.end(),l.queue.submit([A.finish()]),p.destroy(),g.destroy(),m.destroy(),b.transferToImageBitmap()}};const wi="Fill",xi="Stroke",Ci="Shading";function Si(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s),t.clip(n)}class Ti{isModifyingCurrentTransform(){return!1}getPattern(){V("Abstract method `getPattern` called.")}}class Ei extends Ti{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}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let i,s=this._p0,n=this._p1;if(e&&(s=s.slice(),n=n.slice(),ot.applyTransform(s,e),ot.applyTransform(n,e)),"axial"===this._type)i=t.createLinearGradient(s[0],s[1],n[0],n[1]);else if("radial"===this._type){let a=this._r0,r=this._r1;if(e){const t=new Float32Array(2);ot.singularValueDecompose2dScale(e,t),a*=t[0],r*=t[0]}i=t.createRadialGradient(s[0],s[1],a,n[0],n[1],r)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}_createReversedGradient(t,e=null){let i=this._p1,s=this._p0;e&&(i=i.slice(),s=s.slice(),ot.applyTransform(i,e),ot.applyTransform(s,e));let n=this._r1,a=this._r0;if(e){const t=new Float32Array(2);ot.singularValueDecompose2dScale(e,t),n*=t[0],a*=t[0]}const r=t.createRadialGradient(i[0],i[1],n,s[0],s[1],a),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(const[t,e]of o)r.addColorStop(t,e);return r}getPattern(t,e,i,s){let n;if(s===xi||s===wi){if(this.isOriginBased()){let s=ot.transform(i,e.baseTransform);this.matrix&&(s=ot.transform(s,this.matrix));const n=.001,a=Math.hypot(s[0],s[1]),r=Math.hypot(s[2],s[3]),o=(s[0]*s[2]+s[1]*s[3])/(a*r);if(Math.abs(o)<n){if(!this.isRadial())return this._createGradient(t,s);if(Math.abs(a-r)<n)return this._createGradient(t,s)}}const a=e.current.getClippedPathBoundingBox(s,Ft(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.canvasFactory.create(r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=ot.transform(i,[1,0,0,1,a[0],a[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),Si(h,this._bbox),this.areConic()&&(h.fillStyle=this._createReversedGradient(h),h.fill()),h.fillStyle=this._createGradient(h),h.fill(),n=t.createPattern(l.canvas,"no-repeat"),e.canvasFactory.destroy(l);const c=new DOMMatrix(i);n.setTransform(c)}else this.areConic()&&(t.save(),Si(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),Si(t,this._bbox),n=this._createGradient(t);return n}}function _i(t,e,i,s,n,a,r,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;l[2*i+1]>l[2*s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u),l[2*s+1]>l[2*n+1]&&(u=s,s=n,n=u,u=r,r=o,o=u),l[2*i+1]>l[2*s+1]&&(u=i,i=s,s=u,u=a,a=r,r=u);const p=(l[2*i]+e.offsetX)*e.scaleX,g=(l[2*i+1]+e.offsetY)*e.scaleY,m=(l[2*s]+e.offsetX)*e.scaleX,f=(l[2*s+1]+e.offsetY)*e.scaleY,b=(l[2*n]+e.offsetX)*e.scaleX,y=(l[2*n+1]+e.offsetY)*e.scaleY;if(g>=y)return;const v=h[4*a],A=h[4*a+1],w=h[4*a+2],x=h[4*r],C=h[4*r+1],S=h[4*r+2],T=h[4*o],E=h[4*o+1],_=h[4*o+2],k=Math.round(g),M=Math.round(y);let D,P,I,F,B,L,R,O;for(let t=k;t<=M;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);D=p-(p-m)*e,P=v-(v-x)*e,I=A-(A-C)*e,F=w-(w-S)*e}else{let e;e=t>y?1:f===y?0:(f-t)/(f-y),D=m-(m-b)*e,P=x-(x-T)*e,I=C-(C-E)*e,F=S-(S-_)*e}let e;e=t<g?0:t>y?1:(g-t)/(g-y),B=p-(p-b)*e,L=v-(v-T)*e,R=A-(A-E)*e,O=w-(w-_)*e;const i=Math.round(Math.min(D,B)),s=Math.round(Math.max(D,B));let n=d*t+4*i;for(let t=i;t<=s;t++)e=(D-t)/(D-B),e<0?e=0:e>1&&(e=1),c[n++]=P-(P-L)*e|0,c[n++]=I-(I-R)*e|0,c[n++]=F-(F-O)*e|0,c[n++]=255}}class ki extends Ti{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null,Ai.loadMeshShader()}_createMeshCanvas(t,e,i){const s=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-s,r=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3)||1,l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3)||1,h=a?a/o:1,c=r?r/l:1,d={coords:this._posData,colors:this._colData,offsetX:-s,offsetY:-n,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.create(u,p);if(Ai.isReady&&this._vertexCount>48)g.context.drawImage(function(t,e,i,s,n,a,r,o){return Ai.draw(t,e,i,s,n,a,r,o)}(this._posData,this._colData,this._vertexCount,d,e,u,p,2),0,0);else{const t=g.context.createImageData(o,l);if(e){const i=t.data;for(let t=0,s=i.length;t<s;t+=4)i[t]=e[0],i[t+1]=e[1],i[t+2]=e[2],i[t+3]=255}for(let e=0,i=this._vertexCount;e<i;e+=3)_i(t,d,e,e+1,e+2,e,e+1,e+2);g.context.putImageData(t,2,2)}return{canvas:g.canvas,offsetX:s-2*h,offsetY:n-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,s){Si(t,this._bbox);const n=new Float32Array(2);if(s===Ci)ot.singularValueDecompose2dScale(Ft(t),n);else if(this.matrix){ot.singularValueDecompose2dScale(this.matrix,n);const[t,i]=n;ot.singularValueDecompose2dScale(e.baseTransform,n),n[0]*=t,n[1]*=i}else ot.singularValueDecompose2dScale(e.baseTransform,n);const a=this._createMeshCanvas(n,s===Ci?null:this._background,e.canvasFactory);s!==Ci&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(a.offsetX,a.offsetY),t.scale(a.scaleX,a.scaleY);const r=t.createPattern(a.canvas,"no-repeat");return e.canvasFactory.destroy(a),r}}class Mi extends Ti{getPattern(){return"hotpink"}}const Di=1,Pi=2;class Ii{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,s){this.color=t[1],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.needsIsolation=t[9]??!0,this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=s,this.patternBaseMatrix=this.matrix?ot.transform(s,this.matrix):s}canSkipPatternCanvas([t,e,i,s]){const[n,a,r,o]=this.bbox,l=Math.abs(this.xstep),h=Math.abs(this.ystep);if(t>l+1e-6||e>h+1e-6)return null;const c=Math.floor((i-r)/l)+1,d=Math.ceil((i+t-n)/l)-1,u=Math.floor((s-o)/h)+1,p=Math.ceil((s+e-a)/h)-1;return d<=c&&p<=u?[c,u]:null}updatePatternDims(t,e){const i=ot.inverseTransform(this.patternBaseMatrix),s=[t[0],t[1]],n=[t[2],t[3]];ot.applyTransform(s,i),ot.applyTransform(n,i),e[0]=Math.abs(n[0]-s[0]),e[1]=Math.abs(n[1]-s[1]),e[2]=Math.min(s[0],n[0]),e[3]=Math.min(s[1],n[1])}_renderTileCanvas(t,e,i,s){const[n,a,r,o]=this.bbox,l=t.canvasFactory.create(i.size,s.size),h=l.context,c=this.canvasGraphicsFactory.createCanvasGraphics(h,e);return c.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(c,this.paintType,this.color),h.translate(-i.scale*n,-s.scale*a),c.transform(0,i.scale,0,0,s.scale,0,0),h.save(),c.dependencyTracker?.save(),this.clipBbox(c,n,a,r,o),c.baseTransform=Ft(c.ctx),c.executeOperatorList(this.operatorList),c.endDrawing(),c.dependencyTracker?.restore(),h.restore(),l}_getCombinedScales(){const t=new Float32Array(2);ot.singularValueDecompose2dScale(this.matrix,t);const[e,i]=t;return ot.singularValueDecompose2dScale(this.baseTransform,t),[e*t[0],i*t[1]]}drawPattern(t,e,i=!1,[s,n],a){const[r,o,l,h]=this.bbox,c=t.dependencyTracker;if(c&&(t.dependencyTracker=new _e(c,a)),t.save(),i?t.ctx.clip(e,"evenodd"):t.ctx.clip(e),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(s*this.xstep,n*this.ystep),this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const e=l-r,i=h-o,[s,n]=this._getCombinedScales(),c=this.getSizeAndScale(e,this.ctx.canvas.width,s),d=this.getSizeAndScale(i,this.ctx.canvas.height,n),u=this._renderTileCanvas(t,a,c,d);t.ctx.drawImage(u.canvas,r,o,e,i),t.canvasFactory.destroy(u)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,r,o,l,h),t.baseTransformStack.push(t.baseTransform),t.baseTransform=Ft(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),c&&(t.dependencyTracker=c)}createPatternCanvas(t,e){const[i,s,n,a]=this.bbox,r=n-i,o=a-s;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),j("TilingType: "+this.tilingType);const[c,d]=this._getCombinedScales();let u=r,p=o,g=!1,m=!1;Math.ceil(l*c)>=Math.ceil(r*c)?u=l:g=!0,Math.ceil(h*d)>=Math.ceil(o*d)?p=h:m=!0;const f=this.getSizeAndScale(u,this.ctx.canvas.width,c),b=this.getSizeAndScale(p,this.ctx.canvas.height,d),y=this._renderTileCanvas(t,e,f,b);if(g||m){const e=y.canvas;g&&(u=l),m&&(p=h);const n=this.getSizeAndScale(u,this.ctx.canvas.width,c),a=this.getSizeAndScale(p,this.ctx.canvas.height,d),f=n.size,b=a.size,v=t.canvasFactory.create(f,b),A=v.context,w=g?Math.floor(r/l):0,x=m?Math.floor(o/h):0;for(let t=0;t<=w;t++)for(let i=0;i<=x;i++)A.drawImage(e,f*t,b*i,f,b,0,0,f,b);return t.canvasFactory.destroy(y),{canvas:v.canvas,canvasEntry:v,scaleX:n.scale,scaleY:a.scale,offsetX:i,offsetY:s}}return{canvas:y.canvas,canvasEntry:y,scaleX:f.scale,scaleY:b.scale,offsetX:i,offsetY:s}}getSizeAndScale(t,e,i){const s=Math.max(Ii.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);return n>=s?n=s:i=n/t,{scale:i,size:n}}clipBbox(t,e,i,s,n){const a=s-e,r=n-i,o=new Path2D;o.rect(e,i,a,r),ot.axialAlignedBoundingBox([e,i,s,n],Ft(t.ctx),t.current.minMax),t.ctx.clip(o),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(n.patternFill=n.patternStroke=!1,e){case Di:const{fillStyle:t,strokeStyle:a}=this.ctx;s.fillStyle=n.fillColor=t,s.strokeStyle=n.strokeColor=a;break;case Pi:s.fillStyle=s.strokeStyle=i,n.fillColor=n.strokeColor=i;break;default:throw new st(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s,n){const a=s!==Ci?ot.transform(i,this.patternBaseMatrix):i,r=this.createPatternCanvas(e,n);let o=new DOMMatrix(a);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");return e.canvasFactory.destroy(r.canvasEntry),l.setTransform(o),l}}function Fi({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=rt.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],c=s>>3,d=7&s,u=l^h,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let s=0;s<n;++s){for(const s=e+c;e<s;++e,g+=8){const s=t[e];i[g]=l^-(s>>7&1)&u,i[g+1]=l^-(s>>6&1)&u,i[g+2]=l^-(s>>5&1)&u,i[g+3]=l^-(s>>4&1)&u,i[g+4]=l^-(s>>3&1)&u,i[g+5]=l^-(s>>2&1)&u,i[g+6]=l^-(s>>1&1)&u,i[g+7]=l^-(1&s)&u}if(0===d)continue;const s=e<p?t[e++]:255;for(let t=0;t<d;++t,++g)i[g]=l^-(s>>7-t&1)&u}return{srcPos:e,destPos:g}}const Bi=16,Li=new DOMMatrix,Ri=new Float32Array(2);function Oi(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");const i=new Map;for(const s of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const n=t[s];"function"==typeof n&&"function"==typeof e[s]&&(i.set(s,n),t[s]=function(...t){return e[s](...t),n.apply(this,t)})}t._removeMirroring=()=>{for(const[e,s]of i)t[e]=s;delete t._removeMirroring}}function Ni(t,e,i,s,n,a,r,o,l,h){const[c,d,u,p,g,m]=Ft(t);if(0===d&&0===u){const f=r*c+g,b=Math.round(f),y=o*p+m,v=Math.round(y),A=(r+l)*c+g,w=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,C=Math.abs(Math.round(x)-v)||1;return t.setTransform(Math.sign(c),0,0,Math.sign(p),b,v),t.drawImage(e,i,s,n,a,0,0,w,C),t.setTransform(c,d,u,p,g,m),[w,C]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),y=r*d+m,v=Math.round(y),A=(o+h)*u+g,w=Math.abs(Math.round(A)-b)||1,x=(r+l)*d+m,C=Math.abs(Math.round(x)-v)||1;return t.setTransform(0,Math.sign(d),Math.sign(u),0,b,v),t.drawImage(e,i,s,n,a,0,0,C,w),t.setTransform(c,d,u,p,g,m),[C,w]}t.drawImage(e,i,s,n,a,r,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class Hi{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=s;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=A;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=i.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=wi,e=null){const i=this.minMax.slice();if(t===xi){e||V("Stroke bounding box must include transform."),ot.singularValueDecompose2dScale(e,Ri);const t=Ri[0]*this.lineWidth/2,s=Ri[1]*this.lineWidth/2;i[0]-=t,i[1]-=s,i[2]+=t,i[3]+=s}return i}updateClipFromPath(){const t=ot.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(i,0)}getClippedPathBoundingBox(t=wi,e=null){return ot.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Ui(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,s=e.width,n=i%Bi,a=(i-n)/Bi,r=0===n?a:a+1,o=t.createImageData(s,Bi);let l,h=0;const c=e.data,d=o.data;let u,p,g,m;if(e.kind===E.GRAYSCALE_1BPP){const e=c.byteLength,i=new Uint32Array(d.buffer,0,d.byteLength>>2),m=i.length,f=s+7>>3,b=4294967295,y=rt.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?Bi:n,l=0,p=0;p<g;p++){const t=e-h;let n=0;const a=t>f?s:8*t-7,r=-8&a;let o=0,d=0;for(;n<r;n+=8)d=c[h++],i[l++]=128&d?b:y,i[l++]=64&d?b:y,i[l++]=32&d?b:y,i[l++]=16&d?b:y,i[l++]=8&d?b:y,i[l++]=4&d?b:y,i[l++]=2&d?b:y,i[l++]=1&d?b:y;for(;n<a;n++)0===o&&(d=c[h++],o=128),i[l++]=d&o?b:y,o>>=1}for(;l<m;)i[l++]=0;t.putImageData(o,0,u*Bi)}}else if(e.kind===E.RGBA_32BPP){for(p=0,m=s*Bi*4,u=0;u<a;u++)d.set(c.subarray(h,h+m)),h+=m,t.putImageData(o,0,p),p+=Bi;u<r&&(m=s*n*4,d.set(c.subarray(h,h+m)),t.putImageData(o,0,p))}else{if(e.kind!==E.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=Bi,m=s*g,u=0;u<r;u++){for(u>=a&&(g=n,m=s*g),l=0,p=m;p--;)d[l++]=c[h++],d[l++]=c[h++],d[l++]=c[h++],d[l++]=255;t.putImageData(o,0,u*Bi)}}}function zi(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,s=e.width,n=i%Bi,a=(i-n)/Bi,r=0===n?a:a+1,o=t.createImageData(s,Bi);let l=0;const h=e.data,c=o.data;for(let e=0;e<r;e++){const i=e<a?Bi:n;({srcPos:l}=Fi({src:h,srcPos:l,dest:c,width:s,height:i,nonBlackColor:0})),t.putImageData(o,0,e*Bi)}}function Gi(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of i)void 0!==t[s]&&(e[s]=t[s]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function $i(t){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);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function ji(t,e){if(e)return!0;ot.singularValueDecompose2dScale(t,Ri);const i=Math.fround(Rt.pixelRatio*vt.PDF_TO_CSS_UNITS);return Ri[0]<=i&&Ri[1]<=i}const Wi=["butt","round","square"],Vi=["miter","round","bevel"],Ki={},Xi={};class qi{#$s=0;#js=0;#Ws=null;#Vs=null;#Ks=null;#Xs=null;#qs=1;#Ys;#Qs=null;#Js=[];constructor(t,e,i,s,n,{optionalContentConfig:a,markedContentStack:r=null},o,l,h,c){this.ctx=t,this.current=new Hi(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=e,this.objs=i,this.canvasFactory=s,this.filterFactory=n,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=r||[],this.optionalContentConfig=a,this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=h??null,this.imagesTracker=c??null}getObject(t,e,i=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:s=null}){const n=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=s||"#ffffff",this.ctx.fillRect(0,0,n,a),this.ctx.fillStyle=r,i){const t=this.transparentCanvasEntry=this.canvasFactory.create(n,a);this.compositeCtx=this.ctx,({canvas:this.transparentCanvas,context:this.ctx}=t),this.ctx.save(),this.ctx.transform(...Ft(this.compositeCtx))}this.ctx.save(),$i(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=Ft(this.ctx)}executeOperatorList(t,e,i,s,n){const a=t.argsArray,r=t.fnArray;let o=e||0;const l=a.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,c=h?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==s){if(o===s.nextBreakPoint)return s.breakIt(o,i),o;if(s.shouldSkip(o)){if(++o===l)return o;continue}}if(!n||n(o))if(g=r[o],m=a[o]??null,g!==B.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t))return e.get(t,i),o}if(o++,o===l)return o;if(h&&++d>10){if(Date.now()>c)return i(),o;d=0}}}#Zs(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,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.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#Zs();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(const t of this.#Js)this.#tn(t);this.#Js.length=0,this.#Ws=null,this.#Vs=null,this.#Ks=null,this.#Xs=null,this.#qs=1,this.#Qs=null,this.#js=0,this.#$s=0,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.#en()}#en(){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 i=t.width??t.displayWidth,s=t.height??t.displayHeight,n=[];let a=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=i,l=s;for(;a>2&&o>1||r>2&&l>1;){let t=o,e=l;a>2&&o>1&&(t=Math.ceil(o/2),a/=o/t),r>2&&l>1&&(e=Math.ceil(l/2),r/=l/e),n.push({newWidth:t,newHeight:e}),o=t,l=e}if(0===n.length)return{img:t,paintWidth:i,paintHeight:s,tmpCanvas:null};if(1===n.length){const{newWidth:e,newHeight:a}=n[0],r=this.canvasFactory.create(e,a);return r.context.drawImage(t,0,0,i,s,0,0,e,a),{img:r.canvas,paintWidth:e,paintHeight:a,tmpCanvas:r}}let h=this.canvasFactory.create(1,1),c=this.canvasFactory.create(1,1),d=i,u=s,p=t;for(const{newWidth:t,newHeight:e}of n)this.canvasFactory.reset(c,t,e),c.context.drawImage(p,0,0,d,u,0,0,t,e),[h,c]=[c,h],p=h.canvas,d=t,u=e;return this.canvasFactory.destroy(c),{img:h.canvas,paintWidth:d,paintHeight:u,tmpCanvas:h}}_createMaskCanvas(t,e){const s=this.ctx,{width:n,height:a}=e,r=this.current.fillColor,o=this.current.patternFill,l=Ft(s);let h,c,d,u;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;c=JSON.stringify(o?l:[l.slice(0,4),r]),h=this._cachedBitmapsMap.getOrInsertComputed(i,pt);const s=h.get(c);if(s&&!o){const e=Math.round(Math.min(l[0],l[2])+l[4]),i=Math.round(Math.min(l[1],l[3])+l[5]);return this.dependencyTracker?.recordDependencies(t,Be),{canvas:s,offsetX:e,offsetY:i}}d=s}d||(u=this.canvasFactory.create(n,a),zi(u.context,e));let p=ot.transform(l,[1/n,0,0,-1/a,0,0]);p=ot.transform(p,[1,0,0,1,0,-a]);const g=i.slice();ot.axialAlignedBoundingBox([0,0,n,a],p,g);const[m,f,b,y]=g,v=Math.round(b-m)||1,A=Math.round(y-f)||1,w=this.canvasFactory.create(v,A),x=w.context,C=m,S=f;x.translate(-C,-S),x.transform(...p);let T=null;if(!d){const t=this._scaleImage(u.canvas,Bt(x));d=t.img,T=t.tmpCanvas,d!==u.canvas&&(this.canvasFactory.destroy(u),u=null),h&&o&&(h.set(c,d),T=null,u=null)}x.imageSmoothingEnabled=ji(Ft(x),e.interpolate),Ni(x,d,0,0,d.width,d.height,0,0,n,a),T&&this.canvasFactory.destroy(T),u&&this.canvasFactory.destroy(u),x.globalCompositeOperation="source-in";const E=ot.transform(Bt(x),[1,0,0,1,-C,-S]);return x.fillStyle=o?r.getPattern(s,this,E,wi,t):r,x.fillRect(0,0,n,a),h&&!o&&h.set(c,w.canvas),this.dependencyTracker?.recordDependencies(t,Be),{canvas:w.canvas,canvasEntry:h&&!o?null:w,offsetX:Math.round(C),offsetY:Math.round(S)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Wi[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Vi[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const s=this.ctx;void 0!==s.setLineDash&&(s.setLineDash(e),s.lineDashOffset=i)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,s]of e)switch(i){case"LW":this.setLineWidth(t,s);break;case"LC":this.setLineCap(t,s);break;case"LJ":this.setLineJoin(t,s);break;case"ML":this.setMiterLimit(t,s);break;case"D":this.setDash(t,s[0],s[1]);break;case"RI":this.setRenderingIntent(t,s);break;case"FL":this.setFlatness(t,s);break;case"Font":this.setFont(t,s[0],s[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=s;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=s;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=s;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=s?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:e,subtype:i,backdrop:s,transferMap:n}=t,a="Luminosity"===i||"Alpha"===i&&n;if(!(a||"Luminosity"===i&&s))return void(this.smaskPreparedFor=t);let r;if("Luminosity"===i&&s){const[t,e,i]=Pt(s),a=Math.round(.3*t+.59*e+.11*i);r=n?.[a]??a}else r=n?.[0]??0;const{width:o,height:l}=this.ctx.canvas,h=o*l<4*(e.width*e.height),c=a?{url:"Alpha"===i?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:i,transferMap:n}:null,d="Luminosity"===i?s:null;let u,p,g;h?(u=this._bakeSMaskCanvas(e,t.offsetX,t.offsetY,o,l,d,c),p=0,g=0):(u=this._bakeSMaskCanvas(e,0,0,e.width,e.height,d,c),p=t.offsetX,g=t.offsetY),this.smaskPreparedEntry=u,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=p,this.smaskPreparedOffsetY=g,this.smaskPreparedOOBAlpha=h||0===r?null:r}_bakeSMaskCanvas(t,e,i,s,n,a,r){a||r||V("_bakeSMaskCanvas with neither backdrop nor filter");const o=this.canvasFactory.create(s,n),l=o.context;if(l.drawImage(t,e,i),a&&(l.globalCompositeOperation="destination-atop",l.fillStyle=a,l.fillRect(0,0,s,n)),!r)return o;const h=this.canvasFactory.create(s,n),c=h.context;c.filter=r.url;const d=rt.isCanvasFilterSupported&&"none"!==c.filter&&""!==c.filter;if(c.drawImage(o.canvas,0,0),rt.isCanvasFilterSupported&&(c.filter="none"),!d){const t=c.getImageData(0,0,s,n),{data:e}=t,{transferMap:i}=r;if("Luminosity"===r.subtype)for(let t=0,s=e.length;t<s;t+=4){const s=.3*e[t]+.59*e[t+1]+.11*e[t+2]+.5|0;e[t]=e[t+1]=e[t+2]=0,e[t+3]=i?.[s]??s}else for(let t=3,s=e.length;t<s;t+=4)e[t]=i[e[t]];c.putImageData(t,0,0)}return this.canvasFactory.destroy(o),h}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:i}=this.ctx.canvas,s=this.canvasFactory.create(e,i);this.smaskScratchCanvas=s,this.suspendedCtx=this.ctx;const n=this.ctx=s.context;n.setTransform(this.suspendedCtx.getTransform()),Gi(this.suspendedCtx,n),Oi(n,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Gi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#in(t,e=null,i=1){const{width:s,height:n}=t,a=e??this.canvasFactory.create(s,n),r=a.context,o=(i=Math.round(255*i)/255)<1;o&&void 0===this.#Ys&&(this.#Ys=rt.isCanvasFilterSupported?new Map:"none");let l="none";if(o&&this.#Ys instanceof Map&&(l=this.#Ys.get(i),l||(l=this.filterFactory.addKnockoutFilter(i),this.#Ys.set(i,l))),!o||"none"!==l)return e&&(r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,s,n),r.restore()),r.filter=l,r.drawImage(t,0,0),r.filter="none",a;const h=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,s,n),c=r.createImageData(s,n),d=h.data,u=c.data,p=i>0?1/i:1e6;for(let t=3,e=d.length;t<e;t+=4)u[t]=Math.min(Math.round(d[t]*p),255);return r.putImageData(c,0,0),a}#sn(t,e,i,s){let n=t?.[e]??null;if(!n||n.canvas.width===i&&n.canvas.height===s||(this.canvasFactory.destroy(n),n=null),!n)return n=this.canvasFactory.create(i,s),t&&(t[e]=n),n;const a=n.context;return a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,i,s),a.restore(),n}#nn(t,e,i={}){const{backdropCanvas:s=null,destTransform:n=[1,0,0,1,0,0],backdropOffset:a=[0,0],reuseMaskEntry:r=null,poolMeta:o=null,sourceAlpha:l=1,sourceFilter:h="none",knockoutAlpha:c=1}=i,{width:d,height:u}=e,p=this.#in(e,r,c),g=t.globalCompositeOperation;if(t.save(),t.setTransform(...n),t.globalAlpha=1,rt.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(p.canvas,0,0),s){const[e,i]=a,n=this.#sn(o,"knockoutBackdropEntry",d,u),r=n.context;r.drawImage(s,e,i,d,u,0,0,d,u),r.globalCompositeOperation="destination-in",r.drawImage(p.canvas,0,0),r.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(n.canvas,0,0),o||this.canvasFactory.destroy(n)}t.globalCompositeOperation=g,t.globalAlpha=l,rt.isCanvasFilterSupported&&(t.filter=h??"none"),t.drawImage(e,0,0),t.restore(),r||this.canvasFactory.destroy(p)}#an(t=1){if(0===this.#$s||this.#js>0||!this.contentVisible)return!1;this.#js++,this.#qs=t;const e=this.#Js.at(-1),{canvas:i}=this.ctx,s=this.#sn(e,"knockoutTempEntry",i.width,i.height);this.#Ws=s;const n=s.context;return n.save(),n.setTransform(this.ctx.getTransform()),Gi(this.ctx,n),this.#Xs=n.globalCompositeOperation,n.globalCompositeOperation="source-over",Oi(n,this.ctx),this.#Qs=e,this.#Vs=this.ctx,this.#Ks=this.suspendedCtx,this.ctx=n,this.inSMaskMode&&(this.suspendedCtx=n),!0}#rn(t){if(!t)return;const e=this.#Ws,i=this.#Vs,s=this.#Ks,n=e.context;this.#Ws=null,this.#Vs=null,this.#Ks=null,this.inSMaskMode&&this.suspendedCtx===n&&this.ctx!==n&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=s),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#Xs,this.#Xs=null,Gi(this.ctx,i),this.ctx=i;const a=this.#Qs;this.#Qs=null;const r=this.#qs;this.#qs=1;try{this.#nn(s??i,e.canvas,{backdropCanvas:a?.backdropCtx?.canvas??null,backdropOffset:a?.backdropCtx?[a.offsetX,a.offsetY]:[0,0],reuseMaskEntry:a?.knockoutMaskEntry??null,poolMeta:a,knockoutAlpha:r})}finally{n.restore(),this.#js--,a||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx,s=this.#js>0&&i===this.ctx;this.composeSMask(s?null:i,e,this.ctx,t),s||(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,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0===r||0===o)return;const l=this.smaskPreparedEntry;if(l){let t=n,s=a,h=r,c=o;const d=this.smaskPreparedOOBAlpha,u=null!==d;if(u){t=Math.max(n,e.offsetX),s=Math.max(a,e.offsetY);h=Math.min(n+r,e.offsetX+e.canvas.width)-t,c=Math.min(a+o,e.offsetY+e.canvas.height)-s}if(h>0&&c>0){const e=t-this.smaskPreparedOffsetX,n=s-this.smaskPreparedOffsetY;i.save(),i.globalAlpha=1,i.setTransform(1,0,0,1,0,0);const a=new Path2D;a.rect(t,s,h,c),i.clip(a),i.globalCompositeOperation="destination-in",i.drawImage(l.canvas,e,n,h,c,t,s,h,c),i.restore()}u&&d<255&&this._applySMaskOOBAlpha(i,n,a,r,o,t,s,t+h,s+c,d)}else this.genericComposeSMask(e,i,r,o,n,a);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=e.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,n,a,r,o,n,a,r,o),t.restore())}_applySMaskOOBAlpha(t,e,i,s,n,a,r,o,l,h){const c=a<o&&r<l;if(c&&a===e&&r===i&&o===e+s&&l===i+n)return;const d=new Path2D;d.rect(e,i,s,n),c&&d.rect(a,r,o-a,l-r),t.save(),t.globalAlpha=h/255,t.setTransform(1,0,0,1,0,0),t.clip(d,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(e,i,s,n),t.restore()}genericComposeSMask(t,e,i,s,n,a){const{context:r,offsetX:o,offsetY:l}=t;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);const h=new Path2D;h.rect(n,a,i,s),e.clip(h),e.globalCompositeOperation="destination-in",e.drawImage(r.canvas,n-o,a-l,i,s,n,a,i,s),e.restore()}save(t){this.inSMaskMode&&Gi(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(Gi(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,n,a,r){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,i,s,n,a,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,s){let[n]=i;if(!s)return n||=i[0]=new Path2D,e!==B.stroke&&e!==B.closeStroke&&(this.current.tilingPatternDims=null),void this[e](t,n);if(null!==this.dependencyTracker){const i=e===B.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,s[0]-i,s[2]+i,s[1]-i,s[3]+i).recordDependencies(t,["transform"])}n instanceof Path2D||(n=i[0]=Xt(n)),ot.axialAlignedBoundingBox(s,Ft(this.ctx),this.current.minMax);const a=this.current.tilingPatternDims;if(a&&e!==B.stroke&&e!==B.closeStroke&&this.current.fillColor instanceof Ii){const t=ot.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,a):this.current.tilingPatternDims=null}this[e](t,n),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const s=i&&this.#an(this.current.strokeAlpha),n=this.ctx,a=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof a&&a?.getPattern){const i=a.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=a.getPattern(n,this,Bt(n),xi,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,ke),i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(xi,Ft(this.ctx))),n.globalAlpha=this.current.fillAlpha,this.#rn(s)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const s=i&&this.#an(this.current.fillAlpha),n=this.ctx,a=this.current.fillColor,r=this.current.patternFill;let o=!1;const l=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,Me),r){const r=this.current.tilingPatternDims,h=r&&a.canSkipPatternCanvas(r);if(h)return a.drawPattern(this,e,this.pendingEOFill,h,t),this.pendingEOFill=!1,i&&this.consumePath(t,e,l),this.current.tilingPatternDims=null,void this.#rn(s);const c=a.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=a.getPattern(n,this,Bt(n),wi,t),c){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(c)),e=t}o=!0}this.contentVisible&&null!==l&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),o&&(n.restore(),this.dependencyTracker?.restore(t)),i&&this.consumePath(t,e,l),this.#rn(s)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){const i=this.#an(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e),this.#rn(i)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){const i=this.#an(this.current.fillAlpha);this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,Pe).recordOperation(t),this.#rn(i)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Ki}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Xi}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,s=i.getTransform().invertSelf();for(const{transform:i,x:n,y:a,fontSize:r,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(s).translate(n,a).scale(r,-r));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const n=this.commonObjs.get(e),a=this.current;if(!n)throw new Error(`Can't find font for ${e}`);if(a.fontMatrix=n.fontMatrix||s,0!==a.fontMatrix[0]&&0!==a.fontMatrix[3]||W("Invalid font matrix for font "+e),i<0?(i=-i,a.fontDirection=-1):a.fontDirection=1,this.current.font=n,this.current.fontSize=i,n.isType3Font)return;const r=n.loadedName||"sans-serif",o=n.systemFontInfo?.css||`"${r}", ${n.fallbackName}`;let l="normal";n.black?l="900":n.bold&&(l="bold");const h=n.italic?"italic":"normal";let c=i;i<16?c=16:i>100&&(c=100),this.current.fontSizeScale=i/c,this.ctx.font=`${h} ${l} ${c}px ${o}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i),this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e,i.textMatrixScale=Math.hypot(e[0],e[1]),i.x=i.lineX=0,i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#on(t,e,i){const s=new Path2D;return s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),s}paintChar(t,e,i,s,n,a){const r=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=h&S,u=!!(h&T),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e)),m&&(l.disableFontFace||p||g)){let e;if(r.save(),r.translate(i,s),r.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,r,l),d===A||d===x)if(n){e=r.getTransform(),r.setTransform(...n);const t=this.#on(m,e,n);r.fill(t)}else r.fill(m);if(d===w||d===x)if(a){e||=r.getTransform(),r.setTransform(...a);const{a:t,b:i,c:s,d:n}=e,o=ot.inverseTransform(a),l=ot.transform([t,i,s,n,0,0],o);ot.singularValueDecompose2dScale(l,Ri),r.lineWidth*=Math.max(Ri[0],Ri[1])/c,r.stroke(this.#on(m,e,a))}else r.lineWidth/=c,r.stroke(m);r.restore()}else d!==A&&d!==x||(r.fillText(e,i,s),this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,s,()=>r.measureText(e))),d!==w&&d!==x||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,s,()=>r.measureText(e)).recordDependencies(t,ke),r.strokeText(e,i,s));if(u){(this.pendingTextPaths||=[]).push({transform:Ft(r),x:i,y:s,fontSize:c,path:m}),this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,s)}}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1),e.fillText("I",0,10);const i=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let s=!1;for(let t=3;t<i.length;t+=4)if(i[t]>0&&i[t]<255){s=!0;break}return Q(this,"isFontSubpixelAAEnabled",s)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,Ie).resetBBox(t),this.current.textRenderingMode&T&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const i=this.current,s=i.font;if(s.isType3Font){const s=this.#an(i.fillAlpha);return this.showType3Text(t,e),this.dependencyTracker?.recordShowTextOperation(t),void this.#rn(s)}const n=i.fontSize;if(0===n)return void this.dependencyTracker?.recordOperation(t);const a=this.#an(i.fillAlpha),r=this.ctx,o=i.fontSizeScale,l=i.charSpacing,h=i.wordSpacing,c=i.fontDirection,d=i.textHScale*c,u=e.length,p=s.vertical,g=p?1:-1,m=s.defaultVMetrics,f=n*i.fontMatrix[0],b=i.textRenderingMode===A&&!s.disableFontFace&&!i.patternFill;let y,v;r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),c>0?r.scale(d,-1):r.scale(d,1);const C=i.textRenderingMode&S,E=C===A||C===x,_=C===w||C===x;let k=i.lineWidth;const M=i.textMatrixScale;if(0===M||0===k?_&&(k=this.getSinglePixelWidth()):k/=M,1!==o&&(r.scale(o,o),k/=o),r.lineWidth=k,E&&i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,Bt(r),wi,t);y=Ft(r),r.restore(),r.fillStyle=e}if(_&&i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,Bt(r),xi,t);v=Ft(r),r.restore(),r.strokeStyle=e}if(s.isInvalidPDFjsFont){const s=[];let n=0;for(const t of e)s.push(t.unicode),n+=t.width;const o=s.join("");if(r.fillText(o,0,0),null!==this.dependencyTracker){const e=r.measureText(o);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return i.x+=n*f*d,r.restore(),this.compose(),void this.#rn(a)}let D,P=0;for(D=0;D<u;++D){const i=e[D];if("number"==typeof i){P+=g*i*n/1e3;continue}let a=!1;const d=(i.isSpace?h:0)+l,u=i.fontChar,A=i.accent;let w,x,C,S=i.width;if(p){const t=i.vmetric||m,e=-(i.vmetric?t[1]:.5*S)*f,s=t[2]*f;S=t?-t[0]:S,w=e/o,x=(P+s)/o}else w=P/o,x=0;if(s.remeasure&&S>0){C=r.measureText(u);const t=1e3*C.width/n*o;if(S<t&&this.isFontSubpixelAAEnabled){const e=S/t;a=!0,r.save(),r.scale(e,1),w/=e}else S!==t&&(w+=(S-t)/2e3*n/o)}if(this.contentVisible&&(i.isInFont||s.missingFile))if(b&&!A)r.fillText(u,w,x),this.dependencyTracker?.recordCharacterBBox(t,r,C?{bbox:null}:s,n/o,w,x,()=>C??r.measureText(u));else if(this.paintChar(t,u,w,x,y,v),A){const e=w+n*A.offset.x/o,i=x-n*A.offset.y/o;this.paintChar(t,A.fontChar,e,i,y,v)}P+=p?S*f-d*c:S*f+d*c,a&&r.restore()}p?i.y-=P:i.x+=P*d,r.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#rn(a)}showType3Text(t,e){const i=this.ctx,n=this.current,a=n.font,r=n.fontSize,o=n.fontDirection,l=a.vertical?1:-1,h=n.charSpacing,c=n.wordSpacing,d=n.textHScale*o,u=n.fontMatrix||s,p=e.length;let g,m,f,b;if(n.textRenderingMode===C||0===r)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,i.save(),n.textMatrix&&i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),i.scale(d,o);const y=this.dependencyTracker;for(this.dependencyTracker=y?new _e(y,t):null,g=0;g<p;++g){if(m=e[g],"number"==typeof m){b=l*m*r/1e3,this.ctx.translate(b,0),n.x+=b*d;continue}const t=(m.isSpace?c:0)+h,s=a.charProcOperatorList[m.operatorListId];s?this.contentVisible&&(this.save(),i.scale(r,r),i.transform(...u),this.executeOperatorList(s),this.restore()):W(`Type3 character "${m.operatorListId}" is not available.`);const o=[m.width,0];ot.applyTransform(o,u),f=o[0]*r+t,i.translate(f,0),n.x+=f*d}i.restore(),y&&(this.dependencyTracker=y)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,s,n,a,r){const o=new Path2D;o.rect(s,n,a-s,r-n),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,s,a,n,r).recordClipBox(t,this.ctx,s,a,n,r),this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||Ft(this.ctx),s={createCanvasGraphics:(t,e)=>new qi(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new _e(this.dependencyTracker,e,!0):null)};i=new Ii(e,this.ctx,s,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);const i=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0,this.current.tilingPatternDims=i instanceof Ii?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,e,i=null){let s;return this.cachedPatterns.has(e)?s=this.cachedPatterns.get(e):(s=function(t){switch(t[0]){case"RadialAxial":return new Ei(t);case"Mesh":return new ki(t);case"Dummy":return new Mi}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,s)),i&&(s.matrix=i),s}shadingFill(t,e){if(!this.contentVisible)return;const s=this.#an(this.current.fillAlpha),n=this.ctx;this.save(t);const a=this._getPattern(t,e);n.fillStyle=a.getPattern(n,this,Bt(n),Ci,t);const r=Bt(n);if(r){const{width:t,height:e}=n.canvas,s=i.slice();ot.axialAlignedBoundingBox([0,0,t,e],r,s);const[a,o,l,h]=s;this.ctx.fillRect(a,o,l-a,h-o)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,Fe).recordDependencies(t,Me).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#rn(s)}beginInlineImage(){V("Should not call beginInlineImage")}beginImageData(){V("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=Ft(this.ctx),i)){ot.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,s,n,a]=i,r=new Path2D;r.rect(e,s,n-e,a-s),this.ctx.clip(r),this.dependencyTracker?.recordClipBox(t,this.ctx,e,n,s,a),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:s}=this;s&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;if(e.isolated||e.knockout||0!==this.#$s||j("TODO: Fully support non-isolated non-knockout groups."),!e.needsIsolation&&!e.knockout&&0===this.#$s&&1===n.globalAlpha&&"source-over"===n.globalCompositeOperation&&!s){if(e.bbox){let t=new Path2D;const[i,s,a,r]=e.bbox;if(t.rect(i,s,a-i,r-s),e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix)),t=i}n.clip(t)}return this.groupStack.push(null),this.#Js.push(null),void this.groupLevel++}const a=Ft(n);e.matrix&&n.transform(...e.matrix);const r=[0,0,n.canvas.width,n.canvas.height];let o;e.bbox?(o=i.slice(),ot.axialAlignedBoundingBox(e.bbox,Ft(n),o),o=ot.intersect(o,r)||[0,0,0,0]):o=r;const l=Math.floor(o[0]),h=Math.floor(o[1]),c=Math.max(Math.ceil(o[2])-l,1),d=Math.max(Math.ceil(o[3])-h,1);this.current.startNewPathAndClipBox([0,0,c,d]);const u=this.canvasFactory.create(c,d);e.smask&&this.smaskGroupCanvases.push(u);const p=u.context,g=e.knockout&&!e.isolated?n:null,m=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#$s>0,f=e.knockout?this.canvasFactory.create(c,d):null,b=this.#$s;if(e.knockout?this.#$s++:this.#$s=0,p.translate(-l,-h),p.transform(...a),!e.isolated&&!e.smask&&s&&e.needsIsolation&&(p.save(),p.setTransform(1,0,0,1,0,0),p.drawImage(n.canvas,-l,-h),p.restore()),e.bbox){let t=new Path2D;const[i,s,n,a]=e.bbox;if(t.rect(i,s,n-i,a-s),e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix)),t=i}p.clip(t)}e.smask&&this.smaskStack.push({canvas:u.canvas,context:p,offsetX:l,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null}),e.smask&&!this.dependencyTracker||(n.setTransform(1,0,0,1,0,0),n.translate(l,h),n.save()),Gi(n,p),this.ctx=p,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(n),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(n),this.#Js.push({backdropCtx:g,savedKnockoutLevel:b,offsetX:l,offsetY:h,hasInnerBackdrop:m,knockoutMaskEntry:f,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const s=this.ctx,n=this.groupStack.pop(),a=this.#Js.pop();if(a&&(this.#$s=a.savedKnockoutLevel),null!==n)if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#tn(a);else{this.ctx.restore();const e=Ft(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const r=i.slice();ot.axialAlignedBoundingBox([0,0,s.canvas.width,s.canvas.height],e,r);const o=this.#Js.at(-1);if(this.#$s>0)if(a.hasInnerBackdrop){const{width:t,height:i}=s.canvas,r=this.canvasFactory.create(t,i),o=r.context;o.drawImage(n.canvas,a.offsetX,a.offsetY,t,i,0,0,t,i),o.globalCompositeOperation="source-over",o.drawImage(s.canvas,0,0);const l=this.#in(s.canvas);o.globalCompositeOperation="destination-in",o.drawImage(l.canvas,0,0);const h=this.ctx.globalCompositeOperation,c=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...e),this.ctx.globalAlpha=1,rt.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(l.canvas,0,0),this.ctx.globalCompositeOperation=h,this.ctx.globalAlpha=c,rt.isCanvasFilterSupported&&(this.ctx.filter=d??"none"),this.ctx.drawImage(r.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(l),this.canvasFactory.destroy(r)}else{const t=o?.backdropCtx??null;this.#nn(this.ctx,s.canvas,{backdropCanvas:t?.canvas??null,destTransform:e,backdropOffset:t?[o.offsetX+a.offsetX,o.offsetY+a.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(s.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:s.canvas,context:s}),this.#tn(a),this.compose(r)}else this.restore(t)}#tn(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,e,i,s,n,a){if(this.#Zs(),$i(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),i){const n=i[2]-i[0],r=i[3]-i[1];if(a&&this.annotationCanvasMap){(s=s.slice())[4]-=i[0],s[5]-=i[1],(i=i.slice())[0]=i[1]=0,i[2]=n,i[3]=r,ot.singularValueDecompose2dScale(Ft(this.ctx),Ri);const{viewportScale:t}=this,a=Math.ceil(n*this.outputScaleX*t),o=Math.ceil(r*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(a,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(Ri[0],0,0,-Ri[1],0,r*Ri[1]),$i(this.ctx)}else{$i(this.ctx),this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],n,r),this.ctx.clip(e)}}this.current=new Hi(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...s),this.transform(t,...n),this.baseTransform=Ft(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#en(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const s=this.#an(this.current.fillAlpha),n=this.ctx,a=this._createMaskCanvas(t,e),r=a.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(r,a.offsetX,a.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,a.offsetX,a.offsetX+r.width,a.offsetY,a.offsetY+r.height).recordOperation(t),n.restore(),a.canvasEntry&&this.canvasFactory.destroy(a.canvasEntry),this.compose(),this.#rn(s)}paintImageMaskXObjectRepeat(t,e,i,s=0,n=0,a,r){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.#an(this.current.fillAlpha),l=this.ctx;l.save();const h=Ft(l);l.transform(i,s,n,a,0,0);const c=this._createMaskCanvas(t,e);l.setTransform(1,0,0,1,c.offsetX-h[4],c.offsetY-h[5]),this.dependencyTracker?.resetBBox(t);for(let e=0,o=r.length;e<o;e+=2){const o=ot.transform(h,[i,s,n,a,r[e],r[e+1]]);l.drawImage(c.canvas,o[4],o[5]),this.dependencyTracker?.recordBBox(t,this.ctx,o[4],o[4]+c.canvas.width,o[5],o[5]+c.canvas.height)}l.restore(),c.canvasEntry&&this.canvasFactory.destroy(c.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#rn(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.#an(this.current.fillAlpha),s=this.ctx,n=this.current.fillColor,a=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Be);for(const i of e){const{data:e,width:r,height:o,transform:l}=i,h=this.canvasFactory.create(r,o),c=h.context;c.save();zi(c,this.getObject(t,e,i)),c.globalCompositeOperation="source-in",c.fillStyle=a?n.getPattern(c,this,Bt(s),wi,t):n,c.fillRect(0,0,r,o),c.restore(),s.save(),s.transform(...l),s.scale(1,-1),Ni(s,h.canvas,0,0,r,o,0,-1,1,1),this.canvasFactory.destroy(h),this.dependencyTracker?.recordBBox(t,s,0,r,0,o),s.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#rn(i)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):W("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,s,n){if(!this.contentVisible)return;const a=this.getObject(t,e);if(!a)return void W("Dependent image isn't ready yet");const r=a.width,o=a.height,l=[];for(let t=0,e=n.length;t<e;t+=2)l.push({transform:[i,0,0,s,n[t],n[t+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(t,a,l)}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{img:t.bitmap,canvasEntry:null};const{bitmap:e,width:i,height:s}=t,n=this.canvasFactory.create(i,s),a=n.context;return a.filter=this.current.transferMaps,a.drawImage(e,0,0),a.filter="none",{img:n.canvas,canvasEntry:n}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,s=e.height,n=this.#an(this.current.fillAlpha),a=this.ctx;this.save(t);const{filter:r}=a;let o;"none"!==r&&""!==r&&(a.filter="none"),a.scale(1/i,-1/s);let l=null;if(e.bitmap){const t=this.applyTransferMapsToBitmap(e);o=t.img,l=t.canvasEntry}else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)o=e;else{const t=this.canvasFactory.create(i,s);Ui(t.context,e),o=this.applyTransferMapsToCanvas(t.context),l=t}const h=this._scaleImage(o,Bt(a));a.imageSmoothingEnabled=ji(Ft(a),e.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,a,0,i,-s,0).recordDependencies(t,De).recordOperation(t),this.imagesTracker?.record(a,i,s,this.dependencyTracker.clipBox)),Ni(a,h.img,0,0,h.paintWidth,h.paintHeight,0,-s,i,s),h.tmpCanvas&&this.canvasFactory.destroy(h.tmpCanvas),l&&this.canvasFactory.destroy(l),this.compose(),this.restore(t),this.#rn(n)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const s=this.#an(this.current.fillAlpha),n=this.ctx;let a,r=null;if(e.bitmap)a=e.bitmap;else{const t=e.width,i=e.height,s=this.canvasFactory.create(t,i);Ui(s.context,e),a=this.applyTransferMapsToCanvas(s.context),r=s}this.dependencyTracker?.resetBBox(t);for(const e of i)n.save(),n.transform(...e.transform),n.scale(1,-1),Ni(n,a,e.x,e.y,e.w,e.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();r&&this.canvasFactory.destroy(r),this.dependencyTracker?.recordOperation(t),this.compose(),this.#rn(s)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const e=this.#an(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,Me).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#rn(e)}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const s=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(i);const n=this.ctx;this.pendingClip?(s||(this.pendingClip===Xi?n.clip(e,"evenodd"):n.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=Ft(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]),i=Math.hypot(t[0],t[2]),s=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,s)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:s,d:n}=this.ctx.getTransform();let a,r;if(0===i&&0===s){const i=Math.abs(e),s=Math.abs(n);if(i===s)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t)a=1/i,r=1/s;else{const e=i*t,n=s*t;a=e<1?1/e:1,r=n<1?1/n:1}}else{const o=Math.abs(e*n-i*s),l=Math.hypot(e,i),h=Math.hypot(s,n);if(0===t)a=h/o,r=l/o;else{const e=t*o;a=h>e?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:s}}=this,[n,a]=this.getScaleForStroking();if(n===a)return i.lineWidth=(s||1)*n,void i.stroke(t);const r=i.getLineDash();e&&i.save(),i.scale(n,a),Li.a=1/n,Li.d=1/a;const o=new Path2D;if(o.addPath(t,Li),r.length>0){const t=Math.max(n,a);i.setLineDash(r.map(e=>e/t)),i.lineDashOffset/=t}i.lineWidth=s||1,i.stroke(o),e&&i.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 B)void 0!==qi.prototype[t]&&(qi.prototype[B[t]]=qi.prototype[t]);class Yi{#ln=null;#hn=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t,this.#ln=e,this.#hn=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return K(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#ln(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new this.#hn(this,t,e);return this._rangeReaders.add(i),i}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class Qi{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}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(){V("Abstract method `read` called")}cancel(t){V("Abstract method `cancel` called")}}class Ji{_stream=null;constructor(t,e,i){this._stream=t}async read(){V("Abstract method `read` called")}cancel(t){V("Abstract method `cancel` called")}}function Zi(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function ts(t){return URL.parse(t)?.origin??null}function es({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={contentLength:0,isRangeSupported:!1},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;if(n.contentLength=a,a<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;return"identity"===(t.get("Content-Encoding")||"identity")&&(n.isRangeSupported=!0),n}function is(t){const e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const n=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,s,n]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[s,n]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[i,s]=e[t];s=r(s),i&&(s=unescape(s),0===t&&(s=o(s))),a.push(s)}return a.join("")}(t),i)return a(l(i));if(i=s("filename","i").exec(t),i){i=i[1];let t=r(i);return t=l(t),a(t)}function s(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function n(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const s=new TextDecoder(t,{fatal:!0}),n=at(i);i=s.decode(n),e=!1}catch{}}return i}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 i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),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 l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(t,e,i,s){if("q"===i||"Q"===i)return n(e,s=(s=s.replaceAll("_"," ")).replaceAll(/=([0-9a-f]{2})/gi,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{s=atob(s)}catch{}return n(e,s)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(Ct(t))return t}return null}function ss(t,e){return new it(`Unexpected server response (${t}) while retrieving PDF "${e.href}".`,t,404===t||0===t&&"file:"===e.protocol)}function ns(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function as(t,e,i,s){return fetch(t,{method:"GET",headers:e,signal:s.signal,mode:"cors",credentials:i?"include":"same-origin",redirect:"follow"})}function rs(t,e){if(200!==t&&206!==t)throw ss(t,e)}function os(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}class ls extends Yi{_responseOrigin=null;constructor(t){super(t,hs,cs);const{httpHeaders:e,url:i}=t;K(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=Zi(!0,e)}}class hs extends Qi{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,rangeChunkSize:s,url:n,withCredentials:a}=t._source;this._isStreamingSupported=!i;const r=new Headers(t.headers);as(n,r,a,this._abortController).then(i=>{t._responseOrigin=ts(i.url),rs(i.status,n),this._reader=i.body.getReader();const a=i.headers,{contentLength:r,isRangeSupported:o}=es({responseHeaders:a,isHttp:!0,rangeChunkSize:s,disableRange:e});this._contentLength=r,this._isRangeSupported=o,this._filename=is(a),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new nt("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}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._callOnProgress(),{value:os(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class cs extends Ji{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:s,withCredentials:n}=t._source,a=new Headers(t.headers);a.append("Range",`bytes=${e}-${i-1}`),as(s,a,n,this._abortController).then(e=>{ns(ts(e.url),t._responseOrigin),rs(e.status,s),this._reader=e.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:os(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}function ds(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function us(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class ps extends Yi{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,gs,ms);const{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:s}=e;if(i?.length>0){const t=ds(i);this._queuedChunks.push(t)}this._progressiveDone=s;e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#cn(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#cn(t,e){const i=ds(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);K(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),e._enqueue(i)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){const i=super.getRangeReader(t,e);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,e)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class gs extends Qi{#dn=us.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:s}=t._source,{length:n,contentDispositionFilename:a}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone,this._contentLength=n,this._isStreamingSupported=!s,this._isRangeSupported=!i,Ct(a)&&(this._filename=a),this._headersCapability.resolve();const r=this._loaded;Promise.resolve().then(()=>{r>0&&this._loaded===r&&this._callOnProgress()})}_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,this._callOnProgress()}}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,this.#dn()}progressiveDone(){this._done||=!0,0===this._queuedChunks.length&&this.#dn()}}class ms extends Ji{#dn=us.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i),this._begin=e}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1}),this.#dn()}this._done=!0,this.onDone?.()}}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,this.#dn(),this.onDone?.()}}class fs extends Yi{#un=new WeakMap;_responseOrigin=null;constructor(t){super(t,bs,ys);const{httpHeaders:e,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=Zi(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#un.set(e,i),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=t=>206===t||200===t):i.validateStatus=t=>200===t,e.responseType="arraybuffer",K(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#pn.bind(this,e),e.onprogress=this.#gn.bind(this,e),e.send(null),e}#gn(t,e){const i=this.#un.get(t);i?.onProgress?.(e)}#pn(t,e){const i=this.#un.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==t.readyState)return;if(!this.#un.has(t))return;if(this.#un.delete(t),0===t.status&&this.isHttp)return void i.onError(t.status);const s=t.status||200;if(!i.validateStatus(s))return void i.onError(t.status);const n="string"!=typeof(a=t.response)?a:at(a).buffer;var a;if(206===s){const e=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(e)?i.onDone(n):(W('Missing or invalid "Content-Range" header.'),i.onError(0))}else n?i.onDone(n):i.onError(t.status)}_abortRequest(t){this.#un.has(t)&&(this.#un.delete(t),t.abort())}getRangeReader(t,e){const i=super.getRangeReader(t,e);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}class bs extends Qi{#dn=us.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#mn.bind(this),onDone:this.#fn.bind(this),onError:this.#bn.bind(this),onProgress:this.#gn.bind(this)})}#mn(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,s=this._fullRequestXhr;t._responseOrigin=ts(s.responseURL);const n=s.getAllResponseHeaders(),a=new Headers(n?n.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{contentLength:r,isRangeSupported:o}=es({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});this._contentLength=r,this._isRangeSupported=o,this._filename=is(a),this._isRangeSupported&&t._abortRequest(s),this._headersCapability.resolve()}#fn(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._cachedChunks.push(t);this._done=!0,0===this._cachedChunks.length&&this.#dn()}#bn(t){this._storedError=ss(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#gn(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){if(await this._headersCapability.promise,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._headersCapability.reject(t),this.#dn(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class ys extends Ji{#dn=us.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i),this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#mn.bind(this),onDone:this.#fn.bind(this),onError:this.#bn.bind(this),onProgress:null})}#mn(){const t=ts(this._requestXhr?.responseURL);try{ns(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#bn(0)}}#fn(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0,this.#dn(),this.onClosed?.()}#bn(t){this._storedError??=ss(t,this._stream.url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}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,this.#dn(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function vs(t,e=null){const i=process.getBuiltinModule("fs"),{Readable:s}=process.getBuiltinModule("stream"),n=i.createReadStream(t,e);return s.toWeb(n)}class As extends Yi{constructor(t){super(t,ws,xs);const{url:e}=t;K("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}}class ws extends Qi{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,rangeChunkSize:s,url:n}=t._source;this._isStreamingSupported=!i;process.getBuiltinModule("fs/promises").lstat(n).then(t=>{const i=vs(n);this._reader=i.getReader();const{size:a}=t;this._contentLength=a,this._isRangeSupported=!e&&a>2*s,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new nt("Streaming is disabled.")),this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=ss(0,n)),this._headersCapability.reject(t)})}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._callOnProgress(),{value:os(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class xs extends Ji{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:s}=t._source;try{const t=vs(s,{start:e,end:i-1});this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:os(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class Cs{static#yn=null;static#vn="";static get workerPort(){return this.#yn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#yn=t}static get workerSrc(){return this.#vn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#vn=t}}class Ss{#An;#wn;constructor({parsedData:t,rawData:e}){this.#An=t,this.#wn=e}getRaw(){return this.#wn}get(t){return this.#An.get(t)??null}[Symbol.iterator](){return this.#An.entries()}}const Ts=Symbol("INTERNAL");class Es{#xn=!1;#Cn=!1;#Sn=!1;#Tn=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#xn=!!(t&o),this.#Cn=!!(t&l),this.name=e,this.intent=i,this.usage=s,this.rbGroups=n}get visible(){if(this.#Sn)return this.#Tn;if(!this.#Tn)return!1;const{print:t,view:e}=this.usage;return this.#xn?"OFF"!==e?.viewState:!this.#Cn||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ts&&V("Internal method `_setVisible` called."),this.#Sn=i,this.#Tn=e}}class _s{#En=null;#_n=new Map;#kn=null;#Mn=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.#Mn=t.order;for(const i of t.groups)this.#_n.set(i.id,new Es(e,i));if("OFF"===t.baseState)for(const t of this.#_n.values())t._setVisible(Ts,!1);for(const e of t.on)this.#_n.get(e)._setVisible(Ts,!0);for(const e of t.off)this.#_n.get(e)._setVisible(Ts,!1);this.#kn=this.getHash()}}#Dn(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s<e;s++){const e=t[s];let n;if(Array.isArray(e))n=this.#Dn(e);else{if(!this.#_n.has(e))return W(`Optional content group not found: ${e}`),!0;n=this.#_n.get(e).visible}switch(i){case"And":if(!n)return!1;break;case"Or":if(n)return!0;break;case"Not":return!n;default:return!0}}return"And"===i}isVisible(t){if(0===this.#_n.size)return!0;if(!t)return j("Optional content group not defined."),!0;if("OCG"===t.type)return this.#_n.has(t.id)?this.#_n.get(t.id).visible:(W(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#Dn(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#_n.has(e))return W(`Optional content group not found: ${e}`),!0;if(this.#_n.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#_n.has(e))return W(`Optional content group not found: ${e}`),!0;if(!this.#_n.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#_n.has(e))return W(`Optional content group not found: ${e}`),!0;if(!this.#_n.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#_n.has(e))return W(`Optional content group not found: ${e}`),!0;if(this.#_n.get(e).visible)return!1}return!0}return W(`Unknown optional content policy ${t.policy}.`),!0}return W(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const s=this.#_n.get(t);if(s){if(i&&e&&s.rbGroups.length)for(const e of s.rbGroups)for(const i of e)i!==t&&this.#_n.get(i)?._setVisible(Ts,!1,!0);s._setVisible(Ts,!!e,!0),this.#En=null}else W(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const s of t){switch(s){case"ON":case"OFF":case"Toggle":i=s;continue}const t=this.#_n.get(s);if(t)switch(i){case"ON":this.setVisibility(s,!0,e);break;case"OFF":this.setVisibility(s,!1,e);break;case"Toggle":this.setVisibility(s,!t.visible,e)}}this.#En=null}get hasInitialVisibility(){return null===this.#kn||this.getHash()===this.#kn}getOrder(){return this.#_n.size?this.#Mn?this.#Mn.slice():[...this.#_n.keys()]:null}getGroup(t){return this.#_n.get(t)||null}getHash(){if(null!==this.#En)return this.#En;const t=new ge;for(const[e,i]of this.#_n)t.update(`${e}:${i.visible}`);return this.#En=t.hexdigest()}[Symbol.iterator](){return this.#_n.entries()}}class ks{#Pn=null;#In=null;#Fn=0;#Bn=null;#Ln=null;get pagesNumber(){return this.#Fn}set pagesNumber(t){this.#Fn!==t&&(this.#Fn=t,this.#Pn=null,this.#In=null)}#Rn(){if(this.#Pn)return;const t=this.#Fn,e=this.#Pn=new Uint32Array(t);for(let i=0;i<t;i++)e[i]=i+1;this.#In=new Int32Array(e)}#On(){const t=new Map,e=this.#Pn;for(let i=0,s=this.#Fn;i<s;i++){const s=e[i],n=t.get(s);n?n.push(i+1):t.set(s,[i+1])}return t}movePages(t,e,i){this.#Rn();const s=this.#Pn,n=this.#On(),a=e.length,r=new Uint32Array(a);let o=0;for(let t=0;t<a;t++){const n=e[t]-1;r[t]=s[n],n<i&&o++}const l=this.#Fn,h=l-a,c=mt(i-o,0,h);for(let e=0,i=0;e<l;e++)t.has(e+1)||(s[i++]=s[e]);s.copyWithin(c+a,c,h),s.set(r,c),this.#Nn(n),s.every((t,e)=>t===e+1)&&(this.#Pn=null)}deletePages(t){this.#Rn();const e=this.#Pn,i=this.#On();this.#Ln={pageNumberToId:e.slice(),pagesNumber:this.#Fn,prevPageNumbers:this.#In.slice()};const s=this.#Fn-t.length;this.#Fn=s;const n=this.#Pn=new Uint32Array(s);this.#In=new Int32Array(s);let a=0,r=0;for(const i of t){const t=i-1;t!==a&&(n.set(e.subarray(a,t),r),r+=t-a),a=t+1}a<e.length&&n.set(e.subarray(a),r),this.#Nn(i,new Set(t))}cancelDelete(){this.#Ln&&(this.#Pn=this.#Ln.pageNumberToId,this.#Fn=this.#Ln.pagesNumber,this.#In=this.#Ln.prevPageNumbers,this.#Ln=null)}cleanSavedData(){this.#Ln=null}copyPages(t){this.#Rn(),this.#Bn={pageNumbers:t,pageIds:t.map(t=>this.#Pn[t-1])}}cancelCopy(){this.#Bn=null}pastePages(t){this.#Rn();const e=this.#Pn,i=this.#On(),{pageNumbers:s,pageIds:n}=this.#Bn,a=this.#Fn+s.length;this.#Fn=a;const r=this.#Pn=new Uint32Array(a);this.#In=new Int32Array(a),r.set(e.subarray(0,t),0),r.set(n,t),r.set(e.subarray(t),t+s.length),this.#Nn(i,null,t,s),this.#Bn=null}#Nn(t,e=null,i=-1,s=null){const n=this.#In,a=this.#Pn,r=i+(s?.length??0),o=new Map;for(let l=0,h=this.#Fn;l<h;l++){if(l>=i&&l<r){n[l]=-s[l-i];continue}const h=a[l],c=t.get(h);let d=o.get(h)||0;if(e&&c)for(;d<c.length&&e.has(c[d]);)d++;n[l]=c?.[d],o.set(h,d+1)}}hasBeenAltered(){return null!==this.#Pn}getPageMappingForSaving(t=null){t??=this.#On();let e=0;for(const i of t.values())e=Math.max(e,i.length);const i=new Array(e);for(let t=0;t<e;t++)i[t]={document:null,pageIndices:[],includePages:[]};for(const[e,s]of t)for(let t=0,n=s.length;t<n;t++)i[t].includePages.push([e-1,s[t]-1]);for(const{includePages:t,pageIndices:e}of i){t.sort((t,e)=>t[0]-e[0]);for(let i=0,s=t.length;i<s;i++)e.push(t[i][1]),t[i]=t[i][0]}return i}extractPages(t){t=Array.from(t).sort((t,e)=>t-e);const e=new Map;for(let i=0,s=t.length;i<s;i++){const s=this.getPageId(t[i]);e.getOrInsertComputed(s,ut).push(i+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#In?.[t-1]??0}getPageNumber(t){if(!this.#Pn)return t;const e=this.#Pn;for(let i=0,s=this.#Fn;i<s;i++)if(e[i]===t)return i+1;return 0}getPageId(t){return this.#Pn?.[t-1]??t}getMapping(){return this.#Pn?.subarray(0,this.pagesNumber)}}const Ms=Symbol("INITIAL_DATA"),Ds=()=>({...Promise.withResolvers(),data:Ms});class Ps{#Hn=new Map;get(t,e=null){if(e){const i=this.#Hn.getOrInsertComputed(t,Ds);return i.promise.then(()=>e(i.data)),null}const i=this.#Hn.get(t);if(!i||i.data===Ms)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Hn.get(t);return!!e&&e.data!==Ms}delete(t){const e=this.#Hn.get(t);return!(!e||e.data===Ms)&&(this.#Hn.delete(t),!0)}resolve(t,e=null){const i=this.#Hn.getOrInsertComputed(t,Ds);if(i.data!==Ms)throw new Error(`Object already resolved ${t}.`);i.data=e,i.resolve()}clear(){for(const{data:t}of this.#Hn.values())t?.bitmap?.close();this.#Hn.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#Hn)e!==Ms&&(yield[t,e])}}class Is{#Un=Promise.withResolvers();#_t=null;#zn=!1;#Gn=!!globalThis.FontInspector?.enabled;#$n=null;#jn=null;#Wn=null;#Vn=0;#Kn=0;#Xn=null;#qn=null;#Yn=0;#Qn=0;#Jn=Object.create(null);#Zn=[];#ta=null;#ea=[];#ia=new WeakMap;#sa=null;static#na=new Map;static#aa=new Map;static#ra=new WeakMap;static#oa=null;static#la=new Set;constructor({textContentSource:t,images:e,container:i,viewport:s}){if(t instanceof ReadableStream)this.#ta=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#ta=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#_t=this.#qn=i,this.#$n=e,this.#Qn=s.scale*Rt.pixelRatio,this.#Yn=s.rotation,this.#Wn={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:a,pageX:r,pageY:o}=s.rawDims;this.#sa=[1,0,0,-1,-r,o+a],this.#Kn=n,this.#Vn=a,Is.#ha(),i.style.setProperty("--min-font-size",Is.#oa),Lt(i,s),this.#Un.promise.finally(()=>{Is.#la.delete(this),this.#Wn=null,this.#Jn=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=rt.platform;return Q(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){this.#$n&&this.#_t.append(this.#$n.render());const t=()=>{this.#Xn.read().then(({value:e,done:i})=>{i?this.#Un.resolve():(this.#jn??=e.lang,Object.assign(this.#Jn,e.styles),this.#ca(e.items),t())},this.#Un.reject)};return this.#Xn=this.#ta.getReader(),Is.#la.add(this),t(),this.#Un.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*Rt.pixelRatio,s=t.rotation;if(s!==this.#Yn&&(e?.(),this.#Yn=s,Lt(this.#qn,{rotation:s})),i!==this.#Qn){e?.(),this.#Qn=i;const t={div:null,properties:null,ctx:Is.#da(this.#jn)};for(const e of this.#ea)t.properties=this.#ia.get(e),t.div=e,this.#ua(t)}}cancel(){const t=new nt("TextLayer task cancelled.");this.#Xn?.cancel(t).catch(()=>{}),this.#Xn=null,this.#Un.reject(t)}get textDivs(){return this.#ea}get textContentItemsStr(){return this.#Zn}#ca(t){if(this.#zn)return;this.#Wn.ctx??=Is.#da(this.#jn);const e=this.#ea,i=this.#Zn;for(const s of t){if(e.length>1e5)return W("Ignoring additional textDivs for performance reasons."),void(this.#zn=!0);if(void 0!==s.str)i.push(s.str),this.#pa(s);else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#_t;this.#_t=document.createElement("span"),this.#_t.classList.add("markedContent"),s.id&&this.#_t.setAttribute("id",`${s.id}`),"Artifact"===s.tag&&(this.#_t.ariaHidden=!0),t.append(this.#_t)}else"endMarkedContent"===s.type&&(this.#_t=this.#_t.parentNode)}}#pa(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ea.push(e);const s=ot.transform(this.#sa,t.transform);let n=Math.atan2(s[1],s[0]);const a=this.#Jn[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Gn&&a.fontSubstitution||a.fontFamily;r=Is.fontFamilyMap.get(r)||r;const o=Math.hypot(s[2],s[3]),l=o*Is.#ga(r,a,this.#jn);let h,c;0===n?(h=s[4],c=s[5]-l):(h=s[4]+l*Math.sin(n),c=s[5]-l*Math.cos(n));const d=e.style;d.left=`${(100*h/this.#Kn).toFixed(2)}%`,d.top=`${(100*c/this.#Vn).toFixed(2)}%`,d.setProperty("--font-height",`${o.toFixed(2)}px`),d.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#Gn&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==n&&(i.angle=n*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(u=!0)}if(u&&(i.canvasWidth=a.vertical?t.height:t.width),this.#ia.set(e,i),this.#Wn.div=e,this.#Wn.properties=i,this.#ua(this.#Wn),i.hasText&&this.#_t.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#_t.append(t)}}#ua(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:a,fontSize:r}=i;Is.#ma(s,r*this.#Qn,t);const{width:o}=s.measureText(e.textContent);o>0&&n.setProperty("--scale-x",a*this.#Qn/o)}0!==i.angle&&n.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#la.size>0)){this.#na.clear();for(const{canvas:t}of this.#aa.values())t.remove();this.#aa.clear()}}static#da(t=null){let e=this.#aa.get(t||="");if(!e){const i=document.createElement("canvas");i.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#aa.set(t,e),this.#ra.set(e,{size:0,family:""})}return e}static#ma(t,e,i){const s=this.#ra.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#ha(){if(null!==this.#oa)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#oa=t.getBoundingClientRect().height,t.remove()}static#ga(t,e,i){const s=this.#na.get(t);if(s)return s;const n=this.#da(i);n.canvas.width=n.canvas.height=30,this.#ma(n,30,t);const a=n.measureText(""),r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;return r?l=r/(r+o):(rt.platform.isFirefox&&W("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#na.set(t,l),l}}function Fs(e={}){const i=new Bs,{docId:s}=i,n=e.url?function(e){if(e instanceof URL)return e;if("string"==typeof e){if(t){if(/^[a-z][a-z0-9\-+.]+:/i.test(e))return new URL(e);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(e))}const i=URL.parse(e,window.location);if(i)return i}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(e.url):null,a=e.data?function(e){if(t&&"undefined"!=typeof Buffer&&e instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if("string"==typeof e)return at(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||"object"==typeof e&&!isNaN(e?.length))return new Uint8Array(e);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(e.data):null,r=e.httpHeaders||null,o=!0===e.withCredentials,l=e.password??null,h=e.range instanceof Ls?e.range:null,c=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536;let d=e.worker instanceof Ns?e.worker:null;const u=e.verbosity,p="string"!=typeof e.docBaseUrl||xt(e.docBaseUrl)?null:e.docBaseUrl,g=Ke(e.cMapUrl),m=!1!==e.cMapPacked,f=Ke(e.iccUrl),b=Ke(e.standardFontDataUrl),y=Ke(e.wasmUrl),v=!0!==e.stopAtErrors,A=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,w="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,x="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t,C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,S="boolean"==typeof e.disableFontFace?e.disableFontFace:t,T=!0===e.fontExtraProperties,E=!0===e.enableXfa,_=e.ownerDocument||globalThis.document,k=!0===e.disableRange,M=!0===e.disableStream,D=!0===e.disableAutoFetch,P=!0===e.pdfBug,I=e.CanvasFactory||(t?yi:pi),F=e.FilterFactory||(t?bi:mi),B=e.BinaryDataFactory||(t?vi:di),L=!0===e.enableHWA,R=!0===e.enableWebGPU?Ai.init():Promise.resolve(!1),O=!1!==e.useWasm,N=e.pagesMapper||new ks,H="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!S,U="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(B===di&&g&&m&&b&&y&&_t(g,document.baseURI)&&_t(b,document.baseURI)&&_t(y,document.baseURI));G(u);const z={canvasFactory:new I({ownerDocument:_,enableHWA:L}),filterFactory:new F({docId:s,ownerDocument:_}),binaryDataFactory:U?null:new B({cMapUrl:g,standardFontDataUrl:b,wasmUrl:y})};d||(d=Ns.create({verbosity:u,port:Cs.workerPort}),i._worker=d);const $={docId:s,apiVersion:"6.0.227",data:a,password:l,disableAutoFetch:D,rangeChunkSize:c,docBaseUrl:p,enableXfa:E,evaluatorOptions:{maxImageSize:A,disableFontFace:S,ignoreErrors:v,isOffscreenCanvasSupported:w,isImageDecoderSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:T,useSystemFonts:H,useWasm:O,useWorkerFetch:U,cMapUrl:g,cMapPacked:m,iccUrl:f,standardFontDataUrl:b,wasmUrl:y,hasGPU:!1}},j={ownerDocument:_,pdfBug:P,styleElement:null,enableHWA:L,loadingParams:{disableAutoFetch:D,enableXfa:E}};return Promise.all([d.promise,R]).then(function([,e]){if(d.destroyed)throw new Error("Worker was destroyed");$.evaluatorOptions.hasGPU=e;const l=d.messageHandler.sendWithPromise("GetDocRequest",$,a?[a.buffer]:null);let u;if(a);else if(h)u=new ps({pdfDataRangeTransport:h,disableRange:k,disableStream:M});else{if(!n)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const e=function(e){return _t(e)?ls:t?As:fs}(n);u=new e({url:n,httpHeaders:r,withCredentials:o,rangeChunkSize:c,disableRange:k,disableStream:M})}}return l.then(t=>{if(d.destroyed)throw new Error("Worker was destroyed");const e=new hi(s,t,d.port),n=new Hs(e,i,u,j,z,N);if(i._transport=n,i.destroyed)throw new Error("Loading aborted");e.send("Ready",null)})}).catch(i._capability.reject).finally(i._setupCapability.resolve),i}class Bs{static#xs=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+Bs.#xs++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class Ls{#Un=Promise.withResolvers();#fa=null;constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s}onDataRange(t,e){this.#fa({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#Un.promise.then(()=>{this.#fa({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#Un.promise.then(()=>{this.#fa({type:"progressiveDone"})})}transportReady(t){this.#fa=t,this.#Un.resolve()}requestDataRange(t,e){V("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Rs{constructor(t,e){this._pdfInfo=t,this._transport=e}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Q(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()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}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()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}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 Os{#ba=!1;#ya=null;constructor(t,e,i,s,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=n?new Et:null,this._pdfBug=n,this.commonObjs=i.commonObjs,this.objs=new Ps,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#ya=s,this.imageCoordinates=null}clone(t){const e=new Os(t,this._pageInfo,this._transport,this.#ya,this._pdfBug);return e.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(e),e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}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:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new ft({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,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 Q(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:s="display",annotationMode:n=g.ENABLE,transform:a=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:c=null,printAnnotationStorage:d=null,isEditing:u=!1,recordImages:p=!1,recordOperations:m=!1,operationsFilter:f=null}){this._stats?.time("Overall");const b=this._transport.getRenderingIntent(s,n,d,u),{renderingIntent:y,cacheKey:v}=b;this.#ba=!1,o||=this._transport.getOptionalContentConfig(y);const A=this._intentStates.getOrInsertComputed(v,gt);A.streamReaderCancelTimeout&&(clearTimeout(A.streamReaderCancelTimeout),A.streamReaderCancelTimeout=null);const w=!!(y&l);A.displayReadyCapability||(A.displayReadyCapability=Promise.withResolvers(),A.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(b));const x=!(!this._pdfBug||!globalThis.StepperManager?.enabled),C=!!e&&!this.recordedBBoxes&&(m||x),S=!!e&&!this.imageCoordinates&&p,T=t=>{if(A.renderTasks.delete(k),C){const t=k.gfx?.dependencyTracker.take();t&&(k.stepper?.setOperatorBBoxes(t,k.gfx.dependencyTracker.takeDebugMetadata()),m&&(this.recordedBBoxes=t))}S&&!t&&(this.imageCoordinates=k.gfx?.imagesTracker.take()),w&&(this.#ba=!0),this.#va(),t?(k.capability.reject(t),this._abortOperatorList({intentState:A,reason:t instanceof Error?t:new Error(t)})):k.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let E=null,_=null;(C||S)&&(_=new Te(e,A.operatorList.length)),C&&(E=new Ee(_,x));const k=new zs({callback:T,params:{canvas:e,canvasContext:t,dependencyTracker:E??_,imagesTracker:S?new Le(e):null,viewport:i,transform:a,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:A.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!w,pdfBug:this._pdfBug,pageColors:c,enableHWA:this._transport.enableHWA,operationsFilter:f});(A.renderTasks||=new Set).add(k);const M=k.task;return Promise.all([A.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)T();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");k.initializeGraphics({transparency:t,optionalContentConfig:e}),k.operatorListChanged()}}).catch(T),M}getOperatorList({intent:t="display",annotationMode:e=g.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0),a=this._intentStates.getOrInsertComputed(n.cacheKey,gt);let r;return a.opListReadCapability||(r=Object.create(null),r.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(r))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(r),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#ya.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>bt.textContent(t));const e=this.streamTextContent(t),i={items:[],styles:Object.create(null),lang:null};for await(const t of e)i.lang??=t.lang,Object.assign(i.styles,t.styles),i.items.push(...t.items);return i}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 i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#ba=!1,Promise.all(t)}cleanup(t=!1){this.#ba=!0;const e=this.#va();return t&&e&&(this._stats&&=new Et),e}#va(){if(!this.#ba||this.destroyed)return!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.#ba=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i<s;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#va()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:s}){const{map:n,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#ya.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:s},void 0,a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const l=()=>{r.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#va()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof wt){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i))}}if(t.streamReader.cancel(new nt(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class Ns{#Un=Promise.withResolvers();#Aa=null;#yn=null;#wa=null;static#xa=0;static#Ca=!1;static#Sa=new WeakMap;static{t&&(this.#Ca=!0,Cs.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=$()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(Ns.#Sa.has(e))throw new Error("Cannot use more than one PDFWorker per port.");Ns.#Sa.set(e,this),this.#Ta(e)}else this.#Ea()}get promise(){return this.#Un.promise}#_a(){this.#Un.resolve(),this.#Aa.send("configure",{verbosity:this.verbosity})}get port(){return this.#yn}get messageHandler(){return this.#Aa}#Ta(t){this.#yn=t,this.#Aa=new hi("main","worker",t),this.#Aa.on("ready",()=>{}),this.#_a()}#Ea(){if(Ns.#Ca||Ns.#ka)return void this.#Ma();let{workerSrc:t}=Ns;try{Ns._isSameOrigin(window.location,t)||(t=Ns._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new hi("main","worker",e),s=()=>{n.abort(),i.destroy(),e.terminate(),this.destroyed?this.#Un.reject(new Error("Worker was destroyed")):this.#Ma()},n=new AbortController;e.addEventListener("error",()=>{this.#wa||s()},{signal:n.signal}),i.on("test",t=>{n.abort(),!this.destroyed&&t?(this.#Aa=i,this.#yn=e,this.#wa=e,this.#_a()):s()}),i.on("ready",t=>{if(n.abort(),this.destroyed)s();else try{a()}catch{this.#Ma()}});const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{j("The worker has been disabled.")}this.#Ma()}#Ma(){Ns.#Ca||(W("Setting up fake worker."),Ns.#Ca=!0),Ns._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#Un.reject(new Error("Worker was destroyed"));const e=new Ye;this.#yn=e;const i="fake"+Ns.#xa++,s=new hi(i+"_worker",i,e);t.setup(s,e),this.#Aa=new hi(i,i+"_worker",e),this.#_a()}).catch(t=>{this.#Un.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#wa?.terminate(),this.#wa=null,Ns.#Sa.delete(this.#yn),this.#yn=null,this.#Aa?.destroy(),this.#Aa=null}static create(t){const e=this.#Sa.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new Ns(t)}static get workerSrc(){if(Cs.workerSrc)return Cs.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#ka(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Q(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#ka)return this.#ka;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class Hs{downloadInfoCapability=Promise.withResolvers();#Da=null;#Pa=new Map;#Ia=null;#Fa=new Map;#Ba=new Map;#La=new Map;#Ra=null;constructor(t,e,i,s,n,a){this.messageHandler=t,this.loadingTask=e,this.#Ia=i,this.commonObjs=new Ps,this.fontLoader=new Re({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.enableHWA=s.enableHWA,this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.binaryDataFactory=n.binaryDataFactory,this.pagesMapper=a,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#Fa.set(e,t),this.#Ba.set(e,Promise.resolve(t))}#Oa(t,e=null){return this.#Pa.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#gn({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?mt(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return Q(this,"annotationStorage",new fe)}getRenderingIntent(t,e=g.ENABLE,i=null,s=!1,n=!1){let a=o,m=me;switch(t){case"any":a=r;break;case"display":break;case"print":a=l;break;default:W(`getRenderingIntent - invalid intent: ${t}`)}const f=a&l&&i instanceof be?i:this.annotationStorage;switch(e){case g.DISABLE:a+=d;break;case g.ENABLE:break;case g.ENABLE_FORMS:a+=h;break;case g.ENABLE_STORAGE:a+=c,m=f.serializable;break;default:W(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(a+=u),n&&(a+=p);const{ids:b,hash:y}=f.modifiedIds;return{renderingIntent:a,cacheKey:[a,m.hash,y].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#Ra?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Fa.values())t.push(e._destroy());this.#Fa.clear(),this.#Ba.clear(),this.#La.clear(),Object.hasOwn(this,"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.#Pa.clear(),this.filterFactory.destroy(),Is.cleanup(),this.#Ia?.cancelAllRequests(new nt("Worker was terminated.")),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)=>{K(this.#Ia,"GetReader - no `BasePDFStream` instance available."),this.#Da=this.#Ia.getFullReader(),this.#Da.onProgress=t=>this.#gn(t),e.onPull=()=>{this.#Da.read().then(function({value:t,done:i}){i?e.close():(K(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this.#Da.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this.#Da.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:s}=this.#Da;return e&&i&&(this.#Da.onProgress=null),{isStreamingSupported:e,isRangeSupported:i,contentLength:s}}),t.on("GetRangeReader",(t,e)=>{K(this.#Ia,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#Ia.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then(function({value:t,done:i}){i?e.close():(K(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages,this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new Rs(t,this))}),t.on("DocException",t=>{e._capability.reject(li(t))}),t.on("PasswordRequest",t=>{this.#Ra=Promise.withResolvers();try{if(!e.onPassword)throw li(t);const i=t=>{t instanceof Error?this.#Ra.reject(t):this.#Ra.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#Ra.reject(t)}return this.#Ra.promise}),t.on("DataLoaded",t=>{this.#gn({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#Fa.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in s){const t=s.error;W(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const n=new je(s),a=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,r=new Oe(n,a,s.charProcOperatorList,s.extra);this.fontLoader.bind(r).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{r.fontExtraProperties||r.clearData(),this.commonObjs.resolve(e,r)});break;case"CopyLocalImage":const{imageRef:o}=s;K(o,"The imageRef must be defined.");for(const t of this.#Fa.values())for(const[,i]of t.objs){if(i?.ref!==o)continue;if(!i.dataLen)return null;const t=structuredClone(i);return this.commonObjs.resolve(e,t),i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new Ve(s));break;case"Image":this.commonObjs.resolve(e,s);break;case"Pattern":const l=new We(s);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Fa.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||this.#gn(t)}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&W("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.#Da?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let i;const s=globalThis.ImageBitmap;if("function"==typeof s){const e=Array.isArray(t)?t:[t];for(const t of e)t?.image instanceof s&&(i||=[]).push(t.image)}if(this.annotationStorage.size>0){const t=this.annotationStorage.serializable;let{map:s}=t;t.transfer?.length&&(i?i.push(...t.transfer):i=t.transfer);const n=this.pagesMapper.getMapping();if(n){const t=new Map;for(const[e,i]of s){if(void 0!==i?.pageIndex&&i.pageIndex>=0&&i.pageIndex<n.length){const s=n[i.pageIndex]-1;if(s!==i.pageIndex){t.set(e,{...i,pageIndex:s});continue}}t.set(e,i)}s=t}e.annotationStorage=s}return this.messageHandler.sendWithPromise("ExtractPages",e,i).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.pagesMapper.getPageId(t)-1,s=this.#Ba.get(e);if(s)return s;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#La.set(t.refStr,i);const s=new Os(e,t,this,this.pagesMapper,this._params.pdfBug);return this.#Fa.set(e,s),s});return this.#Ba.set(e,n),n}async getPageIndex(t){if(!Xe(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),i=this.pagesMapper.getPageNumber(e+1);if(0===i)throw new Error("GetPageIndex: page has been removed.");return i-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#Oa("GetFieldObjects")}hasJSActions(){return this.#Oa("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)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Oa("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Oa("GetOptionalContentConfig").then(e=>new _s(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Pa.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Ss(t[1]):null,contentDispositionFilename:this.#Da?.filename??null,contentLength:this.#Da?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Fa.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#Pa.clear(),this.filterFactory.destroy(!0),Is.cleanup()}}cachedPageNumber(t){if(!Xe(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#La.get(e);if(i>=0){const t=this.pagesMapper.getPageNumber(i+1);if(0!==t)return t}return null}}class Us{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class zs{#Na=null;static#Ha=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=c,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Us(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.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._imagesTracker=e.imagesTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(zs.#Ha.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.");zs.#Ha.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{viewport:i,transform:s,background:n,dependencyTracker:a,imagesTracker:r}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new qi(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,a,r),this.gfx.beginDrawing({transform:s,viewport:i,transparency:t,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Na&&(window.cancelAnimationFrame(this.#Na),this.#Na=null),zs.#Ha.delete(this._canvas),t||=new wt(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),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.#Na=window.requestAnimationFrame(()=>{this.#Na=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._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),zs.#Ha.delete(this._canvas),this.callback())))}}const Gs="6.0.227",$s="241dbabbf";class js{#Ua=null;#za=null;#Ga;#$a=null;#ja=!1;#Wa=!1;#r=null;#Va;#Ka=null;#y=null;static#Xa=null;static get _keyboardManager(){return Q(this,"_keyboardManager",new se([[["Escape","mac+Escape"],js.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],js.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],js.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],js.prototype._moveToPrevious],[["Home","mac+Home"],js.prototype._moveToBeginning],[["End","mac+End"],js.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#Wa=!1,this.#r=t):this.#Wa=!0,this.#y=t?._uiManager||e,this.#Va=this.#y._eventBus,this.#Ga=t?.color?.toUpperCase()||this.#y?.highlightColors.values().next().value||"#FFFF98",js.#Xa||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Ua=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#r&&(t.ariaControls=`${this.#r.id}_colorpicker_dropdown`);const e=this.#y._signal;t.addEventListener("click",this.#qa.bind(this),{signal:e}),t.addEventListener("keydown",this.#Ya.bind(this),{signal:e});const i=this.#za=document.createElement("span");return i.className="swatch",i.ariaHidden="true",i.style.backgroundColor=this.#Ga,t.append(i),t}renderMainDropdown(){const t=this.#$a=this.#Qa();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#Qa(){const t=document.createElement("div"),e=this.#y._signal;t.addEventListener("contextmenu",kt,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#r&&(t.id=`${this.#r.id}_colorpicker_dropdown`);for(const[i,s]of this.#y.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",s),n.title=i,n.setAttribute("data-l10n-id",js.#Xa[i]);const a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=s,n.ariaSelected=s===this.#Ga,n.addEventListener("click",this.#Ja.bind(this,s),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#Ya.bind(this),{signal:e}),t}#Ja(t,e){e.stopPropagation(),this.#Va.dispatch("switchannotationeditorparams",{source:this,type:y.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Ua)return void this.#qa(t);const e=t.target.getAttribute("data-color");e&&this.#Ja(e,t)}_moveToNext(t){this.#Za?t.target!==this.#Ua?t.target.nextSibling?.focus():this.#$a.firstElementChild?.focus():this.#qa(t)}_moveToPrevious(t){t.target!==this.#$a?.firstElementChild&&t.target!==this.#Ua?(this.#Za||this.#qa(t),t.target.previousSibling?.focus()):this.#Za&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Za?this.#$a.firstElementChild?.focus():this.#qa(t)}_moveToEnd(t){this.#Za?this.#$a.lastElementChild?.focus():this.#qa(t)}#Ya(t){js._keyboardManager.exec(this,t)}#qa(t){if(this.#Za)return void this.hideDropdown();if(this.#ja=0===t.detail,this.#Ka||(this.#Ka=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#y.combinedSignal(this.#Ka)})),this.#Ua.ariaExpanded="true",this.#$a)return void this.#$a.classList.remove("hidden");const e=this.#$a=this.#Qa();this.#Ua.append(e)}#p(t){this.#$a?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#$a?.classList.add("hidden"),this.#Ua.ariaExpanded="false",this.#Ka?.abort(),this.#Ka=null}get#Za(){return this.#$a&&!this.#$a.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Wa||(this.#Za?(this.hideDropdown(),this.#Ua.focus({preventScroll:!0,focusVisible:this.#ja})):this.#r?.unselect())}updateColor(t){if(this.#za&&(this.#za.style.backgroundColor=t),!this.#$a)return;const e=this.#y.highlightColors.values();for(const i of this.#$a.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Ua?.remove(),this.#Ua=null,this.#za=null,this.#$a?.remove(),this.#$a=null}}class Ws{#tr=null;#er=!1;#r=null;#y=null;static#Xa=null;constructor(t){this.#r=t,this.#y=t._uiManager,Ws.#Xa||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#tr)return this.#tr;const{editorType:t,colorType:e,colorAndOpacityType:i,opacityType:s,color:n,opacity:a}=this.#r,r=this.#er=rt.isAlphaColorInputSupported&&void 0!==s,o=this.#tr=document.createElement("input");if(o.type="color",r){o.setAttribute("alpha","");const t=ot.hexNums[Math.round(255*(a??1))];o.value=(n||"#000000")+t}else o.value=n||"#000000";return o.className="basicColorPicker",o.tabIndex=0,o.setAttribute("data-l10n-id",Ws.#Xa[t]),o.addEventListener("input",()=>{if(r){const t=Pt(o.value);if(!t)return;const[n,a,r,l]=t,h=ot.makeHexColor(n,a,r);void 0!==i?this.#y.updateParams(i,{color:h,opacity:l}):(this.#y.updateParams(e,h),this.#y.updateParams(s,l))}else this.#y.updateParams(e,o.value)},{signal:this.#y._signal}),o}update(t){if(this.#tr)if(this.#er){const e=ot.hexNums[Math.round(255*this.#r.opacity)];this.#tr.value=t+e}else this.#tr.value=t}updateOpacity(t){if(!this.#tr||!this.#er)return;const e=ot.hexNums[Math.round(255*t)];this.#tr.value=this.#r.color+e}destroy(){this.#tr?.remove(),this.#tr=null}hideDropdown(){}}function Vs(t){return Math.floor(255*mt(t,0,1)).toString(16).padStart(2,"0")}function Ks(t){return 255*mt(t,0,1)}class Xs{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}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=Ks(t),t,t]}static G_HTML([t]){const e=Vs(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(Ks)}static RGB_HTML(t){return`#${t.map(Vs).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[Ks(1-Math.min(1,t+s)),Ks(1-Math.min(1,i+s)),Ks(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,a=1-i;return["CMYK",s,n,a,Math.min(s,n,a)]}}class qs{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){V("Abstract method `_createSVG` called.")}}class Ys extends qs{_createSVG(t){return document.createElementNS(a,t)}}const Qs=new WeakSet,Js=60*(new Date).getTimezoneOffset()*1e3;class Zs{static create(t){switch(t.data.annotationType){case _.LINK:return new sn(t);case _.TEXT:return new nn(t);case _.WIDGET:switch(t.data.fieldType){case"Tx":return new rn(t);case"Btn":return t.data.radioButton?new hn(t):t.data.checkBox?new ln(t):new cn(t);case"Ch":return new dn(t);case"Sig":return new on(t)}return new an(t);case _.POPUP:return new un(t);case _.FREETEXT:return new gn(t);case _.LINE:return new mn(t);case _.SQUARE:return new fn(t);case _.CIRCLE:return new bn(t);case _.POLYLINE:return new yn(t);case _.CARET:return new An(t);case _.INK:return new wn(t);case _.POLYGON:return new vn(t);case _.HIGHLIGHT:return new xn(t);case _.UNDERLINE:return new Cn(t);case _.SQUIGGLY:return new Sn(t);case _.STRIKEOUT:return new Tn(t);case _.STAMP:return new En(t);case _.FILEATTACHMENT:return new _n(t);default:return new tn(t)}}}class tn{#ir=null;#sr=!1;#nr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!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.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return tn._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:s}=this.data;let n=-1/0,a=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>a?(a=e[t+1],n=e[t+2]):e[t+1]===a&&(n=Math.max(n,e[t+2]));return[n,a]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)t[e+1]>a?(a=t[e+1],n=t[e]):t[e+1]===a&&(n=Math.max(n,t[e]));if(n!==1/0)return[n,a]}return s?[s[2],s[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:a}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-n)/i,t[1]=100*(t[1]-a)/s,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${f}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${f}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#nr?.popup||this.popup)?.remove(),this.#nr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#ir||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#ar(e);let s=this.#nr?.popup||this.popup;!s&&i?.text&&(this._createPopup(i),s=this.#nr.popup),s&&(s.updateEdited(t),i?.deleted&&(s.remove(),this.#nr=null,this.popup=null))}resetEdited(){this.#ir&&(this.#ar(this.#ir.rect),this.#nr?.popup.resetEdited(),this.#ir=null)}#ar(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-r)/n+"%",e.top=100*(a-t[3]+o)/a+"%",0===s?(e.width=100*(t[2]-t[0])/n+"%",e.height=100*(t[3]-t[1])/a+"%"):this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof an||this instanceof sn||(n.tabIndex=0);const{style:a}=n;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof un){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,n),n}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;a.borderRadius=e}else if(this instanceof hn){const t=`calc(${r}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case k:a.borderStyle="solid";break;case M:a.borderStyle="dashed";break;case D:W("Unimplemented border style: beveled");break;case P:W("Unimplemented border style: inset");break;case I:a.borderBottomStyle="solid"}const s=e.borderColor||null;s?(this.#sr=!0,a.borderColor=ot.makeHexColor(...s)):a.borderWidth=0}const l=ot.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=s.rawDims;a.left=100*(l[0]-d)/h+"%",a.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/c+"%"):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims;let{width:n,height:a}=this;t%180!=0&&([n,a]=[a,n]),e.style.width=100*n/i+"%",e.style.height=100*a/s+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const s=i.detail[t],n=s[0],a=s.slice(1);i.target.style[e]=Xs[`${n}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:Xs[`${n}_rgb`](a)})};return Q(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,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 i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const a=i[s];if(a){a({detail:{[s]:n},target:t}),delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(s===a&&n===r&&e===o&&i===l)return}const{style:r}=this.container;let o;if(this.#sr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",`<svg xmlns="${a}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}const l=s-e,h=n-i,{svgFactory:c}=this,d=c.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";const u=c.createElement("defs");d.append(u);const p=c.createElement("clipPath"),g=`clippath_${this.data.id}`;p.setAttribute("id",g),p.setAttribute("clipPathUnits","objectBoundingBox"),u.append(p);for(let i=2,s=t.length;i<s;i+=8){const s=t[i],a=t[i+1],r=t[i+2],d=t[i+3],u=c.createElement("rect"),g=(r-e)/l,m=(n-a)/h,f=(s-r)/l,b=(a-d)/h;u.setAttribute("x",g),u.setAttribute("y",m),u.setAttribute("width",f),u.setAttribute("height",b),p.append(u),o?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#sr&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(d),this.container.style.clipPath=`url(#${g})`}_createPopup(t=null){const{data:e}=this;let i,s;t?(i={str:t.text},s=t.date):(i=e.contentsObj,s=e.modificationDate),this.#nr=new un({data:{color:e.color,titleObj:e.titleObj,modificationDate:s,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#nr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#nr}render(){V("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:a}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${n}"]`);!r||Qs.has(r)?i.push({id:n,exportValue:s,domElement:r}):W(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(Qs.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}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")}_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,mustEnterInEditMode:!0})})}updateOC(t){if(!this.data.oc||!t)return;t.isVisible(this.data.oc)?this.show():this.hide()}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class en extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}class sn extends tn{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,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),s=!0):t.attachment?(this.#rr(i,t.attachment,t.overlaidText,t.attachmentDest),s=!0):t.setOCGState?(this.#or(i,t.setOCGState,t.overlaidText),s=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&(this.contentElement=i,this.container.append(i)),this.container}#lr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#lr(),i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),i&&(t.title=i),this.#lr()}#rr(t,e,i="",s=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#lr()}#or(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),i&&(t.title=i),this.#lr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#lr()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#lr(),!this._fieldObjects)return W('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,a=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&a.push(i)}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 i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Qs.has(i)?i.dispatchEvent(new Event("resetform")):W(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class nn extends tn{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.hasOwnCommentButton=!0,this._createPopup()),this.container.append(t),this.container}}class an extends tn{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return rt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})})}_setEventListeners(t,e,i,s){for(const[n,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,n,a,s),"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":ot.makeHexColor(...e)}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=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/(n*s))||1);r=Math.min(s,o(e/n))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,o(t/n))}a.fontSize=`calc(${r}px * var(--total-scale-factor))`,a.color=ot.makeHexColor(...i),null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class rn extends an{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),n.setValue(a.id,{[s]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=s.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?(i=document.createElement("textarea"),i.textContent=r??n,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",r??n),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),Qs.add(i),this.contentElement=i,i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:c}=this.data,d=!!h&&this.enableScripting;l&&(i.title=l),this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let u=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(d&&(e.type=h,c&&(e.step=c)),o.userValue){const t=o.userValue;if(d)if("time"===h){const i=new Date(t),s=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=s.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Js).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"",d||t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s);const n={formattedValue:s};d&&(n.value=s),t.setValue(e,n)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s)return void n.removeAttribute("maxLength");n.setAttribute("maxLength",s);let a=o.userValue;!a||a.length<=s||(a=a.slice(0,s),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(s,i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});const s=u;u=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:n}=i;if(d){if(n&&"time"===h){const t=n.split(":").map(t=>parseInt(t,10));n=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),i.step=""}else n.includes("T")||(n=`${n}T00:00`),n=new Date(n).valueOf();i.type="text"}o.userValue=n,o.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:a,selectionEnd:r}=s;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*\W*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(a).match(/^\W*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(u&&i.addEventListener("blur",u),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class on extends an{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class ln extends an{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Qs.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=0,n.addEventListener("change",s=>{const{name:n,checked:a}=s.target;for(const s of this._getElementsByName(n,i)){const i=a&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:a})}),n.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",e=>{const s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,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 hn extends an{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");if(Qs.add(n),n.setAttribute("data-element-id",i),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,s&&n.setAttribute("checked",!0),n.tabIndex=0,n.addEventListener("change",e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}),n.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.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 cn extends sn{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 dn extends an{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");Qs.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=0;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e});const a=(t,e)=>{const i=e.replaceAll(" "," ");t.textContent=i,i!==e&&t.setAttribute("display-value",e)};for(const t of this.data.options){const e=document.createElement("option");a(e,t.displayValue),e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),n=!1),s.append(e)}let r=null;if(n){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),r=()=>{t.remove(),s.removeEventListener("input",r),r=null},s.addEventListener("input",r)}const o=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let l=o(!1);const h=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.getAttribute("display-value")||t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",i=>{const n={value(i){r?.();const n=i.detail.value,a=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=a.has(t.value);t.setValue(e,{value:o(!0)}),l=o(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,a=i.detail.remove;if(n[a].selected=!1,s.remove(a),n.length>0){-1===Array.prototype.findIndex.call(n,t=>t.selected)&&(n[0].selected=!0)}t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),l=o(!1)},insert(i){const{index:n,displayValue:r,exportValue:c}=i.detail.insert,d=s.children[n],u=document.createElement("option");a(u,r),u.value=c,d?d.before(u):s.append(u),t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");a(n,e),n.value=i,s.append(n)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:o(!0)}),l=o(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}),s.addEventListener("input",i=>{const s=o(!0),n=o(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(s,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)):s.addEventListener("input",function(i){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class un extends tn{constructor(t){const{data:e,elements:i,parent:s}=t,n=!!s._commentManager;if(super(t,{isRenderable:!n&&tn._hasPopupData(e)}),this.elements=i,n&&tn._hasPopupData(e)){const t=this.popup=this.#hr();for(const e of i)e.popup=t}else this.popup=null}#hr(){return new pn({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,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,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#hr(),i=[];for(const t of this.elements)t.popup=e,t.container.ariaHasPopup="dialog",i.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(t=>`${m}${t}`).join(",")),this.container}}class pn{#W=null;#cr=this.#Ya.bind(this);#dr=this.#ur.bind(this);#pr=this.#gr.bind(this);#mr=this.#fr.bind(this);#br=null;#_t=null;#yr=null;#vr=null;#Ar=null;#wr=null;#xr=null;#Cr=!1;#Sr=null;#Tr=null;#F=null;#Er=null;#_r=null;#Ae=null;#kr=null;#fe=null;#Mr=null;#ir=null;#Dr=!1;#Pr=null;#Ir=null;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:c,commentManager:d=null}){this.#_t=t,this.#Mr=s,this.#yr=a,this.#fe=r,this.#wr=o,this.#br=e,this.#kr=l,this.#xr=h,this.#Ar=i,this.#W=d,this.#Pr=i[0],this.#vr=Dt.toDateObject(n),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),d||(this.#Fr(),this.#_t.hidden=!0,c&&this.#fr())}#Fr(){if(this.#Tr)return;this.#Tr=new AbortController;const{signal:t}=this.#Tr;for(const e of this.trigger)e.addEventListener("click",this.#mr,{signal:t}),e.addEventListener("pointerenter",this.#pr,{signal:t}),e.addEventListener("pointerleave",this.#dr,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#Ar)e.container?.addEventListener("keydown",this.#cr,{signal:t})}#Br(){const t=this.#Ar.find(t=>t.hasCommentButton);t&&(this.#_r=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Er)return void(this.#Er.parentNode||this.#Pr.container.after(this.#Er));if(this.#_r||this.#Br(),!this.#_r)return;const{signal:t}=this.#Tr=new AbortController,e=this.#Pr.hasOwnCommentButton,i=()=>{this.#W.toggleCommentPopup(this,!0,void 0,!e)},s=()=>{this.#W.toggleCommentPopup(this,!1,!0,!e)},n=()=>{this.#W.toggleCommentPopup(this,!1,!1)};if(e){this.#Er=this.#Pr.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#cr,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",s,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#Er=document.createElement("button");e.className="annotationCommentButton";const a=this.#Pr.container;e.style.zIndex=parseInt(a.style.zIndex,10)+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Lr(),this.#Rr(),e.addEventListener("keydown",this.#cr,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",s,{signal:t}),e.addEventListener("pointerleave",n,{signal:t}),a.after(e)}}#Rr(){if(this.#Pr.extraPopupElement&&!this.#Pr.editor)return;this.#Er||this.renderCommentButton();const[t,e]=this.#_r,{style:i}=this.#Er;i.left=`calc(${t}%)`,i.top=`calc(${e}% - var(--comment-button-dim))`}#Lr(){this.#Pr.extraPopupElement||(this.#Er||this.renderCommentButton(),this.#Er.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#Pr.commentData;return t?this.#wr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Er?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}=this.#Pr.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}}get elementBeforePopup(){return this.#Er}get comment(){return this.#Ir||=this.#Pr.commentText,this.#Ir}set comment(t){t!==this.comment&&(this.#Pr.commentText=this.#Ir=t)}focus(){this.#Pr.container?.focus()}get parentBoundingClientRect(){return this.#Pr.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#Er&&(this.#Er.classList.toggle("selected",t),this.#Er.ariaExpanded=e)}setSelectedCommentButton(t){this.#Er.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#Ae)return this.#Ae;const{x:t,y:e,height:i}=this.#Er.getBoundingClientRect(),{x:s,y:n,width:a,height:r}=this.#Pr.layer.getBoundingClientRect();return[(t-s)/a,(e+i-n)/r]}set commentPopupPosition(t){this.#Ae=t}hasDefaultPopupPosition(){return null===this.#Ae}get commentButtonPosition(){return this.#_r}get commentButtonWidth(){return this.#Er.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#Ae||this.commentButtonPosition.map(t=>t/100),s=this.parentBoundingClientRect,{x:n,y:a,width:r,height:o}=s;this.#W.showDialog(null,this,n+e*r,a+i*o,{...t,parentDimensions:s})}render(){if(this.#Sr)return;const t=this.#Sr=document.createElement("div");if(t.className="popup",this.#br){const e=t.style.outlineColor=ot.makeHexColor(...this.#br);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#Mr?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#Mr)}if(t.append(e),this.#vr){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#vr.valueOf()})),t.dateTime=this.#vr.toISOString(),e.append(t)}Kt({html:this.#Or||this.#yr.str,dir:this.#yr?.dir,className:"popupContent"},t),this.#_t.append(t)}get#Or(){const t=this.#fe,e=this.#yr;return!t?.str||e?.str&&e.str!==t.str?null:this.#fe.html||null}get#Nr(){return this.#Or?.attributes?.style?.fontSize||0}get#Hr(){return this.#Or?.attributes?.style?.color||null}#Ur(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#Hr,fontSize:this.#Nr?`calc(${this.#Nr}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}#Ya(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#Cr)&&this.#fr()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#W)return i?(this.remove(),this.#Ir=null):e&&(e.deleted?this.remove():(this.#Lr(),this.#Ir=e.text)),void(t&&(this.#_r=null,this.#Br(),this.#Rr()));i||e?.deleted?this.remove():(this.#Fr(),this.#ir||={contentsObj:this.#yr,richText:this.#fe},t&&(this.#F=null),e&&e.text&&(this.#fe=this.#Ur(e.text),this.#vr=Dt.toDateObject(e.date),this.#yr=null),this.#Sr?.remove(),this.#Sr=null)}resetEdited(){this.#ir&&(({contentsObj:this.#yr,richText:this.#fe}=this.#ir),this.#ir=null,this.#Sr?.remove(),this.#Sr=null,this.#F=null)}remove(){if(this.#Tr?.abort(),this.#Tr=null,this.#Sr?.remove(),this.#Sr=null,this.#Dr=!1,this.#Cr=!1,this.#Er?.remove(),this.#Er=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#zr(){if(null!==this.#F)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:n}}}=this.#wr;let a=!!this.#xr,r=a?this.#xr:this.#kr;for(const t of this.#Ar)if(!r||null!==ot.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=ot.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),l=a?r[2]-r[0]+5:0,h=o[0]+l,c=o[1];this.#F=[100*(h-s)/e,100*(c-n)/i];const{style:d}=this.#_t;d.left=`${this.#F[0]}%`,d.top=`${this.#F[1]}%`}#fr(){this.#W?this.#W.toggleCommentPopup(this,!1):(this.#Cr=!this.#Cr,this.#Cr?(this.#gr(),this.#_t.addEventListener("click",this.#mr),this.#_t.addEventListener("keydown",this.#cr)):(this.#ur(),this.#_t.removeEventListener("click",this.#mr),this.#_t.removeEventListener("keydown",this.#cr)))}#gr(){this.#Sr||this.render(),this.isVisible?this.#Cr&&this.#_t.classList.add("focused"):(this.#zr(),this.#_t.hidden=!1,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)+1e3)}#ur(){this.#_t.classList.remove("focused"),!this.#Cr&&this.isVisible&&(this.#_t.hidden=!0,this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)-1e3)}forceHide(){this.#Dr=this.isVisible,this.#Dr&&(this.#_t.hidden=!0)}maybeShow(){this.#W||(this.#Fr(),this.#Dr&&(this.#Sr||this.#gr(),this.#Dr=!1,this.#_t.hidden=!1))}get isVisible(){return!this.#W&&!1===this.#_t.hidden}}class gn extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=b.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class mn extends tn{#Gr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=this.#Gr=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"),s.append(n),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#Gr}addHighlightArea(){this.container.classList.add("highlightArea")}}class fn extends tn{#$r=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#$r=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",n/2),a.setAttribute("y",n/2),a.setAttribute("width",e-n),a.setAttribute("height",i-n),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#$r}addHighlightArea(){this.container.classList.add("highlightArea")}}class bn extends tn{#jr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),n=t.borderStyle.width,a=this.#jr=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",i/2),a.setAttribute("rx",e/2-n/2),a.setAttribute("ry",i/2-n/2),a.setAttribute("stroke-width",n||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),s.append(a),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#jr}addHighlightArea(){this.container.classList.add("highlightArea")}}class yn extends tn{#Wr=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:i,popupRef:s},width:n,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(n,a,!0);let o=[];for(let i=0,s=e.length;i<s;i+=2){const s=e[i]-t[0],n=t[3]-e[i+1];o.push(`${s},${n}`)}o=o.join(" ");const l=this.#Wr=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),r.append(l),this.container.append(r),!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#Wr}addHighlightArea(){this.container.classList.add("highlightArea")}}class vn extends yn{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class An extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}class wn extends tn{#Vr=null;#Kr=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?b.HIGHLIGHT:b.INK}#Xr(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:s,popupRef:n}}=this,{transform:a,width:r,height:o}=this.#Xr(e,t),l=this.svgFactory.create(r,o,!0),h=this.#Vr=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Kr.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:s}=t,n=this.#Vr;if(e>=0&&n.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#Kr.length;t<e;t++)this.#Kr[t].setAttribute("points",i[t].join(","));if(s){const{transform:t,width:e,height:i}=this.#Xr(this.data.rotation,s);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Kr}addHighlightArea(){this.container.classList.add("highlightArea")}}class xn extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=b.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Cn extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Sn extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class Tn extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),t){const e=document.createElement("s");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class En extends tn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=b.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class _n extends tn{#qr=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 i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#Yr.bind(this)),this.#qr=i;const{isMac:s}=rt.platform;return t.addEventListener("keydown",t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Yr()}),!e.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#qr}addHighlightArea(){this.container.classList.add("highlightArea")}#Yr(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class kn{#Qr=null;#Jr=null;#G=null;#Zr=new Map;#to=null;#eo=null;#Ar=[];#io=!1;zIndex=0;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:a,structTreeLayer:r,commentManager:o,linkService:l,annotationStorage:h}){this.div=t,this.#Qr=e,this.#Jr=i,this.#to=r||null,this.#eo=l||null,this.#G=h||new fe,this.page=n,this.viewport=a,this._annotationEditorUIManager=s,this._commentManager=o||null}hasEditableAnnotations(){return this.#Zr.size>0}async render(t){const{annotations:e,optionalContentConfig:i}=t,s=this.div;Lt(s,this.viewport);const n=new Map,a=[],r={data:null,layer:s,linkService:this.#eo,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new Ys,annotationStorage:this.#G,enableComment:!0===t.enableComment,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===_.POPUP;if(e){const e=n.get(t.id);if(!e)continue;if(!this._commentManager){a.push(t);continue}r.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;r.data=t;const s=Zs.create(r);if(!s.isRenderable)continue;e||(this.#Ar.push(s),t.popupRef&&n.getOrInsertComputed(t.popupRef,ut).push(s));const o=s.render();t.hidden&&(o.style.visibility="hidden"),s.updateOC(i),s._isEditable&&(this.#Zr.set(s.data.id,s),this._annotationEditorUIManager?.renderAnnotationElement(s))}await this.#so();for(const t of a){const e=r.elements=n.get(t.id);r.data=t;const i=Zs.create(r);if(!i.isRenderable)continue;const s=i.render();i.contentElement.id=`${m}${t.id}`,t.hidden&&(s.style.visibility="hidden"),e.at(-1).container.after(s)}this.#no()}async#so(){if(0===this.#Ar.length)return;this.div.replaceChildren();const t=[];if(!this.#io){this.#io=!0;for(const{contentElement:e,data:{id:i}}of this.#Ar){const s=e.id=`${m}${i}`;t.push(this.#to?.getAriaAttributes(s).then(t=>{if(t)for(const[i,s]of t)e.setAttribute(i,s)}))}}this.#Ar.sort(({data:{rect:[t,e,i,s]}},{data:{rect:[n,a,r,o]}})=>{if(t===i&&e===s)return 1;if(n===r&&a===o)return-1;const l=(e+s)/2,h=(a+o)/2;if(l>=o&&h<=e)return-1;if(h>=s&&l<=a)return 1;return(t+i)/2-(n+r)/2});const e=document.createDocumentFragment();for(const t of this.#Ar)e.append(t.container),this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render());if(this.div.append(e),await Promise.all(t),this.#Qr)for(const t of this.#Ar)this.#Qr.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#eo,svgFactory:new Ys,parent:this};for(const i of t){i.borderStyle||=kn._defaultBorderStyle,e.data=i;const t=Zs.create(e);t.isRenderable&&(t.render(),t.contentElement.id=`${m}${i.id}`,this.#Ar.push(t))}await this.#so()}update({viewport:t,optionalContentConfig:e}){const i=this.div;this.viewport=t,Lt(i,{rotation:t.rotation});for(const t of this.#Ar)t.updateOC(e);this.#no(),i.hidden=!1}#no(){if(!this.#Jr)return;const t=this.div;for(const[e,i]of this.#Jr){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i);const a=this.#Zr.get(e);a&&(a._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i),a._hasNoCanvas=!1):a.canvas=i)}this.#Jr.clear()}getEditableAnnotations(){return this.#Zr.values()}getEditableAnnotation(t){return this.#Zr.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:s}=t,n=new en({data:{id:i,rect:t.getPDFRect(),rotation:s},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#eo,annotationStorage:this.#G});return n.render(),n.contentElement.id=`${m}${i}`,n.createOrUpdatePopup(),this.#Ar.push(n),n}removeAnnotation(t){const e=this.#Ar.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#Ar.splice(e,1);this.#Qr?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#so()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return Q(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:k,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Mn=/\r\n?|\n/g;class Dn extends he{#ao="";#ro=`${this.id}-editor`;#oo=null;#Nr;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Dn.prototype,e=t=>t.isEmpty(),i=ae.TRANSLATE_SMALL,s=ae.TRANSLATE_BIG;return Q(this,"_keyboardManager",new se([[["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:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=b.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||Dn._defaultColor||he._defaultLineColor,this.#Nr=t.fontSize||Dn._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(he._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,e){he.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case y.FREETEXT_SIZE:Dn._defaultFontSize=e;break;case y.FREETEXT_COLOR:Dn._defaultColor=e}}updateParams(t,e){switch(t){case y.FREETEXT_SIZE:this.#lo(e);break;case y.FREETEXT_COLOR:this.#Lr(e)}}static get defaultPropertiesToUpdate(){return[[y.FREETEXT_SIZE,Dn._defaultFontSize],[y.FREETEXT_COLOR,Dn._defaultColor||he._defaultLineColor]]}get propertiesToUpdate(){return[[y.FREETEXT_SIZE,this.#Nr],[y.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new Ws(this),[["colorPicker",this._colorPicker]]}get colorType(){return y.FREETEXT_COLOR}#lo(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#Nr)*this.parentScale),this.#Nr=t,this.#ho()},i=this.#Nr;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Lr(t){const e=t=>{this.color=t,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Dn._internalPadding*t,-(Dn._internalPadding+this.#Nr)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#oo=new AbortController;const t=this._uiManager.combinedSignal(this.#oo);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#ro),this._isDraggable=!0,this.#oo?.abort(),this.#oo=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&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()}#co(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(Dn.#do(i)),e=i);return t.join("\n")}#ho(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=s,e.classList.toggle("hidden",n)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#ao,e=this.#ao=this.#co().trimEnd();if(t===e)return;const i=t=>{this.#ao=t,t?(this.#uo(),this._uiManager.rebuild(this),this.#ho()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#ho()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Dn._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)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#ro),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#Nr}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-h)/o,u=e+this.height-(n[1]-c)/l;break;case 90:d=t+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[r,-a];break;case 180:d=t-this.width+(n[0]-h)/o,u=e-(n[1]-c)/l,[a,r]=[-a,-r];break;case 270:d=t+(n[0]-h-this.height*l)/o,u=e+(n[1]-c-this.width*o)/l,[a,r]=[-r,a]}this.setAt(d*i,u*s,a,r)}else this._moveAfterPaste(t,e);this.#uo(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#do(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Mn,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=Dn.#po(e.getData("text")||"").replaceAll(Mn,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const a=n.getRangeAt(0);if(!s.includes("\n"))return a.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),void n.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(Mn,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(Dn.#do(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(Mn,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(Dn.#do(i))}this.#ao=`${l.join("\n")}${s}${h.join("\n")}`,this.#uo();const c=new Range;let d=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d),c.setEnd(t,d);break}d-=e}n.removeAllRanges(),n.addRange(c)}#uo(){if(this.editorDiv.replaceChildren(),this.#ao)for(const t of this.#ao.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#go(){return this.#ao.replaceAll(" "," ")}static#po(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=Dn._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let s=null;if(t instanceof gn){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:a,id:r,popupRef:o,richText:l,contentsObj:h,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;s=t={annotationType:b.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:n.slice(0),rotation:a,annotationElementId:r,id:r,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:c,modificationDate:d}}const n=await super.deserialize(t,e,i);return n.#Nr=t.fontSize,n.color=ot.makeHexColor(...t.color),n.#ao=Dn.#po(t.value),n._initialData=s,t.comment&&n.setCommentData(t),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=he._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#Nr,value:this.#go()});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!this.#mo(i)?null:(i.id=this.annotationElementId,i)}#mo(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==s[e])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#Nr}px * var(--total-scale-factor))`,i.color=this.color,e.replaceChildren();for(const t of this.#ao.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#ao}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Pn{static PRECISION=1e-4;toSVGPath(){V("Abstract method `toSVGPath` must be implemented.")}get box(){V("Abstract getter `box` must be implemented.")}serialize(t,e){V("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*s,a[r+1]=i+t[r+1]*n;return a}static _rescaleAndSwap(t,e,i,s,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*s,a[r+1]=i+t[r]*n;return a}static _translate(t,e,i,s){s||=new Float32Array(t.length);for(let n=0,a=t.length;n<a;n+=2)s[n]=e+t[n],s[n+1]=i+t[n+1];return s}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,s,n){switch(n){case 90:return[1-e/i,t/s];case 180:return[1-t/i,1-e/s];case 270:return[e/i,1-t/s];default:return[t/i,e/s]}}static createBezierPoints(t,e,i,s,n,a){return[(t+5*i)/6,(e+5*s)/6,(5*i+n)/6,(5*s+a)/6,(i+n)/2,(s+a)/2]}}class In{#fo;#bo=[];#yo;#vo;#Ao=[];#wo=new Float32Array(18);#xo;#Co;#So;#To;#Eo;#_o;#ko=[];static#Mo=8;static#Do=2;static#Po=In.#Mo+In.#Do;constructor({x:t,y:e},i,s,n,a,r=0){this.#fo=i,this.#_o=n*s,this.#vo=a,this.#wo.set([NaN,NaN,NaN,NaN,t,e],6),this.#yo=r,this.#To=In.#Mo*s,this.#So=In.#Po*s,this.#Eo=s,this.#ko.push(t,e)}isEmpty(){return isNaN(this.#wo[8])}#Io(){const t=this.#wo.subarray(4,6),e=this.#wo.subarray(16,18),[i,s,n,a]=this.#fo;return[(this.#xo+(t[0]-e[0])/2-i)/n,(this.#Co+(t[1]-e[1])/2-s)/a,(this.#xo+(e[0]-t[0])/2-i)/n,(this.#Co+(e[1]-t[1])/2-s)/a]}add({x:t,y:e}){this.#xo=t,this.#Co=e;const[i,s,n,a]=this.#fo;let[r,o,l,h]=this.#wo.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#So)return!1;const p=u-this.#To,g=p/u,m=g*c,f=g*d;let b=r,y=o;r=l,o=h,l+=m,h+=f,this.#ko?.push(t,e);const v=m/p,A=-f/p*this.#_o,w=v*this.#_o;if(this.#wo.set(this.#wo.subarray(2,8),0),this.#wo.set([l+A,h+w],4),this.#wo.set(this.#wo.subarray(14,18),12),this.#wo.set([l-A,h-w],16),isNaN(this.#wo[6]))return 0===this.#Ao.length&&(this.#wo.set([r+A,o+w],2),this.#Ao.push(NaN,NaN,NaN,NaN,(r+A-i)/n,(o+w-s)/a),this.#wo.set([r-A,o-w],14),this.#bo.push(NaN,NaN,NaN,NaN,(r-A-i)/n,(o-w-s)/a)),this.#wo.set([b,y,r,o,l,h],6),!this.isEmpty();this.#wo.set([b,y,r,o,l,h],6);return Math.abs(Math.atan2(y-o,b-r)-Math.atan2(f,m))<Math.PI/2?([r,o,l,h]=this.#wo.subarray(2,6),this.#Ao.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/n,((o+h)/2-s)/a),[r,o,b,y]=this.#wo.subarray(14,18),this.#bo.push(NaN,NaN,NaN,NaN,((b+r)/2-i)/n,((y+o)/2-s)/a),!0):([b,y,r,o,l,h]=this.#wo.subarray(0,6),this.#Ao.push(((b+5*r)/6-i)/n,((y+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),[l,h,r,o,b,y]=this.#wo.subarray(12,18),this.#bo.push(((b+5*r)/6-i)/n,((y+5*o)/6-s)/a,((5*r+l)/6-i)/n,((5*o+h)/6-s)/a,((r+l)/2-i)/n,((o+h)/2-s)/a),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#Ao,e=this.#bo;if(isNaN(this.#wo[6])&&!this.isEmpty())return this.#Fo();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#Bo(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#Lo(i),i.join(" ")}#Fo(){const[t,e,i,s]=this.#fo,[n,a,r,o]=this.#Io();return`M${(this.#wo[2]-t)/i} ${(this.#wo[3]-e)/s} L${(this.#wo[4]-t)/i} ${(this.#wo[5]-e)/s} L${n} ${a} L${r} ${o} L${(this.#wo[16]-t)/i} ${(this.#wo[17]-e)/s} L${(this.#wo[14]-t)/i} ${(this.#wo[15]-e)/s} Z`}#Lo(t){const e=this.#bo;t.push(`L${e[4]} ${e[5]} Z`)}#Bo(t){const[e,i,s,n]=this.#fo,a=this.#wo.subarray(4,6),r=this.#wo.subarray(16,18),[o,l,h,c]=this.#Io();t.push(`L${(a[0]-e)/s} ${(a[1]-i)/n} L${o} ${l} L${h} ${c} L${(r[0]-e)/s} ${(r[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,a){return new Fn(t,e,i,s,n,a)}getOutlines(){const t=this.#Ao,e=this.#bo,i=this.#wo,[s,n,a,r]=this.#fo,o=new Float32Array((this.#ko?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#ko[t]-s)/a,o[t+1]=(this.#ko[t+1]-n)/r;if(o[o.length-2]=(this.#xo-s)/a,o[o.length-1]=(this.#Co-n)/r,isNaN(i[6])&&!this.isEmpty())return this.#Ro(o);const l=new Float32Array(this.#Ao.length+24+this.#bo.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#Oo(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#No(l,h),this.newFreeDrawOutline(l,o,this.#fo,this.#Eo,this.#yo,this.#vo)}#Ro(t){const e=this.#wo,[i,s,n,a]=this.#fo,[r,o,l,h]=this.#Io(),c=new Float32Array(36);return c.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/a,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/a,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/a],0),this.newFreeDrawOutline(c,t,this.#fo,this.#Eo,this.#yo,this.#vo)}#No(t,e){const i=this.#bo;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#Oo(t,e){const i=this.#wo.subarray(4,6),s=this.#wo.subarray(16,18),[n,a,r,o]=this.#fo,[l,h,c,d]=this.#Io();return t.set([NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o],e),e+24}}class Fn extends Pn{#fo;#Ho=new Float32Array(4);#yo;#vo;#ko;#Eo;#Uo;constructor(t,e,i,s,n,a){super(),this.#Uo=t,this.#ko=e,this.#fo=i,this.#Eo=s,this.#yo=n,this.#vo=a,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#zo(a);const[r,o,l,h]=this.#Ho;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-r)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-r)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#Uo[4]} ${this.#Uo[5]}`];for(let e=6,i=this.#Uo.length;e<i;e+=6)isNaN(this.#Uo[e])?t.push(`L${this.#Uo[e+4]} ${this.#Uo[e+5]}`):t.push(`C${this.#Uo[e]} ${this.#Uo[e+1]} ${this.#Uo[e+2]} ${this.#Uo[e+3]} ${this.#Uo[e+4]} ${this.#Uo[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,s],n){const a=i-t,r=s-e;let o,l;switch(n){case 0:o=Pn._rescale(this.#Uo,t,s,a,-r),l=Pn._rescale(this.#ko,t,s,a,-r);break;case 90:o=Pn._rescaleAndSwap(this.#Uo,t,e,a,r),l=Pn._rescaleAndSwap(this.#ko,t,e,a,r);break;case 180:o=Pn._rescale(this.#Uo,i,e,-a,r),l=Pn._rescale(this.#ko,i,e,-a,r);break;case 270:o=Pn._rescaleAndSwap(this.#Uo,i,s,-a,-r),l=Pn._rescaleAndSwap(this.#ko,i,s,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#zo(t){const i=this.#Uo;let s=i[4],n=i[5];const a=[s,n,s,n];let r=s,o=n,l=s,h=n;const c=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,u=i.length;t<u;t+=6){const u=i[t+4],p=i[t+5];isNaN(i[t])?(ot.pointBoundingBox(u,p,a),o>p?(r=u,o=p):o===p&&(r=c(r,u)),h<p?(l=u,h=p):h===p&&(l=c(l,u))):(d.set(e,0),ot.bezierBoundingBox(s,n,...i.slice(t,t+6),d),ot.rectBoundingBox(...d,a),o>d[1]?(r=d[0],o=d[1]):o===d[1]&&(r=c(r,d[0])),h<d[3]?(l=d[2],h=d[3]):h===d[3]&&(l=c(l,d[2]))),s=u,n=p}const u=this.#Ho;u[0]=a[0]-this.#yo,u[1]=a[1]-this.#yo,u[2]=a[2]-a[0]+2*this.#yo,u[3]=a[3]-a[1]+2*this.#yo,this.firstPoint=[r,o],this.lastPoint=[l,h]}get box(){return this.#Ho}newOutliner(t,e,i,s,n,a=0){return new In(t,e,i,s,n,a)}getNewOutline(t,e){const[i,s,n,a]=this.#Ho,[r,o,l,h]=this.#fo,c=n*l,d=a*h,u=i*l+r,p=s*h+o,g=this.newOutliner({x:this.#ko[0]*c+u,y:this.#ko[1]*d+p},this.#fo,this.#Eo,t,this.#vo,e??this.#yo);for(let t=2;t<this.#ko.length;t+=2)g.add({x:this.#ko[t]*c+u,y:this.#ko[t+1]*d+p});return g.getOutlines()}}class Bn{#fo;#Go;#$o;#jo=[];#Wo=[];constructor(t,i=0,s=0,n=!0){const a=e.slice(),r=1e-4;for(const{x:e,y:s,width:n,height:o}of t){const t=Math.floor((e-i)/r)*r,l=Math.ceil((e+n+i)/r)*r,h=Math.floor((s-i)/r)*r,c=Math.ceil((s+o+i)/r)*r,d=[t,h,c,!0],u=[l,h,c,!1];this.#jo.push(d,u),ot.rectBoundingBox(t,h,l,c,a)}const o=a[2]-a[0]+2*s,l=a[3]-a[1]+2*s,h=a[0]-s,c=a[1]-s;let d=n?-1/0:1/0,u=1/0;const p=this.#jo.at(n?-1:-2),g=[p[0],p[2]];for(const t of this.#jo){const[e,i,s,a]=t;!a&&n?i<u?(u=i,d=e):i===u&&(d=Math.max(d,e)):a&&!n&&(i<u?(u=i,d=e):i===u&&(d=Math.min(d,e))),t[0]=(e-h)/o,t[1]=(i-c)/l,t[2]=(s-c)/l}this.#fo=new Float32Array([h,c,o,l]),this.#Go=[d,u],this.#$o=g}getOutlines(){this.#jo.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#jo)e[3]?(t.push(...this.#Vo(e)),this.#Ko(e)):(this.#Xo(e),t.push(...this.#Vo(e)));return this.#qo(t)}#qo(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,s=e.length;t<s;t+=2){const s=e[t][2],n=e[t+1][2];s.push(n),n.push(s),i.add(s),i.add(n)}const s=[];let n;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,c=a;for(n=[e,r],s.push(n);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(n.push(h,c,e,c===a?a:r),h=e),c=c===a?r:a}n.push(h,c)}return new Ln(s,this.#fo,this.#Go,this.#$o)}#Yo(t){const e=this.#Wo;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,a=e[n][0];if(a===t)return n;a<t?i=n+1:s=n-1}return s+1}#Ko([,t,e]){const i=this.#Yo(t);this.#Wo.splice(i,0,[t,e])}#Xo([,t,e]){const i=this.#Yo(t);for(let s=i;s<this.#Wo.length;s++){const[i,n]=this.#Wo[s];if(i!==t)break;if(i===t&&n===e)return void this.#Wo.splice(s,1)}for(let s=i-1;s>=0;s--){const[i,n]=this.#Wo[s];if(i!==t)break;if(i===t&&n===e)return void this.#Wo.splice(s,1)}}#Vo(t){const[e,i,s]=t,n=[[e,i,s]],a=this.#Yo(s);for(let t=0;t<a;t++){const[i,s]=this.#Wo[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(s<=r||o<=i))if(r>=i)if(o>s)n[t][1]=s;else{if(1===a)return[];n.splice(t,1),t--,a--}else n[t][2]=i,o>s&&n.push([e,s,o])}}return n}}class Ln extends Pn{#fo;#Qo;constructor(t,e,i,s){super(),this.#Qo=t,this.#fo=e,this.firstPoint=i,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#Qo){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n<e.length;n+=2){const a=e[n],r=e[n+1];a===i?(t.push(`V${r}`),s=r):r===s&&(t.push(`H${a}`),i=a)}t.push("Z")}return t.join(" ")}serialize([t,e,i,s],n){const a=[],r=i-t,o=s-e;for(const e of this.#Qo){const i=new Array(e.length);for(let n=0;n<e.length;n+=2)i[n]=t+e[n]*r,i[n+1]=s-e[n+1]*o;a.push(i)}return a}get box(){return this.#fo}get classNamesForOutlining(){return["highlightOutline"]}}class Rn extends In{newFreeDrawOutline(t,e,i,s,n,a){return new On(t,e,i,s,n,a)}}class On extends Fn{newOutliner(t,e,i,s,n,a=0){return new Rn(t,e,i,s,n,a)}}class Nn extends he{#Jo=null;#Zo=0;#tl;#el=null;#a=null;#il=null;#sl=null;#nl=0;#al=null;#rl=null;#E=null;#ol=!1;#Go=null;#$o=null;#ll=null;#be="";#_o;#hl="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=b.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=Nn.prototype;return Q(this,"_keyboardManager",new se([[["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||Nn._defaultColor,this.#_o=t.thickness||Nn._defaultThickness,this.opacity=t.opacity||Nn._defaultOpacity,this.#tl=t.boxes||null,this.#hl=t.methodOfCreation||"",this.#be=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#ol=!0,this.#cl(t),this.#dl()):this.#tl&&(this.#Jo=t.anchorNode,this.#Zo=t.anchorOffset,this.#sl=t.focusNode,this.#nl=t.focusOffset,this.#ul(),this.#dl(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(he._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#ol?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#_o,methodOfCreation:this.#hl}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ul(){const t=new Bn(this.#tl,.001);this.#rl=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#rl.box;const e=new Bn(this.#tl,.0025,.001,"ltr"===this._uiManager.direction);this.#il=e.getOutlines();const{firstPoint:i}=this.#rl;this.#Go=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:s}=this.#il;this.#$o=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#cl({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#rl=t;if(this.#il=t.getNewOutline(this.#_o/2+1.5,.0025),e>=0)this.#E=e,this.#el=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#ll=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#il.box,path:{d:this.#il.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#E,{bbox:Nn.#pl(this.#rl.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#ll,{bbox:Nn.#pl(this.#il.box,e),path:{d:this.#il.toSVGPath()}})}const[s,n,a,r]=t.box;switch(this.rotation){case 0:this.x=s,this.y=n,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=n,this.y=1-s,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-s,this.y=1-n,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n,this.y=s,this.width=a*e/t,this.height=r*t/e;break}}const{firstPoint:o}=t;this.#Go=[(o[0]-s)/a,(o[1]-n)/r];const{lastPoint:l}=this.#il;this.#$o=[(l[0]-s)/a,(l[1]-n)/r]}static initialize(t,e){he.initialize(t,e),Nn._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case y.HIGHLIGHT_COLOR:Nn._defaultColor=e;break;case y.HIGHLIGHT_THICKNESS:Nn._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#$o}get commentButtonPosition(){return this.#Go}updateParams(t,e){switch(t){case y.HIGHLIGHT_COLOR:this.#Lr(e);break;case y.HIGHLIGHT_THICKNESS:this.#gl(e)}}static get defaultPropertiesToUpdate(){return[[y.HIGHLIGHT_COLOR,Nn._defaultColor],[y.HIGHLIGHT_THICKNESS,Nn._defaultThickness]]}get propertiesToUpdate(){return[[y.HIGHLIGHT_COLOR,this.color||Nn._defaultColor],[y.HIGHLIGHT_THICKNESS,this.#_o||Nn._defaultThickness],[y.HIGHLIGHT_FREE,this.#ol]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#E,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#a?.updateColor(this.color),super.onUpdatedColor()}#Lr(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},i=this.color,s=this.opacity;this.addCommands({cmd:e.bind(this,t,Nn._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#gl(t){const e=this.#_o,i=t=>{this.#_o=t,this.#ml(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#a=new js({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#fl())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#fl())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#bl(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dl(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#bl():t&&(this.#dl(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#ml(t){this.#ol&&(this.#cl({highlightOutlines:this.#rl.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#bl(){null!==this.#E&&this.parent&&(this.parent.drawLayer.remove(this.#E),this.#E=null,this.parent.drawLayer.remove(this.#ll),this.#ll=null)}#dl(t=this.parent){null===this.#E&&(({id:this.#E,clipPathId:this.#el}=t.drawLayer.draw({bbox:this.#rl.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#ol},path:{d:this.#rl.toSVGPath()}},!1,!0)),this.#ll=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#ol},bbox:this.#il.box,path:{d:this.#il.toSVGPath()}},this.#ol),this.#al&&(this.#al.style.clipPath=this.#el))}static#pl([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#ol?(t=(t-this.rotation+360)%360,i=Nn.#pl(this.#rl.box,t)):i=Nn.#pl([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#E,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#ll,{bbox:Nn.#pl(this.#il.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#be&&(t.setAttribute("aria-label",this.#be),t.setAttribute("role","mark")),this.#ol?t.classList.add("free"):this.div.addEventListener("keydown",this.#yl.bind(this),{signal:this._uiManager._signal});const e=this.#al=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#el,this.setDims(),Jt(this,this.#al,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#ll,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#ll,{rootClass:{hovered:!1}})}#yl(t){Nn._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#vl(!0);break;case 1:case 3:this.#vl(!1)}}#vl(t){if(!this.#Jo)return;const e=window.getSelection();t?e.setPosition(this.#Jo,this.#Zo):e.setPosition(this.#sl,this.#nl)}select(){super.select(),this.#ll&&this.parent?.drawLayer.updateProperties(this.#ll,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#ll&&(this.parent?.drawLayer.updateProperties(this.#ll,{rootClass:{selected:!1}}),this.#ol||this.#vl(!1))}get _mustFixPosition(){return!this.#ol}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#E,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#ll,{rootClass:{hidden:!t}}))}#fl(){return this.#ol?this.rotation:0}#Al(){if(this.#ol)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#tl,a=new Float32Array(8*n.length);let r=0;for(const{x:o,y:l,width:h,height:c}of n){const n=o*t+i,d=(1-l)*e+s;a[r]=a[r+4]=n,a[r+1]=a[r+3]=d,a[r+2]=a[r+6]=n+h*t,a[r+5]=a[r+7]=d-c*e,r+=8}return a}#wl(t){return this.#rl.serialize(t,this.#fl())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),d=e=>{h.abort(),this.#xl(t,e)};window.addEventListener("blur",d,{signal:c}),window.addEventListener("pointerup",d,{signal:c}),window.addEventListener("pointerdown",Mt,{capture:!0,passive:!1,signal:c}),window.addEventListener("contextmenu",kt,{signal:c}),i.addEventListener("pointermove",this.#Cl.bind(this,t),{signal:c}),this._freeHighlight=new Rn({x:s,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Cl(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#xl(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(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 async deserialize(t,e,i){let s=null;if(t instanceof xn){const{data:{quadPoints:e,rect:i,rotation:n,id:a,color:r,opacity:o,popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:b.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:n,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof wn){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:b.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:n,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:n,quadPoints:a,inkLists:r,outlines:o,opacity:l}=t,h=await super.deserialize(t,e,i);h.color=ot.makeHexColor(...n),h.opacity=l||1,r&&(h.#_o=t.thickness),h._initialData=s,t.comment&&h.setCommentData(t);const[c,d]=h.pageDimensions,[u,p]=h.pageTranslation;if(a){const t=h.#tl=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-u)/c,y:1-(a[e+1]-p)/d,width:(a[e+2]-a[e])/c,height:(a[e+1]-a[e+5])/d});h.#ul(),h.#dl(),h.rotate(h.rotation)}else if(r||o){h.#ol=!0;const t=(r||o.points)[0],i={x:t[0]-u,y:d-(t[1]-p)},s=new Rn(i,[0,0,c,d],1,h.#_o/2,!0,.001);for(let e=0,n=t.length;e<n;e+=2)i.x=t[e]-u,i.y=d-(t[e+1]-p),s.add(i);const{id:n,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:s.toSVGPath()}},!0,!0);h.#cl({highlightOutlines:s.getOutlines(),highlightId:n,clipPathId:a}),h.#dl(),h.rotate(h.parentRotation)}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=he._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#_o,quadPoints:this.#Al(),outlines:this.#wl(i.rect)}),this.addComment(i),this.annotationElementId&&!this.#mo(i)?null:(i.id=this.annotationElementId,i)}#mo(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class Hn{#Sl=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#Sl[t]=e}toSVGProperties(){const t=this.#Sl;return this.#Sl=Object.create(null),{root:t}}reset(){this.#Sl=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){V("Not implemented")}}class Un extends he{#Tl=null;#El;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#_l=null;static#kl=null;static#Ml=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#El=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#Dl(t),this.#dl())}#Dl({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Tl=t,this._drawingOptions||=i,this.annotationElementId||this._uiManager.a11yAlert(he._l10nAlert[this.editorType]),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#Pl(t,this.parent),this.#Il(t.box)}#Pl(t,e){const{id:i}=e.drawLayer.draw(Un._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){V("Not implemented")}static get typesMap(){V("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(Un.#_l.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],a=i=>{s.updateProperty(e,i);const n=this.#Tl.updateProperty(e,i);n&&this.#Il(n),this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const i=this.constructor.typesMap.get(this.colorType),s=this.constructor.typesMap.get(this.opacityType),n=this._drawingOptions,a=n[i],r=n[s],o=(t,e)=>{n.updateProperty(i,t),n.updateProperty(s,e),this.#Tl.updateProperty(i,t),this.#Tl.updateProperty(s,e),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:o.bind(this,t,e),undo:o.bind(this,a,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,Un._mergeSVGProperties(this.#Tl.getPathResizingSVGProperties(this.#Fl()),{bbox:this.#Bl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,Un._mergeSVGProperties(this.#Tl.getPathResizedSVGProperties(this.#Fl()),{bbox:this.#Bl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Bl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,Un._mergeSVGProperties(this.#Tl.getPathTranslatedSVGProperties(this.#Fl(),this.parentDimensions),{bbox:this.#Bl()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#El&&(this.#El=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#bl(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#dl(),this.#Il(this.#Tl.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#bl()):t&&(this._uiManager.addShouldRescale(this),this.#dl(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#bl(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#dl(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#Pl(this.#Tl,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#Ll([t,e,i,s]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/n),s*(n/a)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(a/n),s*(n/a)];default:return[t,e,i,s]}}#Fl(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(n/a),s*(a/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/a),s*(a/n)];default:return[t,e,i,s]}}#Il(t){[this.x,this.y,this.width,this.height]=this.#Ll(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#Bl(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*n+a)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(r/o),s*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),s*(o/r)];case 6:return[1-t-s*(o/r),1-e,s*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-s*(o/r),i*(r/o),s*(o/r)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/r),e,s*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-s*(o/r),i*(r/o),s*(o/r)];case 14:return[1-t,1-e-i*(r/o),s*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),s*(o/r)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,Un._mergeSVGProperties({bbox:this.#Bl()},this.#Tl.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Il(this.#Tl.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const s=document.createElement("div");return i.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,s,n){V("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=s;if(Zt.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=Un.#kl=new AbortController,p=t.combinedSignal(u);Zt.setPointer(l,o),window.addEventListener("pointerup",t=>{Zt.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p}),window.addEventListener("pointercancel",t=>{Zt.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p}),window.addEventListener("pointerdown",t=>{Zt.isSamePointerType(t.pointerType)&&(Zt.initializeAndAddPointerId(t.pointerId),Un.#_l.isCancellable()&&(Un.#_l.removeLastElement(),Un.#_l.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",kt,{signal:p}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),n.addEventListener("touchmove",t=>{Zt.isSameTimeStamp(t.timeStamp)&&Mt(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),Un.#_l?t.drawLayer.updateProperties(this._currentDrawId,Un.#_l.startNew(a,r,c,d,h)):(e.updateUIForDefaultProperties(this),Un.#_l=this.createDrawerInstance(a,r,c,d,h),Un.#Ml=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(Un.#Ml.toSVGProperties(),Un.#_l.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(Zt.isSameTimeStamp(t.timeStamp),!Un.#_l)return;const{offsetX:e,offsetY:i,pointerId:s}=t;Zt.isSamePointerId(s)&&(Zt.isUsingMultiplePointers()?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,Un.#_l.add(e,i)),Zt.setTimeStamp(t.timeStamp),Mt(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,Un.#_l=null,Un.#Ml=null,Zt.clearTimeStamp()),Un.#kl&&(Un.#kl.abort(),Un.#kl=null,Zt.clearPointerIds())}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,Un.#_l.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=Un.#_l,i=this._currentDrawId,s=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:y.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(y.DRAW_STEP),!Un.#_l.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:Un.#_l.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:Un.#Ml,mustBeCommitted:!t});return this._cleanup(!0),a}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,a){V("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#Dl({drawOutlines:o}),l.#dl(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#Tl.serialize([e,i,s,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class zn{#wo=new Float64Array(6);#Gr;#Rl;#Yn;#_o;#ko;#Ol="";#Nl=0;#Qo=new Gn;#Hl;#Ul;constructor(t,e,i,s,n,a){this.#Hl=i,this.#Ul=s,this.#Yn=n,this.#_o=a,[t,e]=this.#zl(t,e);const r=this.#Gr=[NaN,NaN,NaN,NaN,t,e];this.#ko=[t,e],this.#Rl=[{line:r,points:this.#ko}],this.#wo.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#_o=e)}#zl(t,e){return Pn._normalizePoint(t,e,this.#Hl,this.#Ul,this.#Yn)}isEmpty(){return!this.#Rl||0===this.#Rl.length}isCancellable(){return this.#ko.length<=10}add(t,e){[t,e]=this.#zl(t,e);const[i,s,n,a]=this.#wo.subarray(2,6),r=t-n,o=e-a;return Math.hypot(this.#Hl*r,this.#Ul*o)<=2?null:(this.#ko.push(t,e),isNaN(i)?(this.#wo.set([n,a,t,e],2),this.#Gr.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#wo[0])&&this.#Gr.splice(6,6),this.#wo.set([i,s,n,a,t,e],0),this.#Gr.push(...Pn.createBezierPoints(i,s,n,a,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#ko.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Hl=i,this.#Ul=s,this.#Yn=n,[t,e]=this.#zl(t,e);const a=this.#Gr=[NaN,NaN,NaN,NaN,t,e];this.#ko=[t,e];const r=this.#Rl.at(-1);return r&&(r.line=new Float32Array(r.line),r.points=new Float32Array(r.points)),this.#Rl.push({line:a,points:this.#ko}),this.#wo.set(a,0),this.#Nl=0,this.toSVGPath(),null}getLastElement(){return this.#Rl.at(-1)}setLastElement(t){return this.#Rl?(this.#Rl.push(t),this.#Gr=t.line,this.#ko=t.points,this.#Nl=0,{path:{d:this.toSVGPath()}}):this.#Qo.setLastElement(t)}removeLastElement(){if(!this.#Rl)return this.#Qo.removeLastElement();this.#Rl.pop(),this.#Ol="";for(let t=0,e=this.#Rl.length;t<e;t++){const{line:e,points:i}=this.#Rl[t];this.#Gr=e,this.#ko=i,this.#Nl=0,this.toSVGPath()}return{path:{d:this.#Ol}}}toSVGPath(){const t=Pn.svgRound(this.#Gr[4]),e=Pn.svgRound(this.#Gr[5]);if(2===this.#ko.length)return this.#Ol=`${this.#Ol} M ${t} ${e} Z`,this.#Ol;if(this.#ko.length<=6){const i=this.#Ol.lastIndexOf("M");this.#Ol=`${this.#Ol.slice(0,i)} M ${t} ${e}`,this.#Nl=6}if(4===this.#ko.length){const t=Pn.svgRound(this.#Gr[10]),e=Pn.svgRound(this.#Gr[11]);return this.#Ol=`${this.#Ol} L ${t} ${e}`,this.#Nl=12,this.#Ol}const i=[];0===this.#Nl&&(i.push(`M ${t} ${e}`),this.#Nl=6);for(let t=this.#Nl,e=this.#Gr.length;t<e;t+=6){const[e,s,n,a,r,o]=this.#Gr.slice(t,t+6).map(Pn.svgRound);i.push(`C${e} ${s} ${n} ${a} ${r} ${o}`)}return this.#Ol+=i.join(" "),this.#Nl=this.#Gr.length,this.#Ol}getOutlines(t,e,i,s){const n=this.#Rl.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#Qo.build(this.#Rl,t,e,i,this.#Yn,this.#_o,s),this.#wo=null,this.#Gr=null,this.#Rl=null,this.#Ol=null,this.#Qo}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Gn extends Pn{#Ho;#Gl=0;#yo;#Rl;#Hl;#Ul;#$l;#Yn;#_o;build(t,e,i,s,n,a,r){this.#Hl=e,this.#Ul=i,this.#$l=s,this.#Yn=n,this.#_o=a,this.#yo=r??0,this.#Rl=t,this.#jl()}get thickness(){return this.#_o}setLastElement(t){return this.#Rl.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#Rl.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#Rl)if(t.push(`M${Pn.svgRound(e[4])} ${Pn.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Pn.svgRound(e[10])} ${Pn.svgRound(e[11])}`);else for(let i=6,s=e.length;i<s;i+=6){const[s,n,a,r,o,l]=e.subarray(i,i+6).map(Pn.svgRound);t.push(`C${s} ${n} ${a} ${r} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,s],n){const a=[],r=[],[o,l,h,c]=this.#Wl();let d,u,p,g,m,f,b,y,v;switch(this.#Yn){case 0:v=Pn._rescale,d=t,u=e+s,p=i,g=-s,m=t+o*i,f=e+(1-l-c)*s,b=t+(o+h)*i,y=e+(1-l)*s;break;case 90:v=Pn._rescaleAndSwap,d=t,u=e,p=i,g=s,m=t+l*i,f=e+o*s,b=t+(l+c)*i,y=e+(o+h)*s;break;case 180:v=Pn._rescale,d=t+i,u=e,p=-i,g=s,m=t+(1-o-h)*i,f=e+l*s,b=t+(1-o)*i,y=e+(l+c)*s;break;case 270:v=Pn._rescaleAndSwap,d=t+i,u=e+s,p=-i,g=-s,m=t+(1-l-c)*i,f=e+(1-o-h)*s,b=t+(1-l)*i,y=e+(1-o)*s}for(const{line:t,points:e}of this.#Rl)a.push(v(t,d,u,p,g,n?new Array(t.length):null)),r.push(v(e,d,u,p,g,n?new Array(e.length):null));return{lines:a,points:r,rect:[m,f,b,y]}}static deserialize(t,e,i,s,n,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=Pn._rescale,c=-t/i,d=e/s+1,u=1/i,p=-1/s;break;case 90:g=Pn._rescaleAndSwap,c=-e/s,d=-t/i,u=1/s,p=1/i;break;case 180:g=Pn._rescale,c=t/i+1,d=-e/s,u=-1/i,p=1/s;break;case 270:g=Pn._rescaleAndSwap,c=e/s+1,d=t/i+1,u=-1/s,p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[s,n,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,s,n],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(Pn.createBezierPoints(s,n,r,o,e,l),3*(a-2)),[s,n,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map(t=>t??NaN),c,d,u,p),points:g(r[t].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;return m.build(h,i,s,1,o,l,n),m}#Vl(t=this.#_o){const e=this.#yo+t/2*this.#$l;return this.#Yn%180==0?[e/this.#Hl,e/this.#Ul]:[e/this.#Ul,e/this.#Hl]}#Wl(){const[t,e,i,s]=this.#Ho,[n,a]=this.#Vl(0);return[t+n,e+a,i-2*n,s-2*a]}#jl(){const t=this.#Ho=i.slice();for(const{line:e}of this.#Rl){if(e.length<=12){for(let i=4,s=e.length;i<s;i+=6)ot.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],s=e[5];for(let n=6,a=e.length;n<a;n+=6){const[a,r,o,l,h,c]=e.subarray(n,n+6);ot.bezierBoundingBox(i,s,a,r,o,l,h,c,t),i=h,s=c}}const[e,s]=this.#Vl();t[0]=mt(t[0]-e,0,1),t[1]=mt(t[1]-s,0,1),t[2]=mt(t[2]+e,0,1),t[3]=mt(t[3]+s,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#Ho}updateProperty(t,e){return"stroke-width"===t?this.#gl(e):null}#gl(t){const[e,i]=this.#Vl();this.#_o=t;const[s,n]=this.#Vl(),[a,r]=[s-e,n-i],o=this.#Ho;return o[0]-=a,o[1]-=r,o[2]+=2*a,o[3]+=2*r,o}updateParentDimensions([t,e],i){const[s,n]=this.#Vl();this.#Hl=t,this.#Ul=e,this.#$l=i;const[a,r]=this.#Vl(),o=a-s,l=r-n,h=this.#Ho;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Gl=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Ho.map(Pn.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#Ho;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Pn.svgRound(t)} ${Pn.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#Ho;let i=0,s=0,n=0,a=0,r=0,o=0;switch(this.#Gl){case 90:s=e/t,n=-t/e,r=t;break;case 180:i=-1,a=-1,r=t,o=e;break;case 270:s=-e/t,n=t/e,o=e;break;default:return""}return`matrix(${i} ${s} ${n} ${a} ${Pn.svgRound(r)} ${Pn.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,s]){const[n,a]=this.#Vl(),[r,o,l,h]=this.#Ho;if(Math.abs(l-n)<=Pn.PRECISION||Math.abs(h-a)<=Pn.PRECISION){const n=t+i/2-(r+l/2),a=e+s/2-(o+h/2);return{path:{"transform-origin":`${Pn.svgRound(t)} ${Pn.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${a})`}}}const c=(i-2*n)/(l-2*n),d=(s-2*a)/(h-2*a),u=l/i,p=h/s;return{path:{"transform-origin":`${Pn.svgRound(r)} ${Pn.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Pn.svgRound(n)} ${Pn.svgRound(a)}) scale(${c} ${d}) translate(${Pn.svgRound(-n)} ${Pn.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,s]){const[n,a]=this.#Vl(),r=this.#Ho,[o,l,h,c]=r;if(r[0]=t,r[1]=e,r[2]=i,r[3]=s,Math.abs(h-n)<=Pn.PRECISION||Math.abs(c-a)<=Pn.PRECISION){const n=t+i/2-(o+h/2),a=e+s/2-(l+c/2);for(const{line:t,points:e}of this.#Rl)Pn._translate(t,n,a,t),Pn._translate(e,n,a,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Pn.svgRound(t)} ${Pn.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*n)/(h-2*n),u=(s-2*a)/(c-2*a),p=-d*(o+n)+t+n,g=-u*(l+a)+e+a;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#Rl)Pn._rescale(t,p,g,d,u,t),Pn._rescale(e,p,g,d,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Pn.svgRound(t)} ${Pn.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[s,n]=i,a=this.#Ho,r=t-a[0],o=e-a[1];if(this.#Hl===s&&this.#Ul===n)for(const{line:t,points:e}of this.#Rl)Pn._translate(t,r,o,t),Pn._translate(e,r,o,e);else{const t=this.#Hl/s,e=this.#Ul/n;this.#Hl=s,this.#Ul=n;for(const{line:i,points:s}of this.#Rl)Pn._rescale(i,r,o,t,e,i),Pn._rescale(s,r,o,t,e,s);a[2]*=t,a[3]*=e}return a[0]=t,a[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Pn.svgRound(t)} ${Pn.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#Ho;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Pn.svgRound(t[0])} ${Pn.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class $n extends Hn{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:he._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new $n(this._viewParameters);return t.updateAll(this),t}}class jn extends Un{static _type="ink";static _editorType=b.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){he.initialize(t,e),this._defaultDrawingOptions=new $n(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return Q(this,"typesMap",new Map([[y.INK_THICKNESS,"stroke-width"],[y.INK_COLOR,"stroke"],[y.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,s,n){return new zn(t,e,i,s,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,s,n,a){return Gn.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){let s=null;if(t instanceof wn){const{data:{inkLists:e,rect:i,rotation:n,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;s=t={annotationType:b.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:n,annotationElementId:a,id:a,deleted:!1,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const n=await super.deserialize(t,e,i);return n._initialData=s,t.comment&&n.setCommentData(t),n}get toolbarButtons(){return this._colorPicker||=new Ws(this),[["colorPicker",this._colorPicker]]}get colorType(){return y.INK_COLOR}get colorAndOpacityType(){return y.INK_COLOR_AND_OPACITY}get opacityType(){return y.INK_OPACITY}updateParams(t,e){t!==y.INK_COLOR_AND_OPACITY?super.updateParams(t,e):this._updateColorAndOpacity(e.color,e.opacity)}static updateDefaultParams(t,e){if(t===y.INK_COLOR_AND_OPACITY)return super.updateDefaultParams(y.INK_COLOR,e.color),void super.updateDefaultParams(y.INK_OPACITY,e.opacity);super.updateDefaultParams(t,e)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=jn.getDefaultDrawingOptions({stroke:ot.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:s,"stroke-opacity":n,"stroke-width":a}}=this,r=Object.assign(super.serialize(t),{color:he._colorManager.convert(s),opacity:n,thickness:a,paths:{lines:e,points:i}});return this.addComment(r),t?(r.isCopy=!0,r):this.annotationElementId&&!this.#mo(r)?null:(r.id=this.annotationElementId,r)}#mo(t){const{color:e,thickness:i,opacity:s,pageIndex:n}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class Wn extends Gn{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}class Vn{static#Kl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Xl(t,e,i,s){return s-=e,0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#ql=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Yl(t,e,i,s,n,a,r){const o=this.#Xl(i,s,n,a);for(let n=0;n<8;n++){const a=(-n+o-r+16)%8;if(0!==t[(i+this.#ql[2*a])*e+(s+this.#ql[2*a+1])])return a}return-1}static#Ql(t,e,i,s,n,a,r){const o=this.#Xl(i,s,n,a);for(let n=0;n<8;n++){const a=(n+o+r+16)%8;if(0!==t[(i+this.#ql[2*a])*e+(s+this.#ql[2*a+1])])return a}return-1}static#Jl(t,e,i,s){const n=t.length,a=new Int32Array(n);for(let e=0;e<n;e++)a[e]=t[e]<=s?1:0;for(let t=1;t<i-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*i-1-t]=0;let r,o=1;const l=[];for(let t=1;t<i-1;t++){r=1;for(let i=1;i<e-1;i++){const s=t*e+i,n=a[s];if(0===n)continue;let h=t,c=i;if(1===n&&0===a[s-1])o+=1,c-=1;else{if(!(n>=1&&0===a[s+1])){1!==n&&(r=Math.abs(n));continue}o+=1,c+=1,n>1&&(r=n)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===r){g=t;break}g?g.isHole?p.parent=u?g.parent:r:p.parent=u?r:g.parent:p.parent=u?r:0;const m=this.#Yl(a,e,t,i,h,c,0);if(-1===m){a[s]=-o,1!==a[s]&&(r=Math.abs(a[s]));continue}let f=this.#ql[2*m],b=this.#ql[2*m+1];const y=t+f,v=i+b;h=y,c=v;let A=t,w=i;for(;;){const n=this.#Ql(a,e,A,w,h,c,1);f=this.#ql[2*n],b=this.#ql[2*n+1];const l=A+f,u=w+b;d.push(u,l);const p=A*e+w;if(0===a[p+1]?a[p]=-o:1===a[p]&&(a[p]=o),l===t&&u===i&&A===y&&w===v){1!==a[s]&&(r=Math.abs(a[s]));break}h=A,c=w,A=l,w=u}}}return l}static#Zl(t,e,i,s){if(i-e<=4){for(let n=e;n<i-2;n+=2)s.push(t[n],t[n+1]);return}const n=t[e],a=t[e+1],r=t[i-4]-n,o=t[i-3]-a,l=Math.hypot(r,o),h=r/l,c=o/l,d=h*a-c*n,u=o/r,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),y=p*(1-b+b**2),v=Math.max(Math.atan(Math.abs(f+m)*y),Math.atan(Math.abs(f-m)*y));let A=0,w=e;for(let s=e+2;s<i-2;s+=2){const e=Math.abs(d-h*t[s+1]+c*t[s]);e>A&&(w=s,A=e)}A>(l*v)**2?(this.#Zl(t,e,w+2,s),this.#Zl(t,w,i,s)):s.push(n,a)}static#th(t){const e=[],i=t.length;return this.#Zl(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#eh(t,e,i,s,n,a){const r=new Float32Array(a**2),o=-2*s**2,l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let i=0;i<a;i++)r[t*a+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*n**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let s=0;s<i;s++)for(let n=0;n<e;n++){const o=s*e+n,c=t[o];let d=0,g=0;for(let o=0;o<a;o++){const u=s+o-l;if(!(u<0||u>=i))for(let i=0;i<a;i++){const s=n+i-l;if(s<0||s>=e)continue;const p=t[u*e+s],m=r[o*a+i]*h[Math.abs(p-c)];d+=p*m,g+=m}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#ih(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#sh(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let s=-1/0,n=1/0;for(let e=0,a=i.length;e<a;e++){const a=i[e]=t[e<<2];s=Math.max(s,a),n=Math.min(n,a)}const a=255/(s-n);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-n)*a;return i}static#nh(t){let e,i=-1/0,s=-1/0;const n=t.findIndex(t=>0!==t);let a=n,r=n;for(e=n;e<256;e++){const n=t[e];n>i&&(e-a>s&&(s=e-a,r=e-1),i=n,a=e)}for(e=r-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ah(t){const e=t,{width:i,height:s}=t,{maxDim:n}=this.#Kl;let a=i,r=s;if(i>n||s>n){let o=i,l=s,h=Math.log2(Math.max(i,s)/n);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){a=Math.ceil(o/2),r=Math.ceil(l/2);const i=new OffscreenCanvas(a,r);i.getContext("2d").drawImage(t,0,0,o,l,0,0,a,r),o=a,l=r,t!==e&&t.close(),t=i.transferToImageBitmap()}const d=Math.min(n/a,n/r);a=Math.round(a*d),r=Math.round(r*d)}const o=new OffscreenCanvas(a,r).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,a,r),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,a,r);const l=o.getImageData(0,0,a,r).data;return[this.#sh(l),a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:s},n,a,r,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${s} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),y=1.5,v=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*y),A=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*y);l=new OffscreenCanvas(v,A),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=c,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,v,A),h.fillStyle="black",h.fillText(t,.5*v/2,1.5*A/2);const w=this.#sh(h.getImageData(0,0,v,A).data),x=this.#ih(w),C=this.#nh(x),S=this.#Jl(w,v,A,C);return this.processDrawnLines({lines:{curves:S,width:v,height:A},pageWidth:n,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,s,n){const[a,r,o]=this.#ah(t),[l,h]=this.#eh(a,r,o,Math.hypot(r,o)*this.#Kl.sigmaSFactor,this.#Kl.sigmaR,this.#Kl.kernelSize),c=this.#nh(h),d=this.#Jl(l,r,o,c);return this.processDrawnLines({lines:{curves:d,width:r,height:o},pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:n,mustSmooth:a,areContours:r}){s%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=a?this.#th(t):t;if(!e)continue;m.push(e);const i=e.length,s=new Float32Array(i),n=new Float32Array(3*(2===i?2:i-2));if(d.push({line:n,points:s}),2===i){s[0]=e[0]*p,s[1]=e[1]*g,n.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[r,o,l,h]=e;r*=p,o*=g,l*=p,h*=g,s.set([r,o,l,h],0),n.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<i;t+=2){const i=s[t]=e[t]*p,a=s[t+1]=e[t+1]*g;n.set(Pn.createBezierPoints(r,o,l,h,i,a),3*(t-2)),[r,o,l,h]=[l,h,i,a]}}if(0===d.length)return null;const f=r?new Wn:new Gn;return f.build(d,e,i,1,s,r?0:c,n),{outline:f,newCurves:m,areContours:r,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:s,height:n}){let a,r=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];r=Math.min(r,i),o=Math.max(o,i)}}a=r>=-128&&o<=127?Int8Array:r>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*a.BYTES_PER_ELEMENT,d[u++]=0,d[u++]=s,d[u++]=n,d[u++]=e?0:1,d[u++]=Math.max(0,Math.floor(i??0)),d[u++]=h,d[u++]=a.BYTES_PER_ELEMENT;for(const e of t)d[u++]=e.length-2,d[u++]=e[0],d[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(d);const m=a.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,s=e.length;i<s;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();return(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:i,writable:s}=new DecompressionStream("deflate-raw"),n=s.getWriter();await n.ready,n.write(e).then(async()=>{await n.ready,await n.close()}).catch(()=>{});let a=null,r=0;for await(const t of i)a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),a.set(t,r),r+=t.length;const o=new Uint32Array(a.buffer,0,a.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],c=o[3],d=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(a.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(a.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(a.buffer,f)}r=0;for(let t=0;t<p;t++){const e=o[3*t+8],i=new Float32Array(e+2);m.push(i);for(let e=0;e<2;e++)i[e]=o[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+b[r++]}return{areContours:d,thickness:u,outlines:m,width:h,height:c}}catch(t){return W(`decompressSignature: ${t}`),null}}}class Kn extends Hn{constructor(){super(),super.updateProperties({fill:he._defaultLineColor,"stroke-width":0})}clone(){const t=new Kn;return t.updateAll(this),t}}class Xn extends $n{constructor(t){super(t),super.updateProperties({stroke:he._defaultLineColor,"stroke-width":1})}clone(){const t=new Xn(this._viewParameters);return t.updateAll(this),t}}class qn extends Un{#rh=!1;#oh=null;#lh=null;#hh=null;static _type="signature";static _editorType=b.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#lh=t.signatureData||null,this.#oh=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){he.initialize(t,e),this._defaultDrawingOptions=new Kn,this._defaultDrawnSignatureOptions=new Xn(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return Q(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#oh}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#lh){const{lines:t,mustSmooth:e,areContours:i,description:s,uuid:n,heightInPage:a}=this.#lh,{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport,h=Vn.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:qn._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,a,s,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#oh||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#hh=t,this.addEditToolbar()}getUuid(){return this.#hh}get description(){return this.#oh}set description(t){this.#oh=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:s,height:n}=this.#lh,a=Math.max(s,n);return{areContours:e,outline:Vn.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:s,height:n},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,s){const{x:n,y:a}=this,{outline:r}=this.#lh=t;let o;this.#rh=r instanceof Wn,this.description=i,this.#rh?o=qn.getDefaultDrawingOptions():(o=qn._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":r.thickness})),this._addOutlines({drawOutlines:r,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h,this.width*=h/this.height,this.width>=1&&(h*=.9/this.width,this.width=.9),this.height=h,this.setDims(),this.x=n,this.y=a,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(s),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!s,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return Vn.process(t,e,i,s,qn._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:s},rotation:n}=this.parent.viewport;return Vn.extractContoursFromText(t,e,i,s,n,qn._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return Vn.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:qn._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=qn.getDefaultDrawingOptions():(this._drawingOptions=qn._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":s}}=this,n=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#rh,color:[0,0,0],thickness:this.#rh?0:s});return this.addComment(n),t?(n.paths={lines:e,points:i},n.uuid=this.#hh,n.isCopy=!0):n.lines=e,this.#oh&&(n.accessibilityData={type:"Figure",alt:this.#oh}),n}static deserializeDraw(t,e,i,s,n,a){return a.areContours?Wn.deserialize(t,e,i,s,n,a):Gn.deserialize(t,e,i,s,n,a)}static async deserialize(t,e,i){const s=await super.deserialize(t,e,i);return s.#rh=t.areContours,s.description=t.accessibilityData?.alt||"",s.#hh=t.uuid,s}}class Yn extends he{#ch=null;#dh=null;#uh=null;#ph=null;#gh=null;#mh="";#fh=null;#bh=!1;#yh=null;#vh=!1;#Ah=!1;static _type="stamp";static _editorType=b.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#ph=t.bitmapUrl,this.#gh=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){he.initialize(t,e)}static isHandlingMimeForPasting(t){return Ot.includes(t)}static paste(t,e){e.pasteEditor({mode:b.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#wh(t,e=!1){t?(this.#ch=t.bitmap,e||(this.#dh=t.id,this.#vh=t.isSvg),t.file&&(this.#mh=t.file.name),this.#xh()):this.remove()}#Ch(){if(this.#uh=null,this._uiManager.enableWaiting(!1),this.#fh)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#ch)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#ch){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:s,width:n,height:a,channels:s.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#Sh(){if(this.#dh)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#dh).then(t=>this.#wh(t,!0)).finally(()=>this.#Ch());if(this.#ph){const t=this.#ph;return this.#ph=null,this._uiManager.enableWaiting(!0),void(this.#uh=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#wh(t)).finally(()=>this.#Ch()))}if(this.#gh){const t=this.#gh;return this.#gh=null,this._uiManager.enableWaiting(!0),void(this.#uh=this._uiManager.imageManager.getFromFile(t).then(t=>this.#wh(t)).finally(()=>this.#Ch()))}const t=document.createElement("input");t.type="file",t.accept=Ot.join(",");const e=this._uiManager._signal;this.#uh=new Promise(i=>{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._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#wh(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#Ch()),t.click()}remove(){this.#dh&&(this.#ch=null,this._uiManager.imageManager.deleteId(this.#dh),this.#fh?.remove(),this.#fh=null,this.#yh&&(clearTimeout(this.#yh),this.#yh=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#dh&&null===this.#fh&&this.#Sh(),this.isAttachedToDOM||this.parent.add(this))):this.#dh&&this.#Sh()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#uh||this.#ch||this.#ph||this.#gh||this.#dh||this.#bh)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#bh||(this.#ch?this.#xh():this.#Sh()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#dh=i,s&&(this.#ch=s),this.#bh=!1,this.#xh())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#yh&&clearTimeout(this.#yh);this.#yh=setTimeout(()=>{this.#yh=null,this.#Th()},200)}#xh(){const{div:t}=this;let{width:e,height:i}=this.#ch;const[s,n]=this.pageDimensions,a=.75;if(this.width)e=this.width*s,i=this.height*n;else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t,i*=t}this._uiManager.enableWaiting(!1);const r=this.#fh=document.createElement("canvas");r.setAttribute("role","img"),this.addContainer(r),this.width=e/s,this.height=i/n,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#Th(),this.#Ah||(this.parent.addUndoableEditor(this),this.#Ah=!0),this._reportTelemetry({action:"inserted_image"}),this.#mh&&this.div.setAttribute("aria-description",this.#mh),this.annotationElementId||this._uiManager.a11yAlert(he._l10nAlert.stamp)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#ch,a=new Rt;let r=this.#ch,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t),l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#vh||(r=this.#Eh(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":Nt.isDarkMode&&(d="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),c.fillStyle=c.createPattern(f,"repeat"),c.fillRect(0,0,t,i),c.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let c=null;if(i){let e,i;if(a.symmetric&&r.width<t&&r.height<t)e=r.width,i=r.height;else if(r=this.#ch,s>t||n>t){const a=Math.min(t/s,t/n);e=Math.floor(s*a),i=Math.floor(n*a),this.#vh||(r=this.#Eh(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Eh(t,e){const{width:i,height:s}=this.#ch;let n=i,a=s,r=this.#ch;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=Math.ceil(n/2)),a>2*e&&(a=Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a),r=o.transferToImageBitmap()}return r}#Th(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new Rt,a=Math.ceil(i*t*n.sx),r=Math.ceil(s*e*n.sy),o=this.#fh;if(!o||o.width===a&&o.height===r)return;o.width=a,o.height=r;const l=this.#vh?this.#ch:this.#Eh(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#_h(t){if(t){if(this.#vh){const t=this._uiManager.imageManager.getSvgUrl(this.#dh);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#ch);return t.getContext("2d").drawImage(this.#ch,0,0),t.toDataURL()}if(this.#vh){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*vt.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*vt.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);return n.getContext("2d").drawImage(this.#ch,0,0,this.#ch.width,this.#ch.height,0,0,i,s),n.transferToImageBitmap()}return structuredClone(this.#ch)}static async deserialize(t,e,i){let s=null,n=!1;if(t instanceof En){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:f}},canvas:y}=t;let v,A;y?(delete t.canvas,({id:v,bitmap:A}=i.imageManager.getFromCanvas(g.id,y)),y.remove()):(n=!0,t._hasNoCanvas=!0);const w=(await e._structTree.getAriaAttributes(`${m}${o}`))?.get("aria-label")||"";s=t={annotationType:b.STAMP,bitmapId:v,bitmap:A,pageIndex:f-1,rect:a.slice(0),rotation:r,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:w},isSvg:!1,structParent:l,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const a=await super.deserialize(t,e,i),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;n?(i.addMissingCanvas(t.id,a),a.#bh=!0):h&&i.imageManager.isValidId(h)?(a.#dh=h,o&&(a.#ch=o)):a.#ph=l,a.#vh=c;const[u,p]=a.pageDimensions;return a.width=(r[2]-r[0])/u,a.height=(r[3]-r[1])/p,d&&(a.altTextData=d),a._initialData=s,t.comment&&a.setCommentData(t),a.#Ah=!!s,a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#dh,isSvg:this.#vh});if(this.addComment(i),t)return i.bitmapUrl=this.#_h(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:s,altText:n}=this.serializeAltText(!1);if(!s&&n&&(i.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const t=this.#mo(i);return t.isSame?null:(t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(null===e)return i;e.stamps||=new Map;const a=this.#vh?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#dh)){if(this.#vh){const t=e.stamps.get(this.#dh);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#_h(!1))}}else e.stamps.set(this.#dh,{area:a,serialized:i}),i.bitmap=this.#_h(!1);return i}#mo(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class Qn{#Qr;#kh=!1;#Mh=null;#Dh=null;#Ph=null;#Ih=new Map;#Fh=!1;#Bh=!1;#Lh=!1;#Rh=null;#Oh=null;#Nh=null;#Hh=null;#Uh=null;#zh=-1;#y;static _initialized=!1;static#Q=new Map([Dn,jn,Yn,Nn,qn].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const c=[...Qn.#Q.values()];if(!Qn._initialized){Qn._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c),this.#y=t,this.pageIndex=e,this.div=i,this.#Qr=n,this.#Mh=a,this.viewport=l,this.#Nh=o,this.drawLayer=r,this._structTree=s,this.#y.addLayer(this)}get isEmpty(){return 0===this.#Ih.size}get isInvisible(){return this.isEmpty&&this.#y.getMode()===b.NONE}updateToolbar(t){this.#y.updateToolbar(t)}updateMode(t=this.#y.getMode()){switch(this.#Gh(),t){case b.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case b.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case b.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;if(e.toggle("nonEditing",!1),t===b.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of Qn.#Q.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Nh?.div}setEditingState(t){this.#y.setEditingState(t)}addCommands(t){this.#y.addCommands(t)}cleanUndoStack(t){this.#y.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Mh?.togglePointerEvents(t)}get#$h(){return 0!==this.#Ih.size?this.#Ih.values():this.#y.getEditors(this.pageIndex)}async enable(){this.#Lh=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#Uh?.abort(),this.#Uh=null;const t=new Set;for(const e of this.#$h)e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#y.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));const e=this.#Mh;if(e)for(const i of e.getEditableAnnotations()){if(i.hide(),this.#y.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#Lh=!1,this.#y._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#Bh=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#Nh&&!this.#Uh){this.#Uh=new AbortController;const t=this.#y.combinedSignal(this.#Uh);this.#Nh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:s}=t;if(s-this.#zh>500)return void(this.#zh=s);this.#zh=-1;const{classList:n}=this.div;n.toggle("getElements",!0);const a=document.elementsFromPoint(e,i);if(n.toggle("getElements",!1),!this.div.contains(a[0]))return;let r;const o=new RegExp(`^${f}[0-9]+$`);for(const t of a)if(o.test(t.id)){r=t.id;break}if(!r)return;const l=this.#Ih.get(r);null===l?.annotationElementId&&(Mt(t),l.dblclick(t))},{signal:t,capture:!0})}const t=this.#Mh,e=[];if(t){const i=new Map,s=new Map;for(const t of this.#$h)t.disableEditing(),t.annotationElementId?null===t.serialize()?(s.set(t.annotationElementId,t),this.getEditableAnnotation(t.annotationElementId)?.show(),t.remove()):i.set(t.annotationElementId,t):e.push(t);for(const e of t.getEditableAnnotations()){const{id:t}=e.data;if(this.#y.isDeletedAnnotationElement(t)){e.updateEdited({deleted:!0});continue}let n=s.get(t);n?(n.resetAnnotationElement(e),n.show(!1),e.show()):(n=i.get(t),n&&(this.#y.addChangedExistingAnnotation(n),n.renderAnnotationElement(e)&&n.show(!1)),e.show())}}this.#Gh(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of Qn.#Q.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(e),this.#Bh=!1}getEditableAnnotation(t){return this.#Mh?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#y.getActive()!==t&&this.#y.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#Nh?.div&&!this.#Hh){this.#Hh=new AbortController;const t=this.#y.combinedSignal(this.#Hh);this.#Nh.div.addEventListener("pointerdown",this.#jh.bind(this),{signal:t}),this.#Nh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#Nh?.div&&this.#Hh&&(this.#Hh.abort(),this.#Hh=null,this.#Nh.div.classList.remove("highlighting"))}#jh(t){this.#y.unselectAll();const{target:e}=t;if(e===this.#Nh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent")||e.classList.contains("textLayerImages")||e.classList.contains("textLayerImagePlaceholder"))&&this.#Nh.div.contains(e)){const{isMac:e}=rt.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#y.showAllEditors("highlight",!0,!0),this.#Nh.div.classList.add("free"),this.toggleDrawing(),Nn.startHighlighting(this,"ltr"===this.#y.direction,{target:this.#Nh.div,x:t.x,y:t.y}),this.#Nh.div.addEventListener("pointerup",()=>{this.#Nh.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#y._signal}),t.preventDefault()}}enableClick(){if(this.#Dh)return;this.#Dh=new AbortController;const t=this.#y.combinedSignal(this.#Dh);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#Dh?.abort(),this.#Dh=null}attach(t){this.#Ih.set(t.id,t);const{annotationElementId:e}=t;e&&this.#y.isDeletedAnnotationElement(e)&&this.#y.removeDeletedAnnotationElement(t)}detach(t){this.#Ih.delete(t.id),this.#Qr?.removePointerInTextLayer(t.contentDiv),!this.#Bh&&t.annotationElementId&&this.#y.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#y.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#y.addDeletedAnnotationElement(t),he.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.#y.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#Lh),this.#y.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#Ph&&(t._focusEventsAllowed=!1,this.#Ph=setTimeout(()=>{this.#Ph=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#y._signal}),e.focus())},0)),t._structTreeParentId=this.#Qr?.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})}getEditorByUID(t){for(const e of this.#Ih.values())if(e.uid===t)return e;return null}get#Wh(){return Qn.#Q.get(this.#y.getMode())}combinedSignal(t){return this.#y.combinedSignal(t)}#Vh(t){const e=this.#Wh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Wh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#y.updateMode(t.mode);const{offsetX:i,offsetY:s}=this.#Kh(),n=this.#y.getId(),a=this.#Vh({parent:this,id:n,x:i,y:s,uiManager:this.#y,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(Qn.#Q.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#y))||null}createAndAddNewEditor(t,e,i={}){const s=this.#y.getId(),n=this.#Vh({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#y,isCentered:e,...i});return n&&this.add(n),n}get boundingClientRect(){return this.div.getBoundingClientRect()}#Kh(){const{x:t,y:e,width:i,height:s}=this.boundingClientRect,n=Math.max(0,t),a=Math.max(0,e),r=(n+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Kh(),!0,t)}setSelected(t){this.#y.setSelected(t)}toggleSelected(t){this.#y.toggleSelected(t)}unselect(t){this.#y.unselect(t)}pointerup(t){const{isMac:e}=rt.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Fh)return;if(this.#Fh=!1,this.#Wh?.isDrawer&&this.#Wh.supportMultipleDrawings)return;if(!this.#kh)return void(this.#kh=!0);const i=this.#y.getMode();i!==b.STAMP&&i!==b.POPUP&&i!==b.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#y.unselectAll()}pointerdown(t){if(this.#y.getMode()===b.HIGHLIGHT&&this.enableTextSelection(),this.#Fh)return void(this.#Fh=!1);const{isMac:e}=rt.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#Fh=!0,this.#Wh?.isDrawer)return void this.startDrawingSession(t);const i=this.#y.getActive();this.#kh=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#Rh)return void this.#Wh.startDrawing(this,this.#y,!1,t);this.#y.setCurrentDrawingSession(this),this.#Rh=new AbortController;const e=this.#y.combinedSignal(this.#Rh);this.div.addEventListener("blur",({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#Oh=null,this.commitOrRemove())},{signal:e}),this.#Wh.startDrawing(this,this.#y,!1,t)}pause(t){if(t){const{activeElement:t}=document;return void(this.div.contains(t)&&(this.#Oh=t))}this.#Oh&&setTimeout(()=>{this.#Oh?.focus(),this.#Oh=null},0)}endDrawingSession(t=!1){return this.#Rh?(this.#y.setCurrentDrawingSession(null),this.#Rh.abort(),this.#Rh=null,this.#Oh=null,this.#Wh.endDrawing(t)):null}findNewParent(t,e,i){const s=this.#y.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}commitOrRemove(){return!!this.#Rh&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#Rh&&this.#Wh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#y.getActive()?.parent===this&&(this.#y.commitOrRemove(),this.#y.setActiveEditor(null)),this.#Ph&&(clearTimeout(this.#Ph),this.#Ph=null);for(const t of this.#Ih.values())this.#Qr?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#Ih.clear(),this.#y.removeLayer(this)}#Gh(){for(const t of this.#Ih.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t,Lt(this.div,t);for(const t of this.#y.getEditors(this.pageIndex))this.add(t),t.rebuild();await this.#y.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:t}){this.#y.commitOrRemove(),this.#Gh();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Lt(this.div,{rotation:i}),e!==i)for(const t of this.#Ih.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#y.viewParameters.realScale}}function Jn(t,e){return t===e?0:t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function Zn(t){return t?t.nodeType===Node.ELEMENT_NODE?t.closest(".textLayer"):t.parentElement?.closest(".textLayer")||null:null}function ta(t,e,i,s){if(t===i)return e<=s;const n=t.compareDocumentPosition(i);return!!(n&Node.DOCUMENT_POSITION_FOLLOWING)||!(n&Node.DOCUMENT_POSITION_PRECEDING)&&null}function ea(t,e,i){if(t.nodeType!==Node.ELEMENT_NODE||!t.classList.contains("textLayer")||e!==t.childNodes.length)return{container:t,offset:e};let s=t.lastChild;return s?.nodeType===Node.ELEMENT_NODE&&s.classList.contains("endOfContent")&&(s=s.previousSibling),s&&i.contains(s)?s.nodeType===Node.TEXT_NODE?{container:s,offset:s.textContent.length}:{container:s,offset:s.childNodes.length}:null}class ia{#wr=null;#Xh=new Map;#Nh=null;#it=null;#wt=null;#qh=null;#Yh=new Map;static#E=0;static#Qh=0;static#Jh=null;static#Zh=new Set;static#tc=!1;static#ec=new Set;static#ic=new WeakMap;constructor({filterFactory:t=null,pageColors:e=null,pageIndex:i,textLayer:s=null}){if(this.pageIndex=i,this.#it=t,this.#wt=e,s){const t=ia.#ic.get(s);if(t?.selectionDiv&&(t.selectionDiv.remove(),ia.#Zh.delete(t.selectionDiv)),ia.#ic.set(s,{drawLayer:this}),ia.#ec.add(s),this.#Nh=s,this.#qh=new MutationObserver(t=>{if(this.#wr&&this.#Nh?.isConnected&&ia.#sc())for(const{addedNodes:e}of t)for(const t of e)if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains("endOfContent"))return void ia.#Nt()}),this.#qh.observe(s,{childList:!0}),null===ia.#Jh){ia.#Jh=new AbortController;const{signal:t}=ia.#Jh;document.addEventListener("selectionchange",ia.#Nt.bind(ia),{signal:t}),document.addEventListener("pointerdown",()=>{ia.#tc=!0},{signal:t}),document.addEventListener("pointerup",()=>{ia.#tc=!1},{signal:t}),window.addEventListener("blur",()=>{ia.#tc=!1},{signal:t})}}}setParent(t){if(!this.#wr)return this.#wr=t,void(this.#Nh?.isConnected&&ia.#sc()&&ia.#Nt());if(this.#wr!==t){if(this.#Xh.size>0)for(const e of this.#Xh.values())e.remove(),t.append(e);this.#wr=t}}static#nc(t){const e=this.#ic.get(t);e?.selectionDiv&&(e.selectionDiv.remove(),this.#Zh.delete(e.selectionDiv),e.selectionDiv=null,e.path=null)}static#sc(){const t=document.getSelection();return!!t&&!t.isCollapsed}static#ac(){return[...this.#ec].filter(t=>t.isConnected).sort(Jn)}static#Nt(){const t=document.getSelection();if(!t||t.isCollapsed){for(const t of this.#Zh)t.remove();return void this.#Zh.clear()}const e=new WeakMap,i=this.#ac(),s=[];for(let e=0,n=t.rangeCount;e<n;e++){const n=t.getRangeAt(e);if(n.collapsed)continue;let{startContainer:a,startOffset:r,endContainer:o,endOffset:l}=n,h=Zn(a),c=Zn(o);const d=null===h,u=null===c;if(this.#tc&&d!==u)return;if(1===t.rangeCount){const{anchorNode:e,anchorOffset:i,focusNode:s,focusOffset:n}=t,d=Zn(e),u=Zn(s),p=ta(e,i,s,n);d&&u&&null!==p&&(p?(a=e,r=i,h=d,o=s,l=n,c=u):(a=s,r=n,h=u,o=e,l=i,c=d))}const p=i.filter(t=>n.intersectsNode(t));if(0===p.length)continue;let g=!1;if(h||(h=p[0],a=h,r=0,g=!0),c||(c=p.at(-1),o=c,l=c.childNodes.length,g=!0),o.nodeType===Node.ELEMENT_NODE)if(o.classList.contains("endOfContent")){const t=o.previousSibling;if(!t)continue;o=t,l=t.nodeType===Node.TEXT_NODE?t.textContent.length:t.childNodes.length}else if(o.classList.contains("textLayer")&&o.childNodes.length===l){const t=ea(o,l,c);if(!t)continue;o=t.container,l=t.offset}if(a.nodeType===Node.ELEMENT_NODE){const t=ea(a,r,h);if(!t)continue;a=t.container,r=t.offset}if(h!==c||g||!p.includes(h))for(const t of p){const e=t.firstChild;if(!e)continue;const i=document.createRange();if(t===h?i.setStart(a,r):i.setStartBefore(e),t===c)i.setEnd(o,l);else{const e=t.lastChild;if(!e)continue;if(e.nodeType===Node.ELEMENT_NODE&&e.classList.contains("endOfContent")){const t=e.previousSibling;if(!t)continue;i.setEndAfter(t)}else i.setEndAfter(e)}i.collapsed||s.push([i,t])}else s.push([n,h])}const n=new Set(s.map(t=>t[1]));for(const t of this.#ec)n.has(t)||this.#nc(t);for(const[t,i]of s){const s=ia.#ic.get(i);if(!s)continue;let n=e.get(i);if(!n){const t=i.getBoundingClientRect();n=(e,i,s,n)=>({x:(e-t.x)/t.width,y:(i-t.y)/t.height,width:s/t.width,height:n/t.height}),e.set(i,n)}const a=[];for(let{x:e,y:i,width:s,height:r}of t.getClientRects())0!==s&&0!==r&&(({x:e,y:i,width:s,height:r}=n(e,i,s,r)),1===s&&1===r||a.push(`M${e} ${i} h${s} v${r} h-${s} Z`));if(0===a.length)continue;const r=s.drawLayer;let o=s.selectionDiv,l=s.path;if(!o){const t="clip_selection_"+ia.#Qh++;o=document.createElement("div"),o.className="selection",o.style.clipPath=`url(#${t})`;const e=r.#it?.createSelectionStyle(r.#wt);if(e)for(const[t,i]of Object.entries(e))o.style.setProperty(t,i);const i=ia._svgFactory.create(1,1,!0);i.setAttribute("aria-hidden","true"),i.setAttribute("width","100%"),i.setAttribute("height","100%");const n=ia._svgFactory.createElement("clipPath");n.setAttribute("id",t),n.setAttribute("clipPathUnits","objectBoundingBox"),l=ia._svgFactory.createElement("path"),n.append(l),i.append(n),o.append(i),s.path=l,s.selectionDiv=o}!o.parentNode&&r.#wr&&(r.#wr.append(o),this.#Zh.add(o)),l.setAttribute("d",a.join(" "))}}static get _svgFactory(){return Q(this,"_svgFactory",new Ys)}static#rc(t,[e,i,s,n]){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*s+"%",a.height=100*n+"%"}#oc(){const t=ia._svgFactory.create(1,1,!0);return this.#wr.append(t),t.setAttribute("aria-hidden","true"),t}#lc(t,e){const i=ia._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");const n=ia._svgFactory.createElement("use");return i.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),s}#hc(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=ia.#E++,n=this.#oc(),a=ia._svgFactory.createElement("defs");n.append(a);const r=ia._svgFactory.createElement("path");a.append(r);const o=`path_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#Yh.set(s,r);const l=i?this.#lc(a,o):null,h=ia._svgFactory.createElement("use");return n.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(n,t),this.#Xh.set(s,n),{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=ia.#E++,s=this.#oc(),n=ia._svgFactory.createElement("defs");s.append(n);const a=ia._svgFactory.createElement("path");n.append(a);const r=`path_${i}`;let o;if(a.setAttribute("id",r),a.setAttribute("vector-effect","non-scaling-stroke"),e){const t=ia._svgFactory.createElement("mask");n.append(t),o=`mask_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=ia._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const s=ia._svgFactory.createElement("use");t.append(s),s.setAttribute("href",`#${r}`),s.setAttribute("stroke","none"),s.setAttribute("fill","black"),s.setAttribute("fill-rule","nonzero"),s.classList.add("mask")}const l=ia._svgFactory.createElement("use");s.append(l),l.setAttribute("href",`#${r}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return s.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(s,t),this.#Xh.set(i,s),i}finalizeDraw(t,e){this.#Yh.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:a}=e,r="number"==typeof t?this.#Xh.get(t):t;if(r){if(i&&this.#hc(r,i),s&&ia.#rc(r,s),n){const{classList:t}=r;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(a){const t=r.firstElementChild.firstElementChild;this.#hc(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#Xh.get(t);i&&(e.#wr.append(i),this.#Xh.delete(t),e.#Xh.set(t,i))}remove(t){this.#Yh.delete(t),null!==this.#wr&&(this.#Xh.get(t).remove(),this.#Xh.delete(t))}destroy(){this.#wr=null;for(const t of this.#Xh.values())t.remove();if(this.#Xh.clear(),this.#Yh.clear(),this.#qh?.disconnect(),this.#qh=null,this.#Nh){const t=ia.#ic.get(this.#Nh);t?.drawLayer===this&&(ia.#nc(this.#Nh),ia.#ic.delete(this.#Nh),ia.#ec.delete(this.#Nh),0===ia.#ec.size&&(ia.#Jh?.abort(),ia.#Jh=null,ia.#tc=!1)),this.#Nh=null}}}function sa(t){return`${(100*t).toFixed(2)}%`}class na{#cc=[];#dc=new Map;#uc=null;#pc=0;#Kn=0;#Vn=0;static#gc=null;constructor(t,e,i,s){this.#pc=t,this.#cc=e,this.#Kn=i.rawDims.pageWidth,this.#Vn=i.rawDims.pageHeight,this.#uc=s}render(){const t=document.createElement("div");t.className="textLayerImages";for(let e=0;e<this.#cc.length;e+=6){const i=this.#mc(this.#cc.subarray(e,e+6));i&&t.append(i)}return t.addEventListener("contextmenu",t=>{if(!(t.target instanceof HTMLCanvasElement))return;const e=t.target,i=this.#dc.get(e);if(!i)return;const s=na.#gc?.deref();if(s===e)return;s&&(s.width=0,s.height=0),na.#gc=new WeakRef(e);const{inverseTransform:n,x1:a,y1:r,width:o,height:l}=i,h=this.#uc(),c=Math.ceil(a*h.width),d=Math.ceil(r*h.height),u=Math.floor((a+o/this.#Kn)*h.width),p=Math.floor((r+l/this.#Vn)*h.height);e.width=u-c,e.height=p-d;const g=e.getContext("2d");g.setTransform(...n),g.translate(-c,-d),g.drawImage(h,0,0)}),t}#mc([t,e,i,s,n,a]){const r=Math.hypot((n-t)*this.#Kn,(a-e)*this.#Vn),o=Math.hypot((i-t)*this.#Kn,(s-e)*this.#Vn);if(r<this.#pc||o<this.#pc)return null;const l=[(n-t)*this.#Kn/r,(a-e)*this.#Vn/r,(i-t)*this.#Kn/o,(s-e)*this.#Vn/o,0,0],h=ot.inverseTransform(l),c=document.createElement("canvas");return c.className="textLayerImagePlaceholder",c.width=0,c.height=0,Object.assign(c.style,{opacity:0,position:"absolute",left:sa(t),top:sa(e),width:sa(r/this.#Kn),height:sa(o/this.#Vn),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`}),this.#dc.set(c,{inverseTransform:h,width:r,height:o,x1:t,y1:e}),c}}globalThis._pdfjsTestingUtils={HighlightOutliner:Bn},globalThis.pdfjsLib={AbortException:nt,AnnotationEditorLayer:Qn,AnnotationEditorParamsType:y,AnnotationEditorType:b,AnnotationEditorUIManager:ae,AnnotationLayer:kn,AnnotationMode:g,AnnotationType:_,applyOpacity:Ut,build:$s,ColorPicker:js,createValidAbsoluteUrl:X,CSSConstants:Ht,DOMSVGFactory:Ys,DrawLayer:ia,FeatureTest:rt,fetchData:At,findContrastColor:Vt,getDocument:Fs,getFilenameFromUrl:St,getPdfFilenameFromUrl:Tt,getRGB:It,getRGBA:Pt,getUuid:dt,GlobalWorkerOptions:Cs,ImageKind:E,InvalidPDFException:et,isDataScheme:xt,isPdfFile:Ct,isValidExplicitDest:qe,makeArr:ut,makeMap:pt,makeObj:gt,MathClamp:mt,noContextMenu:kt,normalizeUnicode:ct,OPS:B,OutputScale:Rt,PasswordResponses:U,PDFDataRangeTransport:Ls,PDFDateString:Dt,PDFWorker:Ns,PermissionFlag:v,PixelsPerInch:vt,RenderingCancelledException:wt,renderRichText:Kt,ResponseException:it,setLayerDimensions:Lt,shadow:Q,SignatureExtractor:Vn,stopEvent:Mt,SupportedImageMimeTypes:Ot,TextLayer:Is,TextLayerImages:na,TouchManager:le,updateUrlHash:q,Util:ot,VerbosityLevel:F,version:Gs,XfaLayer:yt};export{nt as AbortException,Qn as AnnotationEditorLayer,y as AnnotationEditorParamsType,b as AnnotationEditorType,ae as AnnotationEditorUIManager,kn as AnnotationLayer,g as AnnotationMode,_ as AnnotationType,Ht as CSSConstants,js as ColorPicker,Ys as DOMSVGFactory,ia as DrawLayer,rt as FeatureTest,Cs as GlobalWorkerOptions,E as ImageKind,et as InvalidPDFException,mt as MathClamp,B as OPS,Rt as OutputScale,Ls as PDFDataRangeTransport,Dt as PDFDateString,Ns as PDFWorker,U as PasswordResponses,v as PermissionFlag,vt as PixelsPerInch,wt as RenderingCancelledException,it as ResponseException,Vn as SignatureExtractor,Ot as SupportedImageMimeTypes,Is as TextLayer,na as TextLayerImages,le as TouchManager,ot as Util,F as VerbosityLevel,yt as XfaLayer,Ut as applyOpacity,$s as build,X as createValidAbsoluteUrl,At as fetchData,Vt as findContrastColor,Fs as getDocument,St as getFilenameFromUrl,Tt as getPdfFilenameFromUrl,It as getRGB,Pt as getRGBA,dt as getUuid,xt as isDataScheme,Ct as isPdfFile,qe as isValidExplicitDest,ut as makeArr,pt as makeMap,gt as makeObj,kt as noContextMenu,ct as normalizeUnicode,Kt as renderRichText,Lt as setLayerDimensions,Q as shadow,Mt as stopEvent,q as updateUrlHash,Gs as version};
1
+ var t,e,i,s=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,h=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},d=(t,e,i)=>(i=null!=t?s(o(t)):{},((t,e,i,s)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let o of a(e))!l.call(t,o)&&o!==i&&r(t,o,{get:()=>e[o],enumerable:!(s=n(e,o))||s.enumerable});return t})(!e&&t&&t.__esModule?i:r(i,"default",{value:t,enumerable:!0}),t)),c=h((t,e)=>{Gt();var i=function(t){return t&&t.Math===Math&&t};e.exports=i("object"==typeof globalThis&&globalThis)||i("object"==typeof window&&window)||i("object"==typeof self&&self)||i("object"==typeof global&&global)||i("object"==typeof t&&t)||function(){return this}()||Function("return this")()}),u=h((t,e)=>{Gt(),e.exports=function(t){try{return!!t()}catch{return!0}}}),p=h((t,e)=>{Gt();var i=u();e.exports=!i(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})}),g=h((t,e)=>{Gt();var i=u();e.exports=!i(function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")})}),m=h((t,e)=>{Gt();var i=g(),s=Function.prototype.call;e.exports=i?s.bind(s):function(){return s.apply(s,arguments)}}),f=h(t=>{Gt();var e={}.propertyIsEnumerable,i=Object.getOwnPropertyDescriptor,s=i&&!e.call({1:2},1);t.f=s?function(t){var e=i(this,t);return!!e&&e.enumerable}:e}),b=h((t,e)=>{Gt(),e.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}}),v=h((t,e)=>{Gt();var i=g(),s=Function.prototype,r=s.call,n=i&&s.bind.bind(r,r);e.exports=i?n:function(t){return function(){return r.apply(t,arguments)}}}),y=h((t,e)=>{Gt();var i=v(),s=i({}.toString),r=i("".slice);e.exports=function(t){return r(s(t),8,-1)}}),A=h((t,e)=>{Gt();var i=v(),s=u(),r=y(),n=Object,a=i("".split);e.exports=s(function(){return!n("z").propertyIsEnumerable(0)})?function(t){return"String"===r(t)?a(t,""):n(t)}:n}),w=h((t,e)=>{Gt(),e.exports=function(t){return null==t}}),x=h((t,e)=>{Gt();var i=w(),s=TypeError;e.exports=function(t){if(i(t))throw new s("Can't call method on "+t);return t}}),_=h((t,e)=>{Gt();var i=A(),s=x();e.exports=function(t){return i(s(t))}}),S=h((t,e)=>{Gt();var i="object"==typeof document&&document.all;e.exports=typeof i>"u"&&void 0!==i?function(t){return"function"==typeof t||t===i}:function(t){return"function"==typeof t}}),C=h((t,e)=>{Gt();var i=S();e.exports=function(t){return"object"==typeof t?null!==t:i(t)}}),E=h((t,e)=>{Gt();var i=c(),s=S();e.exports=function(t,e){return arguments.length<2?function(t){return s(t)?t:void 0}(i[t]):i[t]&&i[t][e]}}),k=h((t,e)=>{Gt();var i=v();e.exports=i({}.isPrototypeOf)}),T=h((t,e)=>{Gt();var i=c().navigator,s=i&&i.userAgent;e.exports=s?String(s):""}),M=h((t,e)=>{Gt();var i,s,r=c(),n=T(),a=r.process,o=r.Deno,l=a&&a.versions||o&&o.version,h=l&&l.v8;h&&(s=(i=h.split("."))[0]>0&&i[0]<4?1:+(i[0]+i[1])),!s&&n&&((!(i=n.match(/Edge\/(\d+)/))||i[1]>=74)&&((i=n.match(/Chrome\/(\d+)/))&&(s=+i[1]))),e.exports=s}),P=h((t,e)=>{Gt();var i=M(),s=u(),r=c().String;e.exports=!!Object.getOwnPropertySymbols&&!s(function(){var t=Symbol("symbol detection");return!r(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&i&&i<41})}),D=h((t,e)=>{Gt();var i=P();e.exports=i&&!Symbol.sham&&"symbol"==typeof Symbol.iterator}),I=h((t,e)=>{Gt();var i=E(),s=S(),r=k(),n=D(),a=Object;e.exports=n?function(t){return"symbol"==typeof t}:function(t){var e=i("Symbol");return s(e)&&r(e.prototype,a(t))}}),F=h((t,e)=>{Gt();var i=String;e.exports=function(t){try{return i(t)}catch{return"Object"}}}),L=h((t,e)=>{Gt();var i=S(),s=F(),r=TypeError;e.exports=function(t){if(i(t))return t;throw new r(s(t)+" is not a function")}}),O=h((t,e)=>{Gt();var i=L(),s=w();e.exports=function(t,e){var r=t[e];return s(r)?void 0:i(r)}}),R=h((t,e)=>{Gt();var i=m(),s=S(),r=C(),n=TypeError;e.exports=function(t,e){var a,o;if("string"===e&&s(a=t.toString)&&!r(o=i(a,t))||s(a=t.valueOf)&&!r(o=i(a,t))||"string"!==e&&s(a=t.toString)&&!r(o=i(a,t)))return o;throw new n("Can't convert object to primitive value")}}),N=h((t,e)=>{Gt(),e.exports=!1}),B=h((t,e)=>{Gt();var i=c(),s=Object.defineProperty;e.exports=function(t,e){try{s(i,t,{value:e,configurable:!0,writable:!0})}catch{i[t]=e}return e}}),U=h((t,e)=>{Gt();var i=N(),s=c(),r=B(),n="__core-js_shared__",a=e.exports=s[n]||r(n,{});(a.versions||(a.versions=[])).push({version:"3.49.0",mode:i?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"})}),H=h((t,e)=>{Gt();var i=U();e.exports=function(t,e){return i[t]||(i[t]=e||{})}}),j=h((t,e)=>{Gt();var i=x(),s=Object;e.exports=function(t){return s(i(t))}}),$=h((t,e)=>{Gt();var i=v(),s=j(),r=i({}.hasOwnProperty);e.exports=Object.hasOwn||function(t,e){return r(s(t),e)}}),G=h((t,e)=>{Gt();var i=v(),s=0,r=Math.random(),n=i(1.1.toString);e.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+n(++s+r,36)}}),z=h((t,e)=>{Gt();var i=c(),s=H(),r=$(),n=G(),a=P(),o=D(),l=i.Symbol,h=s("wks"),d=o?l.for||l:l&&l.withoutSetter||n;e.exports=function(t){return r(h,t)||(h[t]=a&&r(l,t)?l[t]:d("Symbol."+t)),h[t]}}),V=h((t,e)=>{Gt();var i=m(),s=C(),r=I(),n=O(),a=R(),o=z(),l=TypeError,h=o("toPrimitive");e.exports=function(t,e){if(!s(t)||r(t))return t;var o,d=n(t,h);if(d){if(void 0===e&&(e="default"),o=i(d,t,e),!s(o)||r(o))return o;throw new l("Can't convert object to primitive value")}return void 0===e&&(e="number"),a(t,e)}}),W=h((t,e)=>{Gt();var i=V(),s=I();e.exports=function(t){var e=i(t,"string");return s(e)?e:e+""}}),X=h((t,e)=>{Gt();var i=c(),s=C(),r=i.document,n=s(r)&&s(r.createElement);e.exports=function(t){return n?r.createElement(t):{}}}),Y=h((t,e)=>{Gt();var i=p(),s=u(),r=X();e.exports=!i&&!s(function(){return 7!==Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a})}),q=h(t=>{Gt();var e=p(),i=m(),s=f(),r=b(),n=_(),a=W(),o=$(),l=Y(),h=Object.getOwnPropertyDescriptor;t.f=e?h:function(t,e){if(t=n(t),e=a(e),l)try{return h(t,e)}catch{}if(o(t,e))return r(!i(s.f,t,e),t[e])}}),K=h((t,e)=>{Gt();var i=p(),s=u();e.exports=i&&s(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype})}),Q=h((t,e)=>{Gt();var i=C(),s=String,r=TypeError;e.exports=function(t){if(i(t))return t;throw new r(s(t)+" is not an object")}}),J=h(t=>{Gt();var e=p(),i=Y(),s=K(),r=Q(),n=W(),a=TypeError,o=Object.defineProperty,l=Object.getOwnPropertyDescriptor,h="enumerable",d="configurable",c="writable";t.f=e?s?function(t,e,i){if(r(t),e=n(e),r(i),"function"==typeof t&&"prototype"===e&&"value"in i&&c in i&&!i[c]){var s=l(t,e);s&&s[c]&&(t[e]=i.value,i={configurable:d in i?i[d]:s[d],enumerable:h in i?i[h]:s[h],writable:!1})}return o(t,e,i)}:o:function(t,e,s){if(r(t),e=n(e),r(s),i)try{return o(t,e,s)}catch{}if("get"in s||"set"in s)throw new a("Accessors not supported");return"value"in s&&(t[e]=s.value),t}}),Z=h((t,e)=>{Gt();var i=p(),s=J(),r=b();e.exports=i?function(t,e,i){return s.f(t,e,r(1,i))}:function(t,e,i){return t[e]=i,t}}),tt=h((t,e)=>{Gt();var i=p(),s=$(),r=Function.prototype,n=i&&Object.getOwnPropertyDescriptor,a=s(r,"name"),o=a&&"something"===function(){}.name,l=a&&(!i||i&&n(r,"name").configurable);e.exports={EXISTS:a,PROPER:o,CONFIGURABLE:l}}),et=h((t,e)=>{Gt();var i=v(),s=S(),r=U(),n=i(Function.toString);s(r.inspectSource)||(r.inspectSource=function(t){return n(t)}),e.exports=r.inspectSource}),it=h((t,e)=>{Gt();var i=c(),s=S(),r=i.WeakMap;e.exports=s(r)&&/native code/.test(String(r))}),st=h((t,e)=>{Gt();var i=H(),s=G(),r=i("keys");e.exports=function(t){return r[t]||(r[t]=s(t))}}),rt=h((t,e)=>{Gt(),e.exports={}}),nt=h((t,e)=>{Gt();var i,s,r,n,a,o=it(),l=c(),h=C(),d=Z(),u=$(),p=U(),g=st(),m=rt(),f="Object already initialized",b=l.TypeError,v=l.WeakMap;o||p.state?((n=p.state||(p.state=new v)).get=n.get,n.has=n.has,n.set=n.set,i=function(t,e){if(n.has(t))throw new b(f);return e.facade=t,n.set(t,e),e},s=function(t){return n.get(t)||{}},r=function(t){return n.has(t)}):(m[a=g("state")]=!0,i=function(t,e){if(u(t,a))throw new b(f);return e.facade=t,d(t,a,e),e},s=function(t){return u(t,a)?t[a]:{}},r=function(t){return u(t,a)}),e.exports={set:i,get:s,has:r,enforce:function(t){return r(t)?s(t):i(t,{})},getterFor:function(t){return function(e){var i;if(!h(e)||(i=s(e)).type!==t)throw new b("Incompatible receiver, "+t+" required");return i}}}}),at=h((t,e)=>{Gt();var i=v(),s=u(),r=S(),n=$(),a=p(),o=tt().CONFIGURABLE,l=et(),h=nt(),d=h.enforce,c=h.get,g=String,m=Object.defineProperty,f=i("".slice),b=i("".replace),y=i([].join),A=a&&!s(function(){return 8!==m(function(){},"length",{value:8}).length}),w=String(String).split("String"),x=e.exports=function(t,e,i){"Symbol("===f(g(e),0,7)&&(e="["+b(g(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(e="get "+e),i&&i.setter&&(e="set "+e),(!n(t,"name")||o&&t.name!==e)&&(a?m(t,"name",{value:e,configurable:!0}):t.name=e),A&&i&&n(i,"arity")&&t.length!==i.arity&&m(t,"length",{value:i.arity});try{i&&n(i,"constructor")&&i.constructor?a&&m(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch{}var s=d(t);return n(s,"source")||(s.source=y(w,"string"==typeof e?e:"")),t};Function.prototype.toString=x(function(){return r(this)&&c(this).source||l(this)},"toString")}),ot=h((t,e)=>{Gt();var i=S(),s=J(),r=at(),n=B();e.exports=function(t,e,a,o){o||(o={});var l=o.enumerable,h=void 0!==o.name?o.name:e;if(i(a)&&r(a,h,o),o.global)l?t[e]=a:n(e,a);else{try{o.unsafe?t[e]&&(l=!0):delete t[e]}catch{}l?t[e]=a:s.f(t,e,{value:a,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return t}}),lt=h((t,e)=>{Gt();var i=Math.ceil,s=Math.floor;e.exports=Math.trunc||function(t){var e=+t;return(e>0?s:i)(e)}}),ht=h((t,e)=>{Gt();var i=lt();e.exports=function(t){var e=+t;return e!=e||0===e?0:i(e)}}),dt=h((t,e)=>{Gt();var i=ht(),s=Math.max,r=Math.min;e.exports=function(t,e){var n=i(t);return n<0?s(n+e,0):r(n,e)}}),ct=h((t,e)=>{Gt();var i=ht(),s=Math.min;e.exports=function(t){var e=i(t);return e>0?s(e,9007199254740991):0}}),ut=h((t,e)=>{Gt();var i=ct();e.exports=function(t){return i(t.length)}}),pt=h((t,e)=>{Gt();var i=_(),s=dt(),r=ut(),n=function(t){return function(e,n,a){var o=i(e),l=r(o);if(0===l)return!t&&-1;var h,d=s(a,l);if(t&&n!=n){for(;l>d;)if((h=o[d++])!=h)return!0}else for(;l>d;d++)if((t||d in o)&&o[d]===n)return t||d||0;return!t&&-1}};e.exports={includes:n(!0),indexOf:n(!1)}}),gt=h((t,e)=>{Gt();var i=v(),s=$(),r=_(),n=pt().indexOf,a=rt(),o=i([].push);e.exports=function(t,e){var i,l=r(t),h=0,d=[];for(i in l)!s(a,i)&&s(l,i)&&o(d,i);for(;e.length>h;)s(l,i=e[h++])&&(~n(d,i)||o(d,i));return d}}),mt=h((t,e)=>{Gt(),e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]}),ft=h(t=>{Gt();var e=gt(),i=mt().concat("length","prototype");t.f=Object.getOwnPropertyNames||function(t){return e(t,i)}}),bt=h(t=>{Gt(),t.f=Object.getOwnPropertySymbols}),vt=h((t,e)=>{Gt();var i=E(),s=v(),r=ft(),n=bt(),a=Q(),o=s([].concat);e.exports=i("Reflect","ownKeys")||function(t){var e=r.f(a(t)),i=n.f;return i?o(e,i(t)):e}}),yt=h((t,e)=>{Gt();var i=$(),s=vt(),r=q(),n=J();e.exports=function(t,e,a){for(var o=s(e),l=n.f,h=r.f,d=0;d<o.length;d++){var c=o[d];!i(t,c)&&(!a||!i(a,c))&&l(t,c,h(e,c))}}}),At=h((t,e)=>{Gt();var i=u(),s=S(),r=/#|\.prototype\./,n=function(t,e){var r=o[a(t)];return r===h||r!==l&&(s(e)?i(e):!!e)},a=n.normalize=function(t){return String(t).replace(r,".").toLowerCase()},o=n.data={},l=n.NATIVE="N",h=n.POLYFILL="P";e.exports=n}),wt=h((t,e)=>{Gt();var i=c(),s=q().f,r=Z(),n=ot(),a=B(),o=yt(),l=At();e.exports=function(t,e){var h,d,c,u,p,g=t.target,m=t.global,f=t.stat;if(h=m?i:f?i[g]||a(g,{}):i[g]&&i[g].prototype)for(d in e){if(u=e[d],t.dontCallGetSet?c=(p=s(h,d))&&p.value:c=h[d],!l(m?d:g+(f?".":"#")+d,t.forced)&&void 0!==c){if(typeof u==typeof c)continue;o(u,c)}(t.sham||c&&c.sham)&&r(u,"sham",!0),n(h,d,u,t)}}}),xt=h((t,e)=>{Gt();var i=v(),s=Map.prototype;e.exports={Map:Map,set:i(s.set),get:i(s.get),has:i(s.has),remove:i(s.delete),proto:s}}),_t=h(()=>{Gt();var t=wt(),e=L(),i=xt(),s=N(),r=i.get,n=i.has,a=i.set;t({target:"Map",proto:!0,real:!0,forced:s},{getOrInsertComputed:function(t,i){var s=n(this,t);if(e(i),s)return r(this,t);0===t&&1/t==-1/0&&(t=0);var o=i(t);return a(this,t,o),o}})}),St=h((t,e)=>{Gt();var i=g(),s=Function.prototype,r=s.apply,n=s.call;e.exports="object"==typeof Reflect&&Reflect.apply||(i?n.bind(r):function(){return n.apply(r,arguments)})}),Ct=h((t,e)=>{Gt();var i=v();e.exports=i([].slice)}),Et=h((t,e)=>{Gt();var i=L(),s=TypeError,r=function(t){var e,r;this.promise=new t(function(t,i){if(void 0!==e||void 0!==r)throw new s("Bad Promise constructor");e=t,r=i}),this.resolve=i(e),this.reject=i(r)};e.exports.f=function(t){return new r(t)}}),kt=h((t,e)=>{Gt(),e.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}}),Tt=h(()=>{Gt();var t=wt(),e=c(),i=St(),s=Ct(),r=Et(),n=L(),a=kt(),o=e.Promise,l=!1;t({target:"Promise",stat:!0,forced:!o||!o.try||a(function(){o.try(function(t){l=8===t},8)}).error||!l},{try:function(t){var e=arguments.length>1?s(arguments,1):[],o=r.f(this),l=a(function(){return i(n(t),void 0,e)});return(l.error?o.reject:o.resolve)(l.value),o.promise}})}),Mt=h(()=>{Gt();var t=wt(),e=Et();t({target:"Promise",stat:!0},{withResolvers:function(){var t=e.f(this);return{promise:t.promise,resolve:t.resolve,reject:t.reject}}})}),Pt=h((t,e)=>{Gt();var i={};i[z()("toStringTag")]="z",e.exports="[object z]"===String(i)}),Dt=h((t,e)=>{Gt();var i=Pt(),s=S(),r=y(),n=z()("toStringTag"),a=Object,o="Arguments"===r(function(){return arguments}());e.exports=i?r:function(t){var e,i,l;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch{}}(e=a(t),n))?i:o?r(e):"Object"===(l=r(e))&&s(e.callee)?"Arguments":l}}),It=h((t,e)=>{Gt();var i=Dt(),s=TypeError;e.exports=function(t){if("Uint8Array"===i(t))return t;throw new s("Argument is not an Uint8Array")}}),Ft=h((t,e)=>{Gt(),e.exports=typeof ArrayBuffer<"u"&&typeof DataView<"u"}),Lt=h((t,e)=>{Gt();var i=v(),s=L();e.exports=function(t,e,r){try{return i(s(Object.getOwnPropertyDescriptor(t,e)[r]))}catch{}}}),Ot=h((t,e)=>{Gt();var i=c(),s=Lt(),r=y(),n=i.ArrayBuffer,a=i.TypeError;e.exports=n&&s(n.prototype,"byteLength","get")||function(t){if("ArrayBuffer"!==r(t))throw new a("ArrayBuffer expected");return t.byteLength}}),Rt=h((t,e)=>{Gt();var i=c(),s=Ft(),r=Ot(),n=i.DataView;e.exports=function(t){if(!s||0!==r(t))return!1;try{return new n(t),!1}catch{return!0}}}),Nt=h((t,e)=>{Gt();var i=Rt(),s=TypeError;e.exports=function(t){if(i(t))throw new s("ArrayBuffer is detached");return t}}),Bt=h(()=>{Gt();var t=wt(),e=c(),i=v(),s=It(),r=Nt(),n=i(1.1.toString),a=i([].join),o=Array,l=e.Uint8Array,h=!l||!l.prototype.toHex||!function(){try{return"ffffffffffffffff"===new l([255,255,255,255,255,255,255,255]).toHex()}catch{return!1}}();l&&t({target:"Uint8Array",proto:!0,forced:h},{toHex:function(){s(this),r(this.buffer);for(var t=o(this.length),e=0,i=this.length;e<i;e++){var l=n(this[e],16);t[e]=1===l.length?"0"+l:l}return a(t,"")}})}),Ut=h((t,e)=>{Gt();var i=TypeError;e.exports=function(t,e){if(t<e)throw new i("Not enough arguments");return t}}),Ht=h((t,e)=>{Gt();var i=Dt(),s=String;e.exports=function(t){if("Symbol"===i(t))throw new TypeError("Cannot convert a Symbol value to a string");return s(t)}}),jt=h((t,e)=>{Gt();var i=u(),s=z(),r=p(),n=N(),a=s("iterator");e.exports=!i(function(){var t=new URL("b?a=1&b=2&c=3","https://a"),e=t.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),s="";return t.pathname="c%20d",e.forEach(function(t,i){e.delete("b"),s+=i+t}),i.delete("a",2),i.delete("b",void 0),n&&(!t.toJSON||!i.has("a",1)||i.has("a",2)||!i.has("a",void 0)||i.has("b"))||!e.size&&(n||!r)||!e.sort||"https://a/c%20d?a=1&c=3"!==t.href||"3"!==e.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!e[a]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==s||"x"!==new URL("https://x",void 0).host})}),$t=h(()=>{Gt();var t=wt(),e=E(),i=Ut(),s=Ht(),r=jt(),n=e("URL");t({target:"URL",stat:!0,forced:!r},{parse:function(t){var e=i(arguments.length,1),r=s(t),a=e<2||void 0===arguments[1]?void 0:s(arguments[1]);try{return new n(r,a)}catch{return null}}})}),Gt=(t=()=>{d(_t()),d(Tt()),d(Mt()),d(Bt()),d($t())},()=>{if(i)throw i[0];try{return t&&(e=t(t=0)),e}catch(t){throw i=[t],t}});Gt();var zt=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),Vt=[1/0,1/0,-1/0,-1/0],Wt=new Float32Array(Vt),Xt=[.001,0,0,.001,0,0],Yt=1.35,qt="http://www.w3.org/2000/svg",Kt=1,Qt=2,Jt=4,Zt=16,te=32,ee=64,ie=128,se=256,re={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},ne="pdfjs_internal_id_",ae="pdfjs_internal_editor_",oe={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},le={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},he={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},de=0,ce=1,ue=2,pe=3,ge=3,me=4,fe={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},be={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},ve=1,ye=2,Ae=3,we=4,xe=5,_e={ERRORS:0,WARNINGS:1,INFOS:5},Se={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,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Ce=0,Ee=1,ke=2,Te=3,Me=4,Pe={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},De=_e.WARNINGS;function Ie(){return De}function Fe(t){De>=_e.INFOS&&console.info(`Info: ${t}`)}function Le(t){De>=_e.WARNINGS&&console.warn(`Warning: ${t}`)}function Oe(t){throw new Error(t)}function Re(t,e){t||Oe(e)}function Ne(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t&&(i.addDefaultProtocol&&t.startsWith("www.")&&t.match(/\./g)?.length>=2&&(t=`http://${t}`),i.tryConvertEncoding))try{t=function(t){return decodeURIComponent(escape(t))}(t)}catch{}let s=e?URL.parse(t,e):URL.parse(t);return function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s)?s:null}function Be(t,e,i=!1){let s=URL.parse(t);return s?(s.hash=e,s.href):i&&Ne(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function Ue(t){return t.substring(t.lastIndexOf("/")+1)}function He(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}var je=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}(),$e=class extends je{constructor(t,e){super(t,"PasswordException"),this.code=e}},Ge=class extends je{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}},ze=class extends je{constructor(t){super(t,"InvalidPDFException")}},Ve=class extends je{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}},We=class extends je{constructor(t){super(t,"FormatError")}},Xe=class extends je{constructor(t){super(t,"AbortException")}};function Ye(t){"string"!=typeof t&&Oe("Invalid argument for stringToBytes");let e=t.length,i=new Uint8Array(e);for(let s=0;s<e;++s)i[s]=255&t.charCodeAt(s);return i}var qe=class{static get isLittleEndian(){let t=new Uint8Array(4);return t[0]=1,He(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return He(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return He(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return He(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return He(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){let{platform:t,userAgent:e}=navigator;return He(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;return this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):typeof document<"u"&&(t=document.createElement("canvas").getContext("2d")),He(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){if(typeof document>"u")return He(this,"isAlphaColorInputSupported",!1);let t=document.createElement("input");return t.type="color",t.setAttribute("alpha",""),t.value="#ff000080",He(this,"isAlphaColorInputSupported","#ff0000"!==t.value)}},Ke=class{static get hexNums(){return He(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,i){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[i]}`}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 multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){let s=t[i],r=t[i+1];t[i]=s*e[0]+r*e[2]+e[4],t[i+1]=s*e[1]+r*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){let s=e[0],r=e[1],n=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){let h=t[i+e],d=t[i+e+1];t[i+e]=h*s+d*n+o,t[i+e+1]=h*r+d*a+l}}static applyInverseTransform(t,e){let i=t[0],s=t[1],r=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-s*e[2]+e[2]*e[5]-e[4]*e[3])/r,t[1]=(-i*e[1]+s*e[0]+e[4]*e[1]-e[5]*e[0])/r}static axialAlignedBoundingBox(t,e,i){let s=e[0],r=e[1],n=e[2],a=e[3],o=e[4],l=e[5],h=t[0],d=t[1],c=t[2],u=t[3],p=s*h+o,g=p,m=s*c+o,f=m,b=a*d+l,v=b,y=a*u+l,A=y;if(0!==r||0!==n){let t=r*h,e=r*c,i=n*d,s=n*u;p+=i,f+=i,m+=s,g+=s,b+=t,A+=t,y+=e,v+=e}i[0]=Math.min(i[0],p,m,g,f),i[1]=Math.min(i[1],b,y,v,A),i[2]=Math.max(i[2],p,m,g,f),i[3]=Math.max(i[3],b,y,v,A)}static inverseTransform(t){let 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,e){let i=t[0],s=t[1],r=t[2],n=t[3],a=i**2+s**2,o=i*r+s*n,l=r**2+n**2,h=(a+l)/2,d=Math.sqrt(h**2-(a*l-o**2));e[0]=Math.sqrt(h+d||1),e[1]=Math.sqrt(h-d||1)}static normalizeRect(t){let 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){let i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;let r=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),n=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return r>n?null:[i,r,s,n]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,s,r){r[0]=Math.min(r[0],t,i),r[1]=Math.min(r[1],e,s),r[2]=Math.max(r[2],t,i),r[3]=Math.max(r[3],e,s)}static#t(t,e,i,s,r,n,a,o,l,h){if(l<=0||l>=1)return;let d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*r+3*l*n)+3*c*a)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,s,r,n,a,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,s,r,n,a,o,-d/h,c));let u=h**2-4*d*l;if(u<0)return;let p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,r,n,a,o,(-h+p)/g,c),this.#t(t,e,i,s,r,n,a,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,r,n,a,o,l){l[0]=Math.min(l[0],t,a),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,a),l[3]=Math.max(l[3],e,o),this.#e(t,i,r,a,e,s,n,o,3*(3*(i-r)-t+a),6*(t-2*i+r),3*(i-t),l),this.#e(t,i,r,a,e,s,n,o,3*(3*(s-n)-e+o),6*(e-2*s+n),3*(s-e),l)}};var Qe=null,Je=null;function Ze(t){return Qe||(Qe=/([\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,Je=new Map([["ſt","ſt"]])),t.replaceAll(Qe,(t,e,i)=>e?e.normalize("NFKC"):Je.get(i))}function ti(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();let t=new Uint8Array(32);return crypto.getRandomValues(t),function(t){("object"!=typeof t||void 0===t?.length)&&Oe("Invalid argument for bytesToString");let e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);let s=[];for(let r=0;r<e;r+=i){let n=Math.min(r+i,e),a=t.subarray(r,n);s.push(String.fromCharCode.apply(null,a))}return s.join("")}(t)}var ei=()=>[],ii=()=>new Map,si=()=>Object.create(null);function ri(t,e,i){return Math.min(Math.max(t,e),i)}var ni=class t{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:r=0,offsetY:n=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=s,this.offsetX=r,this.offsetY=n,i*=e;let o,l,h,d,c,u,p,g,m=(t[2]+t[0])/2,f=(t[3]+t[1])/2;switch((s%=360)<0&&(s+=360),s){case 180:o=-1,l=0,h=0,d=1;break;case 90:o=0,l=1,h=1,d=0;break;case 270:o=0,l=-1,h=-1,d=0;break;case 0:o=1,l=0,h=0,d=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(h=-h,d=-d),0===o?(c=Math.abs(f-t[1])*i+r,u=Math.abs(m-t[0])*i+n,p=(t[3]-t[1])*i,g=(t[2]-t[0])*i):(c=Math.abs(m-t[0])*i+r,u=Math.abs(f-t[1])*i+n,p=(t[2]-t[0])*i,g=(t[3]-t[1])*i),this.transform=[o*i,l*i,h*i,d*i,c-o*i*m-h*i*f,u-l*i*m-d*i*f],this.width=p,this.height=g}get rawDims(){let t=this.viewBox;return He(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:e=this.scale,rotation:i=this.rotation,offsetX:s=this.offsetX,offsetY:r=this.offsetY,dontFlip:n=!1}={}){return new t({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:i,offsetX:s,offsetY:r,dontFlip:n})}convertToViewportPoint(t,e){let i=[t,e];return Ke.applyTransform(i,this.transform),i}convertToViewportRectangle(t){let e=[t[0],t[1]];Ke.applyTransform(e,this.transform);let i=[t[2],t[3]];return Ke.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){let i=[t,e];return Ke.applyInverseTransform(i,this.transform),i}},ai=class t{static textContent(e){let i=[],s={items:i,styles:Object.create(null)};return function e(s){if(!s)return;let r=null,n=s.name;if("#text"===n)r=s.value;else{if(!t.shouldBuildText(n))return;s?.attributes?.textContent?r=s.attributes.textContent:s.value&&(r=s.value)}if(null!==r&&i.push({str:r}),s.children)for(let t of s.children)e(t)}(e),s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}},oi=class{static setupStorage(t,e,i,s,r){let n=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==n.value&&(t.textContent=n.value),"print"===r)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(n.value===i.attributes.xfaOn?t.setAttribute("checked",!0):n.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===r)break;t.addEventListener("change",t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==n.value&&t.setAttribute("value",n.value),"print"===r)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})})}break;case"select":if(null!==n.value){t.setAttribute("value",n.value);for(let t of i.children)t.attributes.value===n.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{let i=t.target.options,r=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:r})})}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:r}){let{attributes:n}=e,a=t instanceof HTMLAnchorElement;"radio"===n.type&&(n.name=`${n.name}-${s}`);for(let[e,i]of Object.entries(n))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&r.addLinkAttributes(t,n.href,n.newWindow),i&&n.dataId&&this.setupStorage(t,n.dataId,e,i)}static render(t){let e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,r=t.intent||"display",n=document.createElement(s.name);s.attributes&&this.setAttributes({html:n,element:s,intent:r,linkService:i});let a="richText"!==r,o=t.div;if(o.append(n),t.viewport){let e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");let l=[];if(0===s.children.length){if(s.value){let t=document.createTextNode(s.value);n.append(t),a&&ai.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}let h=[[s,-1,n]];for(;h.length>0;){let[t,s,n]=h.at(-1);if(s+1===t.children.length){h.pop();continue}let o=t.children[++h.at(-1)[1]];if(null===o)continue;let{name:d}=o;if("#text"===d){let t=document.createTextNode(o.value);l.push(t),n.append(t);continue}let c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(n.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:r,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){let t=document.createTextNode(o.value);a&&ai.shouldBuildText(d)&&l.push(t),c.append(t)}}for(let t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){let e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}static getPageViewport(t,{scale:e=1,rotation:i=0}){let{width:s,height:r}=t.attributes.style;return new ni({viewBox:[0,0,parseInt(s,10),parseInt(r,10)],userUnit:1,scale:e,rotation:i})}},li=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function hi(t,e="text"){if(fi(t,document.baseURI)){let i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"blob":return i.blob();case"bytes":return i.bytes();case"json":return i.json()}return i.text()}return new Promise((i,s)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="bytes"===e?"arraybuffer":e,r.onreadystatechange=()=>{if(r.readyState===XMLHttpRequest.DONE){if(200===r.status||0===r.status){switch(e){case"bytes":return void i(new Uint8Array(r.response));case"blob":case"json":return void i(r.response)}return void i(r.responseText)}s(new Error(r.statusText))}},r.send(null)})}var di=class extends je{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}};function ci(t){let e=t.length,i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function ui(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function pi(t){return[t]=t.split(/[#?]/,1),Ue(t)}function gi(t,e="document.pdf"){if("string"!=typeof t)return e;if(ci(t))return Le('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;let i=(t=>{try{return new URL(t)}catch{}try{return new URL(decodeURIComponent(t))}catch{}try{return new URL(t,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{}return null})(t);if(!i)return e;let s=t=>{try{let e=decodeURIComponent(t);return e.includes("/")&&(e=Ue(e),4===e.length&&r.test(e))?t:e}catch{return t}},r=/\.pdf$/i,n=Ue(i.pathname);if(r.test(n))return s(n);if(i.searchParams.size>0){let t=t=>[...t].findLast(t=>r.test(t)),e=t(i.searchParams.values())??t(i.searchParams.keys());if(e)return s(e)}if(i.hash){let t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return s(t[0])}return e}var mi=class{#t=new Map;times=[];time(t){this.#t.has(t)&&Le(`Timer is already running for ${t}`),this.#t.set(t,Date.now())}timeEnd(t){this.#t.has(t)||Le(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.#t.get(t),end:Date.now()}),this.#t.delete(t)}toString(){let t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).join("")}};function fi(t,e){let i=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(i?.protocol??"")}function bi(t){t.preventDefault()}function vi(t){t.preventDefault(),t.stopPropagation()}var yi=class{static#t;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");let e=this.#t.exec(t);if(!e)return null;let i=parseInt(e[1],10),s=parseInt(e[2],10);s=s>=1&&s<=12?s-1:0;let r=parseInt(e[3],10);r=r>=1&&r<=31?r:1;let n=parseInt(e[4],10);n=n>=0&&n<=23?n:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;let l=e[7]||"Z",h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(n+=h,a+=d):"+"===l&&(n-=h,a-=d),new Date(Date.UTC(i,s,r,n,a,o))}};function Ai(t){if(t.startsWith("#")){let e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){let[e,i,s]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,i,s,1]}if(t.startsWith("rgba(")){let e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}let e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function wi(t){let e=Ai(t);return e?e.slice(0,3):(Le(`Not a valid color format: "${t}"`),[0,0,0])}function xi(t){let{a:e,b:i,c:s,d:r,e:n,f:a}=t.getTransform();return[e,i,s,r,n,a]}function _i(t){let{a:e,b:i,c:s,d:r,e:n,f:a}=t.getTransform().invertSelf();return[e,i,s,r,n,a]}function Si(t,e,i=!1,s=!0){if(e instanceof ni){let{pageWidth:s,pageHeight:r}=e.rawDims,{style:n}=t,a=`round(down, var(--total-scale-factor) * ${s}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-y))`;i&&e.rotation%180!=0?(n.width=o,n.height=a):(n.width=a,n.height=o)}s&&t.setAttribute("data-main-rotation",e.rotation)}var Ci=class t{constructor(){let{pixelRatio:e}=t;this.sx=e,this.sy=e}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(e,i,s,r,n=-1){let a=1/0,o=1/0,l=1/0;(s=t.capPixels(s,n))>0&&(a=Math.sqrt(s/(e*i))),-1!==r&&(o=r/e,l=r/i);let h=Math.min(a,o,l);return(this.sx>h||this.sy>h)&&(this.sx=h,this.sy=h,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){let i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}},Ei=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"],ki=class{static get isDarkMode(){return He(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}},Ti=class{static get commentForegroundColor(){let t=document.createElement("span");t.classList.add("comment","sidebar");let{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);let{color:i}=window.getComputedStyle(t);return t.remove(),He(this,"commentForegroundColor",wi(i))}};function Mi(t,e){let i=255*(1-(e=ri(e??1,0,1)));return t.map(t=>Math.round(t*e+i))}function Pi(t,e){let i=t[0]/255,s=t[1]/255,r=t[2]/255,n=Math.max(i,s,r),a=Math.min(i,s,r),o=(n+a)/2;if(n===a)e[0]=e[1]=0;else{let t=n-a;switch(e[1]=o<.5?t/(n+a):t/(2-n-a),n){case i:e[0]=60*((s-r)/t+(s<r?6:0));break;case s:e[0]=60*((r-i)/t+2);break;case r:e[0]=60*((i-s)/t+4)}}e[2]=o}function Di(t,e){let i=t[0],s=t[1],r=t[2],n=(1-Math.abs(2*r-1))*s,a=n*(1-Math.abs(i/60%2-1)),o=r-n/2;switch(Math.floor(i/60)){case 0:e[0]=n+o,e[1]=a+o,e[2]=o;break;case 1:e[0]=a+o,e[1]=n+o,e[2]=o;break;case 2:e[0]=o,e[1]=n+o,e[2]=a+o;break;case 3:e[0]=o,e[1]=a+o,e[2]=n+o;break;case 4:e[0]=a+o,e[1]=o,e[2]=n+o;break;case 5:case 6:e[0]=n+o,e[1]=o,e[2]=a+o}}function Ii(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Fi(t,e,i){Di(t,i),i.map(Ii);let s=.2126*i[0]+.7152*i[1]+.0722*i[2];Di(e,i),i.map(Ii);let r=.2126*i[0]+.7152*i[1]+.0722*i[2];return s>r?(s+.05)/(r+.05):(r+.05)/(s+.05)}var Li=new Map;function Oi(t,e){let i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2],s=Li.get(i);if(s)return s;let r=new Float32Array(9),n=r.subarray(0,3),a=r.subarray(3,6);Pi(t,a);let o=r.subarray(6,9);Pi(e,o);let l=o[2]<.5,h=l?12:4.5;if(a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),Fi(a,o,n)<h){let t,e;l?(t=a[2],e=1):(t=0,e=a[2]);let i=.005;for(;e-t>i;){let i=a[2]=(t+e)/2;l===Fi(a,o,n)<h?t=i:e=i}a[2]=l?e:t}return Di(a,n),s=Ke.makeHexColor(Math.round(255*n[0]),Math.round(255*n[1]),Math.round(255*n[2])),Li.set(i,s),s}function Ri({html:t,dir:e,className:i},s){let r=document.createDocumentFragment();if("string"==typeof t){let i=document.createElement("p");i.dir=e||"auto";let s=t.split(/\r\n?|\n/);for(let t=0,e=s.length;t<e;++t){let r=s[t];i.append(document.createTextNode(r)),t<e-1&&i.append(document.createElement("br"))}r.append(i)}else oi.render({xfaHtml:t,div:r,intent:"richText"});r.firstElementChild.classList.add("richText",i),s.append(r)}function Ni(t){let e=new Path2D;if(!t)return e;for(let i=0,s=t.length;i<s;)switch(t[i++]){case Ce:e.moveTo(t[i++],t[i++]);break;case Ee:e.lineTo(t[i++],t[i++]);break;case ke:e.bezierCurveTo(t[i++],t[i++],t[i++],t[i++],t[i++],t[i++]);break;case Te:e.quadraticCurveTo(t[i++],t[i++],t[i++],t[i++]);break;case Me:e.closePath();break;default:Le(`Unrecognized drawing path operator: ${t[i-1]}`)}return e}var Bi=class t{#t=null;#e=null;#i;#s=null;#r=null;#n=null;#a=null;#o=null;static#l=null;constructor(e){this.#i=e,t.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){let e=this.#t=document.createElement("div");e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");let i=this.#i._uiManager._signal;i instanceof AbortSignal&&!i.aborted&&(e.addEventListener("contextmenu",bi,{signal:i}),e.addEventListener("pointerdown",t.#h,{signal:i}));let s=this.#s=document.createElement("div");s.className="buttons",e.append(s);let r=this.#i.toolbarPosition;if(r){let{style:t}=e,i="ltr"===this.#i._uiManager.direction?1-r[0]:r[0];t.insetInlineEnd=100*i+"%",t.top=`calc(${100*r[1]}% + var(--editor-toolbar-vert-offset))`}return e}get div(){return this.#t}static#h(t){t.stopPropagation()}#d(t){this.#i._focusEventsAllowed=!1,vi(t)}#c(t){this.#i._focusEventsAllowed=!0,vi(t)}#u(t){let e=this.#i._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#d.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",bi,{signal:e}),!0)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown(),this.#n?.shown()}addDeleteButton(){let{editorType:e,_uiManager:i}=this.#i,s=document.createElement("button");s.classList.add("basic","deleteButton"),s.tabIndex=0,s.setAttribute("data-l10n-id",t.#l[e]),this.#u(s)&&s.addEventListener("click",t=>{i.delete()},{signal:i._signal}),this.#s.append(s)}get#p(){let t=document.createElement("div");return t.className="divider",t}async addAltText(t){let e=await t.render();this.#u(e),this.#s.append(e,this.#p),this.#r=t}addComment(t,e=null){if(this.#n)return;let i=t.renderForToolbar();if(!i)return;this.#u(i);let s=this.#a=this.#p;e?(this.#s.insertBefore(i,e),this.#s.insertBefore(s,e)):this.#s.append(i,s),this.#n=t,t.toolbar=this}addColorPicker(t){if(this.#e)return;this.#e=t;let e=t.renderButton();this.#u(e),this.#s.append(e,this.#p)}async addEditSignatureButton(t){let e=this.#o=await t.renderEditButton(this.#i);this.#u(e),this.#s.append(e,this.#p)}removeButton(t){"comment"===t&&(this.#n?.removeToolbarCommentButton(),this.#n=null,this.#a?.remove(),this.#a=null)}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;let s=this.#s.querySelector(i);s&&"comment"===t&&this.addComment(e,s)}updateEditSignatureButton(t){this.#o&&(this.#o.title=t)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}},Ui=class{#t=null;#e=null;#i;constructor(t){this.#i=t}#s(){let t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");let e=this.#i._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",bi,{signal:e});let i=this.#t=document.createElement("div");return i.className="buttons",t.append(i),this.#i.hasCommentManager()&&this.#n("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#i.commentSelection("floating_button")}),this.#n("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#i.highlightSelection("floating_button")}),t}#r(t,e){let i=0,s=0;for(let r of t){let t=r.y+r.height;if(t<i)continue;let n=r.x+(e?r.width:0);t>i?(s=n,i=t):e?n>s&&(s=n):n<s&&(s=n)}return[e?1-s:s,i]}show(t,e,i){let[s,r]=this.#r(e,i),{style:n}=this.#e||=this.#s();t.append(this.#e),n.insetInlineEnd=100*s+"%",n.top=`calc(${100*r}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(t,e,i,s){let r=document.createElement("button");r.classList.add("basic",t),r.tabIndex=0,r.setAttribute("data-l10n-id",e);let n=document.createElement("span");r.append(n),n.className="visuallyHidden",n.setAttribute("data-l10n-id",i);let a=this.#i._signal;a instanceof AbortSignal&&!a.aborted&&(r.addEventListener("contextmenu",bi,{signal:a}),r.addEventListener("click",s,{signal:a})),this.#t.append(r)}},Hi=Object.freeze({internal:"a0babde2-53ef-4493-91fe-62dfc3177bcf"});function ji(t,e,i){for(let s of i)e.addEventListener(s,t[s].bind(t))}var $i=class t{static#t=NaN;static#e=null;static#i=NaN;static#s=null;static initializeAndAddPointerId(e){(t.#e||=new Set).add(e)}static setPointer(e,i){t.#t||=i,t.#s??=e}static setTimeStamp(e){t.#i=e}static isSamePointerId(e){return t.#t===e}static isSamePointerIdOrRemove(e){return t.#t===e||(t.#e?.delete(e),!1)}static isSamePointerType(e){return t.#s===e}static isInitializedAndDifferentPointerType(e){return null!==t.#s&&!t.isSamePointerType(e)}static isSameTimeStamp(e){return t.#i===e}static isUsingMultiplePointers(){return t.#e?.size>=1}static clearPointerType(){t.#s=null}static clearPointerIds(){t.#t=NaN,t.#e=null}static clearTimeStamp(){t.#i=NaN}},Gi=class{#t=0;get id(){return`${ae}${this.#t++}`}},zi=class t{#t=ti();#e=0;#i=null;static get _isSVGFittingCanvas(){let t=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${qt}"><rect width="1" height="1" style="fill:red;"/></svg>`,e=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;return i.src=t,He(this,"_isSVGFittingCanvas",i.decode().then(()=>(e.drawImage(i,0,0,1,1,0,0,1,3),0===new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0])))}async#s(e,i){this.#i||=new Map;let s=this.#i.get(e);if(null===s)return null;if(s?.bitmap)return s.refCounter+=1,s;try{let e;if(s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1},"string"==typeof i?(s.url=i,e=await hi(i,"blob")):i instanceof File?e=s.file=i:i instanceof Blob&&(e=i),"image/svg+xml"===e.type){let i=t._isSVGFittingCanvas,r=new FileReader,n=new Image,a=new Promise((t,e)=>{n.onload=()=>{s.bitmap=n,s.isSvg=!0,t()},r.onload=async()=>{let t=s.svgUrl=r.result;n.src=await i?`${t}#svgView(preserveAspectRatio(none))`:t},n.onerror=r.onerror=e});r.readAsDataURL(e),await a}else s.bitmap=await createImageBitmap(e);s.refCounter=1}catch(t){Le(t),s=null}return this.#i.set(e,s),s&&this.#i.set(s.id,s),s}async getFromFile(t){let{lastModified:e,name:i,size:s,type:r}=t;return this.#s(`${e}_${i}_${s}_${r}`,t)}async getFromUrl(t){return this.#s(t,t)}async getFromBlob(t,e){let i=await e;return this.#s(t,i)}async getFromId(t){this.#i||=new Map;let e=this.#i.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){let{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#i||=new Map;let i=this.#i.get(t);if(i?.bitmap)return i.refCounter+=1,i;let s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#i.set(t,i),this.#i.set(i.id,i),i}getSvgUrl(t){let e=this.#i.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#i||=new Map;let e=this.#i.get(t);if(!e||(e.refCounter-=1,0!==e.refCounter))return;let{bitmap:i}=e;if(!e.url&&!e.file){let t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}},Vi=class{#t=[];#e=!1;#i;#s=-1;constructor(t=128){this.#i=t}add({cmd:t,undo:e,post:i,mustExec:s,type:r=NaN,overwriteIfSameType:n=!1,keepUndo:a=!1}){if(s&&t(),this.#e)return;let o={cmd:t,undo:e,post:i,type:r};if(-1===this.#s)return this.#t.length>0&&(this.#t.length=0),this.#s=0,void this.#t.push(o);if(n&&this.#t[this.#s].type===r)return a&&(o.undo=this.#t[this.#s].undo),void(this.#t[this.#s]=o);let l=this.#s+1;l===this.#i?this.#t.splice(0,1):(this.#s=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(o)}undo(){if(-1===this.#s)return;this.#e=!0;let{undo:t,post:e}=this.#t[this.#s];t(),e?.(),this.#e=!1,this.#s-=1}redo(){if(this.#s<this.#t.length-1){this.#s+=1,this.#e=!0;let{cmd:t,post:e}=this.#t[this.#s];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return-1!==this.#s}hasSomethingToRedo(){return this.#s<this.#t.length-1}cleanType(t){if(-1!==this.#s){for(let e=this.#s;e>=0;e--)if(this.#t[e].type!==t)return this.#t.splice(e+1,this.#s-e),void(this.#s=e);this.#t.length=0,this.#s=-1}}destroy(){this.#t=null}},Wi=class{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:e}=qe.platform;for(let[i,s,r={}]of t)for(let t of i){let i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:s,options:r}),this.allKeys.add(t.split("+").at(-1))):!e&&!i&&(this.callbacks.set(t,{callback:s,options:r}),this.allKeys.add(t.split("+").at(-1)))}}#t(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);let e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;let i=this.callbacks.get(this.#t(e));if(!i)return;let{callback:s,options:{bubbles:r=!1,args:n=[],checker:a=null}}=i;a&&!a(t,e)||(s.bind(t,...n,e)(),r||vi(e))}},Xi=class t{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let t=new Map([["CanvasText",null],["Canvas",null]]);return function(t){let e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(let i of t.keys()){e.style.color=i;let s=window.getComputedStyle(e).color;t.set(i,wi(s))}e.remove()}(t),He(this,"_colors",t)}convert(e){let i=wi(e);if(!window.matchMedia("(forced-colors: active)").matches)return i;for(let[e,s]of this._colors)if(s.every((t,e)=>t===i[e]))return t._colorsMapping.get(e);return i}getHexCode(t){let e=this._colors.get(t);return e?Ke.makeHexColor(...e):t}},Yi=class t{#t=new AbortController;#e=null;#i=null;#s=new Map;#r=new Map;#n=null;#a=null;#o=null;#l=null;#h=new Vi;#d=null;#c=null;#u=null;#p=0;#g=new Set;#m=null;#f=null;#b=new Set;_editorUndoBar=null;#v=!1;#y=!1;#A=!1;#w=null;#x=null;#_=null;#S=null;#C=!1;#E=null;#k=new Gi;#T=!1;#M=!1;#P=!1;#D=null;#I=null;#F=null;#L=null;#O=null;#R=oe.NONE;#N=new Set;#B=null;#U=null;#H=null;#j=null;#$=null;#G={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#z=[0,0];#V=null;#W=null;#X=null;#Y=null;#q=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let e=t.prototype,i=t=>t.#W.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),s=(t,{target:e})=>{if(e instanceof HTMLInputElement){let{type:t}=e;return"text"!==t&&"number"!==t}return!0},r=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return He(this,"_keyboardManager",new Wi([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],e.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.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"],e.delete,{checker:s}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#W.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#W.contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-r,0],checker:i}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-n,0],checker:i}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[r,0],checker:i}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[n,0],checker:i}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-r],checker:i}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-n],checker:i}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,r],checker:i}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,n],checker:i}]]))}constructor(t,e,i,s,r,n,a,o,l,h,d,c,u,p,g,m){let f=this._signal=this.#t.signal;this.#W=t,this.#X=e,this.#Y=i,this.#a=s,this.#d=r,this.#U=n,this.#$=o,this._eventBus=a;let b={signal:f,...Hi};a.on("editingaction",this.onEditingAction.bind(this),b),a.on("pagechanging",this.onPageChanging.bind(this),b),a.on("scalechanging",this.onScaleChanging.bind(this),b),a.on("rotationchanging",this.onRotationChanging.bind(this),b),a.on("setpreference",this.onSetPreference.bind(this),b),a.on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),b),window.addEventListener("pointerdown",()=>{this.#M=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#M=!1},{capture:!0,signal:f}),window.addEventListener("beforeunload",this.#K.bind(this),{capture:!0,signal:f}),this.#Q(),this.#J(),this.#Z(),this.#o=o.annotationStorage,this.#w=o.filterFactory,this.#H=l,this.#S=h||null,this.#v=d,this.#y=c,this.#A=u,this.#O=p||null,this.viewParameters={realScale:li.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,r?.setSidebarUiManager(this)}destroy(){this.#q?.resolve(),this.#q=null,this.#t?.abort(),this.#t=null,this._signal=null;for(let t of this.#r.values())t.destroy();this.#r.clear(),this.#s.clear(),this.#b.clear(),this.#L?.clear(),this.#e=null,this.#N.clear(),this.#h.destroy(),this.#a?.destroy(),this.#d?.destroy(),this.#U?.destroy(),this.#E?.hide(),this.#E=null,this.#F?.destroy(),this.#F=null,this.#i=null,this.#x&&(clearTimeout(this.#x),this.#x=null),this.#V&&(clearTimeout(this.#V),this.#V=null),this._editorUndoBar?.destroy(),this.#$=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#O}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#A}get hcmFilter(){return He(this,"hcmFilter",this.#H?this.#w.addHCMFilter(this.#H.foreground,this.#H.background):"none")}get direction(){return He(this,"direction",getComputedStyle(this.#W).direction)}get _highlightColors(){return He(this,"_highlightColors",this.#S?new Map(this.#S.split(",").map(t=>(t=t.split("=").map(t=>t.trim()),t[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){let{_highlightColors:t}=this;if(!t)return He(this,"highlightColors",null);let e=new Map,i=!!this.#H;for(let[s,r]of t){let t=s.endsWith("_HCM");i&&t?e.set(s.replace("_HCM",""),r):!i&&!t&&e.set(s,r)}return He(this,"highlightColors",e)}get highlightColorNames(){return He(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;let e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#u=t}setMainHighlightColorPicker(t){this.#F=t}editAltText(t,e=!1){this.#a?.editAltText(this,t,e)}hasCommentManager(){return!!this.#d}editComment(t,e,i,s){this.#d?.showDialog(this,t,e,i,s)}selectComment(t,e){this.#r.get(t)?.getEditorByUID(e)?.toggleComment(!0,!0)}updateComment(t){this.#d?.updateComment(t.getData())}updatePopupColor(t){this.#d?.updatePopupColor(t)}removeComment(t){this.#d?.removeComments([t.uid])}deleteComment(t,e){let i=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,"comment"),this.toggleComment(null),t.comment=null},undo:i,mustExec:!0})}toggleComment(t,e,i=void 0){this.#d?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#d?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#d?.dialogElement||null}async waitForEditorsRendered(t){if(this.#r.has(t-1))return;let{resolve:e,promise:i}=Promise.withResolvers(),s=i=>{i.pageNumber===t&&(this._eventBus.off("editorsrendered",s),e())};this._eventBus.on("editorsrendered",s),await i}getSignature(t){this.#U?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#U}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){"enableNewAltTextWhenAddingImage"===t&&(this.#A=e)}onPageChanging({pageNumber:t}){this.#p=t-1}deletePage(t){for(let e of this.getEditors(t))e.remove();this.#r.delete(t),this.#p===t&&(this.#p=0)}focusMainContainer(){this.#W.focus()}findParent(t,e){for(let i of this.#r.values()){let{x:s,y:r,width:n,height:a}=i.div.getBoundingClientRect();if(t>=s&&t<=s+n&&e>=r&&e<=r+a)return i}return null}disableUserSelect(t=!1){this.#X.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*li.PDF_TO_CSS_UNITS;for(let t of this.#b)t.onScaleChanging();this.#u?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#tt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#et(t){let{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(let e of this.#r.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){let i=document.getSelection();if(!i||i.isCollapsed)return;let{anchorNode:s,anchorOffset:r,focusNode:n,focusOffset:a}=i,o=i.toString(),l=this.#tt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();let d=this.#et(l),c=this.#R===oe.NONE,u=()=>{let i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:r,focusNode:n,focusOffset:a,text:o});c&&this.showAllEditors("highlight",!0,!0),e&&i?.editComment()};c?this.switchToMode(oe.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#K(t){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#it(){let t=document.getSelection();if(!t||t.isCollapsed)return;let e=this.#tt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#E||=new Ui(this),this.#E.show(e,i,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#o)return null;let e=`${ae}${t}`,i=this.#o.getRawValue(e);return i&&this.#o.remove(e),i}addToAnnotationStorage(t){!t.isEmpty()&&this.#o&&!this.#o.has(t.id)&&this.#o.setValue(t.id,t)}a11yAlert(t,e=null){let i=this.#Y;i&&(i.setAttribute("data-l10n-id",t),e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args"))}#st(){let t=document.getSelection();if(!t||t.isCollapsed)return void(this.#B&&(this.#E?.hide(),this.#B=null,this.#rt({hasSelectedText:!1})));let{anchorNode:e}=t;if(e===this.#B)return;let i=this.#tt(t).closest(".textLayer");if(i){if(this.#E?.hide(),this.#B=e,this.#rt({hasSelectedText:!0}),(this.#R===oe.HIGHLIGHT||this.#R===oe.NONE)&&(this.#R===oe.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#C=this.isShiftKeyDown,!this.isShiftKeyDown)){let t=this.#R===oe.HIGHLIGHT?this.#et(i):null;if(t?.toggleDrawing(),this.#M){let e=new AbortController,i=this.combinedSignal(e),s=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#nt("main_toolbar"))};window.addEventListener("pointerup",s,{signal:i}),window.addEventListener("blur",s,{signal:i})}else t?.toggleDrawing(!0),this.#nt("main_toolbar")}}else this.#B&&(this.#E?.hide(),this.#B=null,this.#rt({hasSelectedText:!1}))}#nt(t=""){this.#R===oe.HIGHLIGHT?this.highlightSelection(t):this.#v&&this.#it()}#Q(){document.addEventListener("selectionchange",this.#st.bind(this),{signal:this._signal})}#at(){if(this.#_)return;this.#_=new AbortController;let t=this.combinedSignal(this.#_);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#ot(){this.#_?.abort(),this.#_=null}blur(){if(this.isShiftKeyDown=!1,this.#C&&(this.#C=!1,this.#nt("main_toolbar")),!this.hasSelection)return;let{activeElement:t}=document;for(let e of this.#N)if(e.div.contains(t)){this.#I=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#I)return;let[t,e]=this.#I;this.#I=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Z(){if(this.#D)return;this.#D=new AbortController;let t=this.combinedSignal(this.#D);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#lt(){this.#D?.abort(),this.#D=null}#ht(){if(this.#c)return;this.#c=new AbortController;let t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#dt(){this.#c?.abort(),this.#c=null}#J(){let t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Z(),this.setEditingState(!0)}removeEditListeners(){this.#lt(),this.setEditingState(!1)}dragOver(t){for(let{type:e}of t.dataTransfer.items)for(let i of this.#f)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(let e of t.dataTransfer.items)for(let i of this.#f)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;let e=[];for(let t of this.#N){let i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();let{clipboardData:e}=t;for(let t of e.items)for(let e of this.#f)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void Le(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();let s=this.currentLayer;try{let t=[];for(let e of i){let i=await s.deserialize(e);if(!i)return;t.push(i)}let e=()=>{for(let e of t)this.#ct(e);this.#ut(t)},r=()=>{for(let e of t)e.remove()};this.addCommands({cmd:e,undo:r,mustExec:!0})}catch(t){Le(`paste: "${t.message}".`)}}keydown(e){!this.isShiftKeyDown&&"Shift"===e.key&&(this.isShiftKeyDown=!0),this.#R!==oe.NONE&&!this.isEditorHandlingKeyboard&&t._keyboardManager.exec(this,e)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#C&&(this.#C=!1,this.#nt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(let i of this.getEditors(t))i.pageIndex=e;let i=this.#n.get(t);i&&(i.pageIndex=e,this.#r.set(e,i),this.#T?i.enable():i.disable())}startUpdatePages(){this.#n=new Map(this.#r),this.#r.clear()}endUpdatePages(){this.#n=null}clonePage(t,e){for(let i of this.getEditors(t)){let t=i.serialize(i.mode!==oe.HIGHLIGHT);t&&(t.pageIndex=e,t.id=this.getId(),t.isClone=!0,delete t.popupRef,this.#o.setValue(t.id,t))}}findClonesForPage(t){let e=[],{pageIndex:i}=t;for(let[s,r]of this.#o)r.pageIndex===i&&r.isClone&&(this.#o.remove(s),e.push(t.deserialize(r).then(e=>{e&&(e.isClone=!0,t.addOrRebuild(e))})));return Promise.all(e)}#rt(t){Object.entries(t).some(([t,e])=>this.#G[t]!==e)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#G,t)}),this.#R===oe.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#pt([[le.HIGHLIGHT_FREE,!0]]))}#pt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#at(),this.#ht(),this.#rt({isEditing:this.#R!==oe.NONE,isEmpty:this.#gt(),hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:this.#h.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#ot(),this.#dt(),this.#rt({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#f){this.#f=t;for(let t of this.#f)this.#pt(t.defaultPropertiesToUpdate)}}getId(){return this.#k.id}get currentLayer(){return this.#r.get(this.#p)}getLayer(t){return this.#r.get(t)}get currentPageIndex(){return this.#p}addLayer(t){this.#r.set(t.pageIndex,t),this.#T?t.enable():t.disable()}removeLayer(t){this.#r.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,s=!1,r=!1,n=!1){if(this.#R!==t&&(!this.#q||(await this.#q.promise,this.#q))){if(this.#q=Promise.withResolvers(),this.#u?.commitOrRemove(),this.#R===oe.POPUP&&this.#d?.hideSidebar(),this.#d?.destroyPopup(),this.#R=t,t===oe.NONE){this.setEditingState(!1),this.#mt();for(let t of this.#s.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#q.resolve()}for(let t of this.#s.values())t.addStandaloneCommentButton();t===oe.SIGNATURE&&await(this.#U?.loadSignatures()),i&&$i.clearPointerType(),this.setEditingState(!0),await this.#ft(),this.unselectAll();for(let e of this.#r.values())e.updateMode(t);if(t===oe.POPUP){this.#i||=await this.#$.getAnnotationsByType(new Set(this.#f.map(t=>t._editorType)));let t=new Set,e=[];for(let i of this.#s.values()){let{annotationElementId:s,hasComment:r,deleted:n}=i;s&&t.add(s),r&&!n&&e.push(i.getData())}for(let i of this.#i){let{id:s,popupRef:r,contentsObj:n}=i;r&&n?.str&&!t.has(s)&&!this.#g.has(s)&&e.push(i)}this.#d?.showSidebar(e)}if(!e)return s&&this.addNewEditorFromKeyboard(),void this.#q.resolve();for(let t of this.#s.values())t.uid===e?(this.setSelected(t),n?t.editComment():r?t.enterInEditMode():t.focus()):t.unselect();this.#q.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#R&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#f){switch(t){case le.CREATE:return void this.currentLayer.addNewEditor(e);case le.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#j||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(let i of this.#N)i.updateParams(t,e);else for(let i of this.#f)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(let i of this.#s.values())i.editorType===t&&i.show(e);(this.#j?.get(le.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#pt([[le.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#P!==t){this.#P=t;for(let e of this.#r.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ft(){if(!this.#T){this.#T=!0;let t=[];for(let e of this.#r.values())t.push(e.enable());await Promise.all(t);for(let t of this.#s.values())t.enable()}}#mt(){if(this.unselectAll(),this.#T){this.#T=!1;for(let t of this.#r.values())t.disable();for(let t of this.#s.values())t.disable()}}*getEditors(t){for(let e of this.#s.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#x&&clearTimeout(this.#x),this.#x=setTimeout(()=>{this.focusMainContainer(),this.#x=null},0)),this.#s.delete(t.id),t.annotationElementId&&this.#L?.delete(t.annotationElementId),this.unselect(t),(!t.annotationElementId||!this.#g.has(t.annotationElementId))&&this.#o?.remove(t.id)}addDeletedAnnotationElement(t){this.#g.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#g.has(t)}removeDeletedAnnotationElement(t){this.#g.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#ct(t){let e=this.#r.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#pt(t.propertiesToUpdate))}get#bt(){let t=null;for(t of this.#N);return t}updateUI(t){this.#bt===t&&this.#pt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#pt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#N.has(t))return this.#N.delete(t),t.unselect(),void this.#rt({hasSelectedEditor:this.hasSelection});this.#N.add(t),t.select(),this.#pt(t.propertiesToUpdate),this.#rt({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#u?.commitOrRemove();for(let e of this.#N)e!==t&&e.unselect();this.#d?.destroyPopup(),this.#N.clear(),this.#N.add(t),t.select(),this.#pt(t.propertiesToUpdate),this.#rt({hasSelectedEditor:!0})}isSelected(t){return this.#N.has(t)}get firstSelectedEditor(){return this.#N.values().next().value}unselect(t){t.unselect(),this.#N.delete(t),this.#rt({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#N.size}get isEnterHandled(){return 1===this.#N.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#h.undo(),this.#rt({hasSomethingToUndo:this.#h.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#gt()}),this._editorUndoBar?.hide()}redo(){this.#h.redo(),this.#rt({hasSomethingToUndo:!0,hasSomethingToRedo:this.#h.hasSomethingToRedo(),isEmpty:this.#gt()})}addCommands(t){this.#h.add(t),this.#rt({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#gt()})}cleanUndoStack(t){this.#h.cleanType(t)}#gt(){if(0===this.#s.size)return!0;if(1===this.#s.size)for(let t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();let t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;let e=t?[t]:[...this.#N],i=()=>{for(let t of e)this.#ct(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(let t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#ut(t){for(let t of this.#N)t.unselect();this.#N.clear();for(let e of t)e.isEmpty()||(this.#N.add(e),e.select());this.#rt({hasSelectedEditor:this.hasSelection})}selectAll(){for(let t of this.#N)t.commit();this.#ut(this.#s.values())}unselectAll(){if((!this.#e||(this.#e.commitOrRemove(),this.#R===oe.NONE))&&!this.#u?.commitOrRemove()&&(this.#d?.destroyPopup(),this.hasSelection)){for(let t of this.#N)t.unselect();this.#N.clear(),this.#rt({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#z[0]+=t,this.#z[1]+=e;let[s,r]=this.#z,n=[...this.#N];this.#V&&clearTimeout(this.#V),this.#V=setTimeout(()=>{this.#V=null,this.#z[0]=this.#z[1]=0,this.addCommands({cmd:()=>{for(let t of n)this.#s.has(t.id)&&(t.translateInPage(s,r),t.translationDone())},undo:()=>{for(let t of n)this.#s.has(t.id)&&(t.translateInPage(-s,-r),t.translationDone())},mustExec:!1})},1e3);for(let i of n)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#m=new Map;for(let t of this.#N)this.#m.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#m)return!1;this.disableUserSelect(!1);let t=this.#m;this.#m=null;let e=!1;for(let[{x:i,y:s,pageIndex:r},n]of t)n.newX=i,n.newY=s,n.newPageIndex=r,e||=i!==n.savedX||s!==n.savedY||r!==n.savedPageIndex;if(!e)return!1;let i=(t,e,i,s)=>{if(this.#s.has(t.id)){let r=this.#r.get(s);r?t._setParentAndPosition(r,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(let[e,{newX:s,newY:r,newPageIndex:n}]of t)i(e,s,r,n)},undo:()=>{for(let[e,{savedX:s,savedY:r,savedPageIndex:n}]of t)i(e,s,r,n)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#m)for(let i of this.#m.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){let 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.#N.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#R}isEditingMode(){return this.#R!==oe.NONE}get imageManager(){return He(this,"imageManager",new zi)}getSelectionBoxes(t){if(!t)return null;let e=document.getSelection();for(let i=0,s=e.rangeCount;i<s;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;let i,{x:s,y:r,width:n,height:a}=t.getBoundingClientRect();switch(t.getAttribute("data-main-rotation")){case"90":i=(t,e,i,o)=>({x:(e-r)/a,y:1-(t+i-s)/n,width:o/a,height:i/n});break;case"180":i=(t,e,i,o)=>({x:1-(t+i-s)/n,y:1-(e+o-r)/a,width:i/n,height:o/a});break;case"270":i=(t,e,i,o)=>({x:1-(e+o-r)/a,y:(t-s)/n,width:o/a,height:i/n});break;default:i=(t,e,i,o)=>({x:(t-s)/n,y:(e-r)/a,width:i/n,height:o/a})}let o=[];for(let t=0,s=e.rangeCount;t<s;t++){let s=e.getRangeAt(t);if(!s.collapsed)for(let{x:t,y:e,width:r,height:n}of s.getClientRects())0===r||0===n||o.push(i(t,e,r,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#l||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#l?.delete(t)}renderAnnotationElement(t){let e=this.#l?.get(t.data.id);if(!e)return;let i=this.#o.getRawValue(e);i&&(this.#R===oe.NONE&&!i.hasBeenModified||i.renderAnnotationElement(t))}setMissingCanvas(t,e,i){let s=this.#L?.get(t);s&&(s.setCanvas(e,i),this.#L.delete(t))}addMissingCanvas(t,e){(this.#L||=new Map).set(t,e)}},qi=class t{#t=null;#e=!1;#i=null;#s=null;#r=null;#n=null;#a=!1;#o=null;#l=null;#h=null;#d=null;#c=!1;static#u=null;static _l10n=null;constructor(e){this.#l=e,this.#c=e._uiManager.useNewAltTextFlow,t.#u||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(e){t._l10n??=e}async render(){let e=this.#i=document.createElement("button");e.className="altText",e.tabIndex="0";let i=this.#s=document.createElement("span");e.append(i),this.#c?(e.classList.add("new"),e.setAttribute("data-l10n-id",t.#u.missing),i.setAttribute("data-l10n-id",t.#u["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),i.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));let s=this.#l._uiManager._signal;e.addEventListener("contextmenu",bi,{signal:s}),e.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:s});let r=t=>{t.preventDefault(),this.#l._uiManager.editAltText(this.#l),this.#c&&this.#l._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#p}})};return e.addEventListener("click",r,{capture:!0,signal:s}),e.addEventListener("keydown",t=>{t.target===e&&"Enter"===t.key&&(this.#a=!0,r(t))},{signal:s}),await this.#g(),e}get#p(){return(this.#t?"added":null===this.#t&&this.guessedText&&"review")||"missing"}finish(){this.#i&&(this.#i.focus({focusVisible:this.#a}),this.#a=!1)}isEmpty(){return this.#c?null===this.#t:!this.#t&&!this.#e}hasData(){return this.#c?null!==this.#t||!!this.#h:this.isEmpty()}get guessedText(){return this.#h}async setGuessedText(e){null===this.#t&&(this.#h=e,this.#d=await t._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#c||this.#t)return this.#o?.remove(),void(this.#o=null);if(!this.#o){let t=this.#o=document.createElement("div");t.className="noAltTextBadge",this.#l.div.append(t)}this.#o.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#h===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#h,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:r=!1}){i&&(this.#h=i,this.#d=s),(this.#t!==t||this.#e!==e)&&(r||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#i&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#i.disabled=!t)}shown(){this.#l._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#p}})}destroy(){this.#i?.remove(),this.#i=null,this.#s=null,this.#r=null,this.#o?.remove(),this.#o=null}async#g(){let e=this.#i;if(!e)return;if(this.#c){if(e.classList.toggle("done",!!this.#t),e.setAttribute("data-l10n-id",t.#u[this.#p]),this.#s?.setAttribute("data-l10n-id",t.#u[`${this.#p}-label`]),!this.#t)return void this.#r?.remove()}else{if(!this.#t&&!this.#e)return e.classList.remove("done"),void this.#r?.remove();e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let i=this.#r;if(!i){this.#r=i=document.createElement("span"),i.className="tooltip",i.setAttribute("role","tooltip"),i.id=`alt-text-tooltip-${this.#l.id}`;let t=100,s=this.#l._uiManager._signal;s.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),e.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#l._reportTelemetry({action:"alt_text_tooltip"})},t)},{signal:s}),e.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:s})}this.#e?i.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(i.removeAttribute("data-l10n-id"),i.textContent=this.#t),i.parentNode||e.append(i),this.#l.getElementForAltText()?.setAttribute("aria-describedby",i.id)}},Ki=class{#t=null;#e=null;#i=!1;#s=null;#r=null;#n=null;#a=null;#o=null;#l=!1;#h=null;constructor(t){this.#s=t}renderForToolbar(){let t=this.#e=document.createElement("button");return t.className="comment",this.#d(t,!1)}renderForStandalone(){let t=this.#t=document.createElement("button");t.className="annotationCommentButton";let e=this.#s.commentButtonPosition;if(e){let{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#s._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;let s=this.#s.commentButtonColor;s&&(i.backgroundColor=s)}return this.#d(t,!0)}focusButton(){setTimeout(()=>{(this.#t??this.#e)?.focus()},0)}onUpdatedColor(){if(!this.#t)return;let t=this.#s.commentButtonColor;t&&(this.#t.style.backgroundColor=t),this.#s._uiManager.updatePopupColor(this.#s)}get commentButtonWidth(){return(this.#t?.getBoundingClientRect().width??0)/this.#s.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#h)return this.#h;if(!this.#t)return null;let{x:t,y:e,height:i}=this.#t.getBoundingClientRect(),{x:s,y:r,width:n,height:a}=this.#s.parent.boundingClientRect;return[(t-s)/n,(e+i-r)/a]}set commentPopupPositionInLayer(t){this.#h=t}hasDefaultPopupPosition(){return null===this.#h}removeStandaloneCommentButton(){this.#t?.remove(),this.#t=null}removeToolbarCommentButton(){this.#e?.remove(),this.#e=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#t&&(this.#t.classList.toggle("selected",t),this.#t.ariaExpanded=e)}#d(t,e){if(!this.#s._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#s._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));let i=this.#s._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",bi,{signal:i}),e&&(t.addEventListener("focusin",t=>{this.#s._focusEventsAllowed=!1,vi(t)},{capture:!0,signal:i}),t.addEventListener("focusout",t=>{this.#s._focusEventsAllowed=!0,vi(t)},{capture:!0,signal:i})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});let s=e=>{e.preventDefault(),t===this.#e?this.edit():this.#s.toggleComment(!0)};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#i=!0,s(e))},{signal:i}),t.addEventListener("pointerenter",()=>{this.#s.toggleComment(!1,!0)},{signal:i}),t.addEventListener("pointerleave",()=>{this.#s.toggleComment(!1,!1)},{signal:i}),t}edit(t){let e,i,s=this.commentPopupPositionInLayer;if(s)[e,i]=s;else{[e,i]=this.#s.commentButtonPosition;let{width:t,height:s,x:r,y:n}=this.#s;e=r+e*t,i=n+i*s}let r=this.#s.parent.boundingClientRect,{x:n,y:a,width:o,height:l}=r;this.#s._uiManager.editComment(this.#s,n+e*o,a+i*l,{...t,parentDimensions:r})}finish(){this.#e&&(this.#e.focus({focusVisible:this.#i}),this.#i=!1)}isDeleted(){return this.#l||""===this.#a}isEmpty(){return null===this.#a}hasBeenEdited(){return this.isDeleted()||this.#a!==this.#r}serialize(){return this.data}get data(){return{text:this.#a,richText:this.#n,date:this.#o,deleted:this.isDeleted()}}set data(t){if(t!==this.#a&&(this.#n=null),null===t)return this.#a="",void(this.#l=!0);this.#a=t,this.#o=new Date,this.#l=!1}restoreData({text:t,richText:e,date:i}){this.#a=t,this.#n=e,this.#o=i,this.#l=!1}setInitialText(t,e=null){this.#r=t,this.data=t,this.#o=null,this.#n=e}shown(){}destroy(){this.#e?.remove(),this.#e=null,this.#t?.remove(),this.#t=null,this.#a="",this.#n=null,this.#o=null,this.#s=null,this.#i=!1,this.#l=!1}},Qi=class t{#t;#e=!1;#i=null;#s;#r;#n;#a;#o=null;#l;#h=null;#d;#c=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:r=null,onPinchEnd:n=null,signal:a}){this.#t=t,this.#i=i,this.#s=e,this.#r=s,this.#n=r,this.#a=n,this.#d=new AbortController,this.#l=AbortSignal.any([a,this.#d.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#l})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Ci.pixelRatio}#u(t){if(this.#s?.())return;if(1===t.touches.length){if(this.#o)return;let t=this.#o=new AbortController,e=AbortSignal.any([this.#l,t.signal]),i=this.#t,s={capture:!0,signal:e,passive:!1},r=t=>{"touch"===t.pointerType&&(this.#o?.abort(),this.#o=null)};return i.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(vi(t),r(t))},s),i.addEventListener("pointerup",r,s),void i.addEventListener("pointercancel",r,s)}if(!this.#c){this.#c=new AbortController;let t=AbortSignal.any([this.#l,this.#c.signal]),e=this.#t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#p.bind(this),i);let s=this.#g.bind(this);e.addEventListener("touchend",s,i),e.addEventListener("touchcancel",s,i),i.capture=!0,e.addEventListener("pointerdown",vi,i),e.addEventListener("pointermove",vi,i),e.addEventListener("pointercancel",vi,i),e.addEventListener("pointerup",vi,i),this.#r?.()}if(vi(t),2!==t.touches.length||this.#i?.())return void(this.#h=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#h={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#p(e){if(!this.#h||2!==e.touches.length)return;vi(e);let[i,s]=e.touches;i.identifier>s.identifier&&([i,s]=[s,i]);let{screenX:r,screenY:n}=i,{screenX:a,screenY:o}=s,l=this.#h,{touch0X:h,touch0Y:d,touch1X:c,touch1Y:u}=l,p=c-h,g=u-d,m=a-r,f=o-n,b=Math.hypot(m,f)||1,v=Math.hypot(p,g)||1;if(!this.#e&&Math.abs(v-b)<=t.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(l.touch0X=r,l.touch0Y=n,l.touch1X=a,l.touch1Y=o,!this.#e)return void(this.#e=!0);let y=[(r+a)/2,(n+o)/2];this.#n?.(y,v,b)}#g(t){t.touches.length>=2||(this.#c&&(this.#c.abort(),this.#c=null,this.#a?.()),this.#h&&(vi(t),this.#h=null,this.#e=!1))}destroy(){this.#d?.abort(),this.#d=null,this.#o?.abort(),this.#o=null}},Ji=class t{#t=null;#e=null;#i=null;#s=null;#r=null;#n=!1;#a=null;#o="";#l=null;#h=null;#d=null;#c=null;#u=null;#p="";#g=!1;#m=null;#f=!1;#b=!1;#v=!1;#y=null;#A=0;#w=0;#x=null;#_=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#S=!1;#C=t._zIndex++;static _borderLineWidth=-1;static _colorManager=new Xi;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let e=t.prototype._resizeWithKeyboard,i=Yi.TRANSLATE_SMALL,s=Yi.TRANSLATE_BIG;return He(this,"_resizerKeyboardManager",new Wi([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-i,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[i,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-i]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,i]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,s]}],[["Escape","mac+Escape"],t.prototype._stopResizingWithKeyboard]]))}constructor(t){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,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;let{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:r,pageY:n}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[r,n];let[a,o]=this.parentDimensions;this.x=t.x/a,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return He(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){let e=new Zi({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(e,i){if(t._l10n??=e,t._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),t._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==t._borderLineWidth)return;let s=getComputedStyle(document.documentElement);t._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){Oe("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(t){this.#S=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[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.#C}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#z(),this.#c?.remove(),this.#c=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#g?this.#g=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){let[r,n]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/r,this.y=(e+s)/n,this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone)return void delete this.isClone;let[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s),this._onTranslated()}#E([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#E(this.parentDimensions,t,e)}translateInPage(t,e){this.#m||=[this.x,this.y,this.width,this.height],this.#E(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#m||=[this.x,this.y,this.width,this.height];let{div:i,parentDimensions:[s,r]}=this;if(this.x+=t/s,this.y+=e/r,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{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,[o,l]=this.getBaseTranslation();n+=o,a+=l;let{style:h}=i;h.left=`${(100*n).toFixed(2)}%`,h.top=`${(100*a).toFixed(2)}%`,this._onTranslating(n,a),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#m&&(this.#m[0]!==this.x||this.#m[1]!==this.y)}get _hasBeenResized(){return!!this.#m&&(this.#m[2]!==this.width||this.#m[3]!==this.height)}getBaseTranslation(){let[e,i]=this.parentDimensions,{_borderLineWidth:s}=t,r=s/e,n=s/i;switch(this.rotation){case 90:return[-r,n];case 180:return[r,n];case 270:return[r,-n];default:return[-r,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){let{div:{style:e},pageDimensions:[i,s]}=this,{x:r,y:n,width:a,height:o}=this;if(a*=i,o*=s,r*=i,n*=s,this._mustFixPosition)switch(t){case 0:r=ri(r,0,i-a),n=ri(n,0,s-o);break;case 90:r=ri(r,0,i-o),n=ri(n,a,s);break;case 180:r=ri(r,a,i),n=ri(n,o,s);break;case 270:r=ri(r,o,i),n=ri(n,0,s-a)}this.x=r/=i,this.y=n/=s;let[l,h]=this.getBaseTranslation();r+=l,n+=h,e.left=`${(100*r).toFixed(2)}%`,e.top=`${(100*n).toFixed(2)}%`,this.moveInDOM()}static#k(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(e,i){return t.#k(e,i,this.parentRotation)}pageTranslationToScreen(e,i){return t.#k(e,i,360-this.parentRotation)}#T(t){switch(t){case 90:{let[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{let[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(){let{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){let{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#M(){if(this.#l)return;this.#l=document.createElement("div"),this.#l.classList.add("resizers");let t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(let i of t){let t=document.createElement("div");this.#l.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#P.bind(this,i),{signal:e}),t.addEventListener("contextmenu",bi,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#l)}#P(t,e){e.preventDefault();let{isMac:i}=qe.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#i?.toggle(!1);let s=this._isDraggable;this._isDraggable=!1,this.#h=[e.screenX,e.screenY];let r=new AbortController,n=this._uiManager.combinedSignal(r);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#F.bind(this,t),{passive:!0,capture:!0,signal:n}),window.addEventListener("touchmove",vi,{passive:!1,signal:n}),window.addEventListener("contextmenu",bi,{signal:n}),this.#d={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;let l=()=>{r.abort(),this.parent.togglePointerEvents(!0),this.#i?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=a,this.div.style.cursor=o,this.#I()};window.addEventListener("pointerup",l,{signal:n}),window.addEventListener("blur",l,{signal:n})}#D(t,e,i,s){this.width=i,this.height=s,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#d)return;let{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#d;this.#d=null;let r=this.x,n=this.y,a=this.width,o=this.height;r===t&&n===e&&a===i&&o===s||this.addCommands({cmd:this.#D.bind(this,r,n,a,o),undo:this.#D.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#F(e,i){let s,r,[n,a]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=t.MIN_SIZE/n,u=t.MIN_SIZE/a,p=this.#T(this.rotation),g=(t,e)=>[p[0]*t+p[2]*e,p[1]*t+p[3]*e],m=this.#T(360-this.rotation),f=!1,b=!1;switch(e){case"topLeft":f=!0,s=(t,e)=>[0,0],r=(t,e)=>[t,e];break;case"topMiddle":s=(t,e)=>[t/2,0],r=(t,e)=>[t/2,e];break;case"topRight":f=!0,s=(t,e)=>[t,0],r=(t,e)=>[0,e];break;case"middleRight":b=!0,s=(t,e)=>[t,e/2],r=(t,e)=>[0,e/2];break;case"bottomRight":f=!0,s=(t,e)=>[t,e],r=(t,e)=>[0,0];break;case"bottomMiddle":s=(t,e)=>[t/2,e],r=(t,e)=>[t/2,0];break;case"bottomLeft":f=!0,s=(t,e)=>[0,e],r=(t,e)=>[t,0];break;case"middleLeft":b=!0,s=(t,e)=>[0,e/2],r=(t,e)=>[t,e/2]}let v,y,A=s(h,d),w=r(h,d),x=g(...w),_=t._round(o+x[0]),S=t._round(l+x[1]),C=1,E=1;if(i.fromKeyboard)({deltaX:v,deltaY:y}=i);else{let{screenX:t,screenY:e}=i,[s,r]=this.#h;[v,y]=this.screenToPageTranslation(t-s,e-r),this.#h[0]=t,this.#h[1]=e}if([v,y]=(k=v/n,T=y/a,[m[0]*k+m[2]*T,m[1]*k+m[3]*T]),f){let t=Math.hypot(h,d);C=E=Math.max(Math.min(Math.hypot(w[0]-A[0]-v,w[1]-A[1]-y)/t,1/h,1/d),c/h,u/d)}else b?C=ri(Math.abs(w[0]-A[0]-v),c,1)/h:E=ri(Math.abs(w[1]-A[1]-y),u,1)/d;var k,T;let M=t._round(h*C),P=t._round(d*E);x=g(...r(M,P));let D=_-x[0],I=S-x[1];this.#m||=[this.x,this.y,this.width,this.height],this.width=M,this.height=P,this.x=D,this.y=I,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#i?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#b)return this._editToolbar;this._editToolbar=new Bi(this),this.div.append(this._editToolbar.render());let{toolbarButtons:t}=this;if(t)for(let[e,i]of t)await this._editToolbar.addButton(e,i);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#i?.destroy()}addContainer(t){let e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#i||(qi.initialize(t._l10n),this.#i=new qi(this),this.#t&&(this.#i.data=this.#t,this.#t=null)),this.#i}get altTextData(){return this.#i?.data}set altTextData(t){this.#i&&(this.#i.data=t)}get guessedAltText(){return this.#i?.guessedText}async setGuessedAltText(t){await(this.#i?.setGuessedText(t))}serializeAltText(t){return this.#i?.serialize(t)}hasAltText(){return!!this.#i&&!this.#i.isEmpty()}hasAltTextData(){return this.#i?.hasData()??!1}focusCommentButton(){this.#s?.focusButton()}addCommentButton(){return this.canAddComment?this.#s||=new Ki(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#r)return void(this._uiManager.isEditingMode()&&this.#r.classList.remove("hidden"));this.hasComment&&(this.#r=this.#s.renderForStandalone(),this.div.append(this.#r))}}removeStandaloneCommentButton(){this.#s.removeStandaloneCommentButton(),this.#r=null}hideStandaloneCommentButton(){this.#r?.classList.add("hidden")}get comment(){if(!this.#s)return null;let{data:{richText:t,text:e,date:i,deleted:s}}=this.#s;return{text:e,richText:t,date:i,deleted:s,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#s||=new Ki(this),"object"==typeof t&&null!==t?this.#s.restoreData(t):this.#s.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:i}){if(!e||(this.#s||=new Ki(this),this.#s.setInitialText(t,i),!this.annotationElementId))return;let s=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);s&&this.updateFromAnnotationLayer(s)}get hasEditedComment(){return this.#s?.hasBeenEdited()}get hasDeletedComment(){return this.#s?.isDeleted()}get hasComment(){return!!this.#s&&!this.#s.isEmpty()&&!this.#s.isDeleted()}async editComment(t){this.#s||=new Ki(this),this.#s.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#s.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){let[,,,e]=t.rect,[i]=this.pageDimensions,[s]=this.pageTranslation,r=s+i+1,n=e-100,a=r+180;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[r,n,a,e]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#s.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#n?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#U();let[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);let[s,r]=this.getInitialTranslation();return this.translate(s,r),ji(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#_||=new Qi({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#L.bind(this),onPinching:this.#O.bind(this),onPinchEnd:this.#R.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#L(){this.#d={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#i?.toggle(!1),this.parent.togglePointerEvents(!1)}#O(e,i,s){let r=s/i*.7+1-.7;if(1===r)return;let n=this.#T(this.rotation),a=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[o,l]=this.parentDimensions,h=this.x,d=this.y,c=this.width,u=this.height,p=t.MIN_SIZE/o,g=t.MIN_SIZE/l;r=Math.max(Math.min(r,1/c,1/u),p/c,g/u);let m=t._round(c*r),f=t._round(u*r);if(m===c&&f===u)return;this.#m||=[h,d,c,u];let b=a(c/2,u/2),v=t._round(h+b[0]),y=t._round(d+b[1]),A=a(m/2,f/2);this.x=v-A[0],this.y=y-A[1],this.width=m,this.height=f,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#R(){this.#i?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){let{isMac:e}=qe.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#g=!0,this._isDraggable?this.#B(t):this.#N(t))}#N(t){let{isMac:e}=qe.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#B(t){let{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1,s=new AbortController,r=this._uiManager.combinedSignal(s),n={capture:!0,passive:!1,signal:r},a=t=>{s.abort(),this.#a=null,this.#g=!1,this._uiManager.endDragSession()||this.#N(t),i&&this._onStopDragging()};e&&(this.#A=t.clientX,this.#w=t.clientY,this.#a=t.pointerId,this.#o=t.pointerType,window.addEventListener("pointermove",t=>{i||(i=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:e,clientY:s,pointerId:r}=t;if(r!==this.#a)return void vi(t);let[n,a]=this.screenToPageTranslation(e-this.#A,s-this.#w);this.#A=e,this.#w=s,this._uiManager.dragSelectedEditors(n,a)},n),window.addEventListener("touchmove",vi,n),window.addEventListener("pointerdown",t=>{t.pointerType===this.#o&&(this.#_||t.isPrimary)&&a(t),vi(t)},n));let o=t=>{this.#a&&this.#a!==t.pointerId?vi(t):a(t)};window.addEventListener("pointerup",o,{signal:r}),window.addEventListener("blur",o,{signal:r})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){let s=this.parentScale,[r,n]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*r,c=this.y*n,u=this.width*r,p=this.height*n;switch(i){case 0:return[d+l+a,n-c-h-p+o,d+l+u+a,n-c-h+o];case 90:return[d+h+a,n-c+l+o,d+h+p+a,n-c+l+u+o];case 180:return[d-l-u+a,n-c+h+o,d-l+a,n-c+h+p+o];case 270:return[d-h-p+a,n-c-l-u+o,d-h+a,n-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){let[i,s,r,n]=t,a=r-i,o=n-s;switch(this.rotation){case 0:return[i,e-n,a,o];case 90:return[i,e-s,o,a];case 180:return[r,e-s,a,o];case 270:return[r,e-n,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&t._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#s?.onUpdatedColor()}getData(){let{comment:{text:t,color:e,date:i,opacity:s,deleted:r,richText:n},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:n,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!r,color:e,opacity:s}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#b=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#b=!1,!0)}isInEditMode(){return this.#b}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:r,innerWidth:n}=window;return e<n&&s>0&&t<r&&i>0}#U(){if(this.#u||!this.div)return;this.#u=new AbortController;let t=this._uiManager.combinedSignal(this.#u);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#U()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){let s=new this.prototype.constructor({parent:e,id:i.getId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});s.rotation=t.rotation,s.#t=t.accessibilityData,s._isCopy=t.isCopy||!1;let[r,n]=s.pageDimensions,[a,o,l,h]=s.getRectInCurrentCoords(t.rect,n);return s.x=a/r,s.y=o/n,s.width=l/r,s.height=h/n,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#u?.abort(),this.#u=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#y&&(clearTimeout(this.#y),this.#y=null),this.#z(),this.removeEditToolbar(),this.#x){for(let t of this.#x.values())clearTimeout(t);this.#x=null}this.parent=null,this.#_?.destroy(),this.#_=null,this.#c?.remove(),this.#c=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#M(),this.#l.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[e,i]}=this,[s,r,n,a]=this.getPDFRect();return[t._round(s+(n-s)*e),t._round(r+(a-r)*(1-i))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#s.commentPopupPositionInLayer}set commentPopupPosition(t){this.#s.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#s.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#s.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#s?.setCommentButtonStates(t)}keydown(e){if(!this.isResizable||e.target!==this.div||"Enter"!==e.key)return;this._uiManager.setSelected(this),this.#d={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let i=this.#l.children;if(!this.#e){this.#e=Array.from(i);let e=this.#H.bind(this),s=this.#j.bind(this),r=this._uiManager._signal;for(let i of this.#e){let n=i.getAttribute("data-resizer-name");i.setAttribute("role","spinbutton"),i.addEventListener("keydown",e,{signal:r}),i.addEventListener("blur",s,{signal:r}),i.addEventListener("focus",this.#$.bind(this,n),{signal:r}),i.setAttribute("data-l10n-id",t._l10nResizer[n])}}let s=this.#e[0],r=0;for(let t of i){if(t===s)break;r++}let n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==r){if(n<r)for(let t=0;t<r-n;t++)this.#l.append(this.#l.firstElementChild);else if(n>r)for(let t=0;t<n-r;t++)this.#l.firstElementChild.before(this.#l.lastElementChild);let e=0;for(let s of i){let i=this.#e[e++].getAttribute("data-resizer-name");s.setAttribute("data-l10n-id",t._l10nResizer[i])}}this.#G(0),this.#v=!0,this.#l.firstElementChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}#H(e){t._resizerKeyboardManager.exec(this,e)}#j(t){this.#v&&t.relatedTarget?.parentNode!==this.#l&&this.#z()}#$(t){this.#p=this.#v?t:""}#G(t){if(this.#e)for(let e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#v&&this.#F(this.#p,{deltaX:t,deltaY:e,fromKeyboard:!0})}#z(){this.#v=!1,this.#G(-1),this.#I()}_stopResizingWithKeyboard(){this.#z(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#i?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#l?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#i?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#f}set isEditing(t){this.#f=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,i=!1){if(i){this.#x||=new Map;let{action:i}=e,s=this.#x.get(i);return s&&clearTimeout(s),s=setTimeout(()=>{this._reportTelemetry(e),this.#x.delete(i),0===this.#x.size&&(this.#x=null)},t._telemetryTimeout),void this.#x.set(i,s)}e.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#n=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#n=!0}updateFakeAnnotationElement(t){if(this.#c||this.deleted)return this.deleted?(this.#c.remove(),void(this.#c=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#c.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#c=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){let 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){let{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}},Zi=class extends Ji{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},ts=3285377520,es=4294901760,is=65535,ss=class{constructor(t){this.h1=t?4294967295&t:ts,this.h2=t?4294967295&t:ts}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,r=t.length;s<r;s++){let r=t.charCodeAt(s);r<=255?e[i++]=r:(e[i++]=r>>>8,e[i++]=255&r)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}let s=i>>2,r=i-4*s,n=new Uint32Array(e.buffer,0,s),a=0,o=0,l=this.h1,h=this.h2,d=3432918353,c=461845907,u=d&is,p=c&is;for(let t=0;t<s;t++)1&t?(a=n[t],a=a*d&es|a*u&is,a=a<<15|a>>>17,a=a*c&es|a*p&is,l^=a,l=l<<13|l>>>19,l=5*l+3864292196):(o=n[t],o=o*d&es|o*u&is,o=o<<15|o>>>17,o=o*c&es|o*p&is,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(a=0,r){case 3:a^=e[4*s+2]<<16;case 2:a^=e[4*s+1]<<8;case 1:a^=e[4*s],a=a*d&es|a*u&is,a=a<<15|a>>>17,a=a*c&es|a*p&is,1&s?l^=a:h^=a}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&es|36045*t&is,e=4283543511*e&es|(2950163797*(e<<16|t>>>16)&es)>>>16,t^=e>>>1,t=444984403*t&es|60499*t&is,e=3301882366*e&es|(3120437893*(e<<16|t>>>16)&es)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}},rs=Object.freeze({map:null,hash:"",transfer:void 0}),ns=class{#t=!1;#e=null;#i=null;#s=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){let i=this.#s.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#s.get(t)}remove(t){let e=this.#s.get(t);void 0!==e&&(e instanceof Ji&&this.#i.delete(e.annotationElementId),this.#s.delete(t),0===this.#s.size&&this.resetModified(),!this.#s.values().some(t=>t instanceof Ji)&&this.onAnnotationEditor?.(null))}setValue(t,e){let i=this.#s.get(t),s=!1;if(void 0!==i)for(let[t,r]of Object.entries(e))i[t]!==r&&(s=!0,i[t]=r);else s=!0,this.#s.set(t,e);s&&this.#r(),e instanceof Ji&&((this.#i||=new Map).set(e.annotationElementId,e),this.onAnnotationEditor?.(e.constructor._type))}has(t){return this.#s.has(t)}get size(){return this.#s.size}#r(){this.#t||(this.#t=!0,this.onSetModified?.())}resetModified(){this.#t&&(this.#t=!1,this.onResetModified?.())}get print(){return new as(this)}get serializable(){if(0===this.#s.size)return rs;let t=new Map,e=new ss,i=[],s=Object.create(null),r=!1;for(let[i,n]of this.#s){let a=n instanceof Ji?n.serialize(!1,s):n;n.page&&(n.pageIndex=n.page._pageIndex,delete n.page),a&&(t.set(i,a),e.update(`${i}:${JSON.stringify(a)}`),r||=!!a.bitmap)}if(r)for(let e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:rs}get editorStats(){let t=null,e=new Map,i=0,s=0;for(let r of this.#s.values()){if(!(r instanceof Ji)){r.popup&&(r.popup.deleted?s+=1:i+=1);continue}r.isCommentDeleted?s+=1:r.hasEditedComment&&(i+=1);let n=r.telemetryFinalData;if(!n)continue;let{type:a}=n;e.has(a)||e.set(a,Object.getPrototypeOf(r).constructor),t||=Object.create(null);let o=t[a]||=new Map;for(let[t,e]of Object.entries(n)){if("type"===t)continue;let i=o.getOrInsertComputed(t,ii);i.set(e,(i.get(e)??0)+1)}}if((s>0||i>0)&&(t||=Object.create(null),t.comments={deleted:s,edited:i}),!t)return null;for(let[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#e=null}updateEditor(t,e){let i=this.#i?.get(t);return!!i&&(i.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#i?.get(t)||null}get modifiedIds(){if(this.#e)return this.#e;let t=[];if(this.#i)for(let e of this.#i.values())e.serialize()&&t.push(e.annotationElementId);let e="";if(t.length){let i=new ss;i.update(t.join(",")),e=i.hexdigest()}return this.#e={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#s.entries()}},as=class extends ns{#t=rs;constructor(t){super();let{serializable:e}=t;if(e===rs)return;let{map:i,hash:s,transfer:r}=e,n=structuredClone(i,r?{transfer:r}:null);this.#t={map:n,hash:s,transfer:[]}}get print(){Oe("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return He(this,"modifiedIds",{ids:new Set,hash:""})}},os="__forcedDependency",{floor:ls,ceil:hs}=Math;function ds(t,e,i,s,r,n){t[4*e+0]=Math.min(t[4*e+0],i),t[4*e+1]=Math.min(t[4*e+1],s),t[4*e+2]=Math.max(t[4*e+2],r),t[4*e+3]=Math.max(t[4*e+3],n)}var cs=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],us=class{#t;#e;constructor(t,e){this.#t=t,this.#e=e}get length(){return this.#t.length}isEmpty(t){return this.#t[t]===cs}minX(t){return this.#e[4*t+0]/256}minY(t){return this.#e[4*t+1]/256}maxX(t){return(this.#e[4*t+2]+1)/256}maxY(t){return(this.#e[4*t+3]+1)/256}},ps=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1})),gs=class{#t=[[1,0,0,1,0,0]];#e=[-1/0,-1/0,1/0,1/0];#i=new Float64Array(Vt);_pendingBBoxIdx=-1;#s;#r;#n;#a;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#s=t.width,this.#r=t.height,this.#o(e)}growOperationsCount(t){t>=this.#a.length&&this.#o(t,this.#a)}#o(t,e){let i=new ArrayBuffer(4*t);this.#n=new Uint8ClampedArray(i),this.#a=new Uint32Array(i),e&&e.length>0?(this.#a.set(e),this.#a.fill(cs,e.length)):this.#a.fill(cs)}get clipBox(){return this.#e}save(t){return this.#e={__proto__:this.#e},this._savesStack.push(t),this}restore(t,e){let i=Object.getPrototypeOf(this.#e);if(null===i)return this;this.#e=i;let s=this._savesStack.pop();return void 0!==s&&(e?.(s,t),this.#a[t]=this.#a[s]),this}recordOpenMarker(t){return this._savesStack.push(t),this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){let i=this._savesStack.pop();return void 0!==i&&(e?.(i,t),this.#a[t]=this.#a[i]),this}beginMarkedContent(t){return this._markedContentStack.push(t),this}endMarkedContent(t,e){let i=this._markedContentStack.pop();return void 0!==i&&(e?.(i,t),this.#a[t]=this.#a[i]),this}pushBaseTransform(t){return this.#t.push(Ke.multiplyByDOMMatrix(this.#t.at(-1),t.getTransform())),this}popBaseTransform(){return this.#t.length>1&&this.#t.pop(),this}resetBBox(t){return this._pendingBBoxIdx!==t&&(this._pendingBBoxIdx=t,this.#i.set(Vt,0)),this}recordClipBox(t,e,i,s,r,n){let a=Ke.multiplyByDOMMatrix(this.#t.at(-1),e.getTransform()),o=Vt.slice();Ke.axialAlignedBoundingBox([i,r,s,n],a,o);let l=Ke.intersect(this.#e,o);return l?(this.#e[0]=l[0],this.#e[1]=l[1],this.#e[2]=l[2],this.#e[3]=l[3]):(this.#e[0]=this.#e[1]=1/0,this.#e[2]=this.#e[3]=-1/0),this}recordBBox(t,e,i,s,r,n){let a=this.#e;if(a[0]===1/0)return this;let o=Ke.multiplyByDOMMatrix(this.#t.at(-1),e.getTransform());if(a[0]===-1/0)return Ke.axialAlignedBoundingBox([i,r,s,n],o,this.#i),this;let l=Vt.slice();return Ke.axialAlignedBoundingBox([i,r,s,n],o,l),this.#i[0]=ri(l[0],a[0],this.#i[0]),this.#i[1]=ri(l[1],a[1],this.#i[1]),this.#i[2]=ri(l[2],this.#i[2],a[2]),this.#i[3]=ri(l[3],this.#i[3],a[3]),this}recordFullPageBBox(t){return this.#i[0]=Math.max(0,this.#e[0]),this.#i[1]=Math.max(0,this.#e[1]),this.#i[2]=Math.min(this.#s,this.#e[2]),this.#i[3]=Math.min(this.#r,this.#e[3]),this}recordOperation(t,e=!1,i){if(this._pendingBBoxIdx!==t)return this;let s=ls(256*this.#i[0]/this.#s),r=ls(256*this.#i[1]/this.#r),n=hs(256*this.#i[2]/this.#s),a=hs(256*this.#i[3]/this.#r);if(ds(this.#n,t,s,r,n,a),i)for(let e of i)for(let i of e)i!==t&&ds(this.#n,i,s,r,n,a);return e||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(t){return this._pendingBBoxIdx===t&&(this._pendingBBoxIdx=-1,this.#e[0]=Math.max(this.#e[0],this.#i[0]),this.#e[1]=Math.max(this.#e[1],this.#i[1]),this.#e[2]=Math.min(this.#e[2],this.#i[2]),this.#e[3]=Math.min(this.#e[3],this.#i[3])),this}take(){return new us(this.#a,this.#n)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,i,s=1,r=0,n=0,a){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}},ms=class{#t={__proto__:null};#e={__proto__:null,transform:[],moveText:[],sameLineText:[],[os]:[]};#i=new Map;#s=new Set;#r=new Map;#n;#a;#o;constructor(t,e=!1){this.#o=t,e&&(this.#n=new Map,this.#a=(t,e)=>{ps(this.#n,e).dependencies.add(t)})}get clipBox(){return this.#o.clipBox}growOperationsCount(t){this.#o.growOperationsCount(t)}save(t){return this.#t={__proto__:this.#t},this.#e={__proto__:this.#e,transform:{__proto__:this.#e.transform},moveText:{__proto__:this.#e.moveText},sameLineText:{__proto__:this.#e.sameLineText},[os]:{__proto__:this.#e[os]}},this.#o.save(t),this}restore(t){this.#o.restore(t,this.#a);let e=Object.getPrototypeOf(this.#t);return null===e||(this.#t=e,this.#e=Object.getPrototypeOf(this.#e)),this}recordOpenMarker(t){return this.#o.recordOpenMarker(t,this.#a),this}getOpenMarker(){return this.#o.getOpenMarker()}recordCloseMarker(t){return this.#o.recordCloseMarker(t,this.#a),this}beginMarkedContent(t){return this.#o.beginMarkedContent(t),this}endMarkedContent(t){return this.#o.endMarkedContent(t,this.#a),this}pushBaseTransform(t){return this.#o.pushBaseTransform(t),this}popBaseTransform(){return this.#o.popBaseTransform(),this}recordSimpleData(t,e){return this.#t[t]=e,this}recordIncrementalData(t,e){return this.#e[t].push(e),this}resetIncrementalData(t,e){return this.#e[t].length=0,this}recordNamedData(t,e){return this.#i.set(t,e),this}recordSimpleDataFromNamed(t,e,i){this.#t[t]=this.#i.get(e)??i}recordFutureForcedDependency(t,e){return this.recordIncrementalData(os,e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(let e of t)e in this.#t&&this.recordFutureForcedDependency(e,this.#t[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let t of this.#s)this.recordFutureForcedDependency(os,t);return this}resetBBox(t){return this.#o.resetBBox(t),this}recordClipBox(t,e,i,s,r,n){return this.#o.recordClipBox(t,e,i,s,r,n),this}recordBBox(t,e,i,s,r,n){return this.#o.recordBBox(t,e,i,s,r,n),this}recordCharacterBBox(t,e,i,s=1,r=0,n=0,a){let o,l,h=i.bbox;if(h&&(o=h[2]!==h[0]&&h[3]!==h[1]&&this.#r.get(i),!1!==o&&(l=[0,0,0,0],Ke.axialAlignedBoundingBox(h,i.fontMatrix,l),(1!==s||0!==r||0!==n)&&function(t,e,i,s,r){let n;t?(t<0&&(n=r[0],r[0]=r[2],r[2]=n),r[0]*=t,r[2]*=t,e<0&&(n=r[1],r[1]=r[3],r[3]=n),r[1]*=e,r[3]*=e):r.fill(0),r[0]+=i,r[1]+=s,r[2]+=i,r[3]+=s}(s,-s,r,n,l),o)))return this.recordBBox(t,e,l[0],l[2],l[1],l[3]);if(!a)return this.recordFullPageBBox(t);let d=a();return h&&l&&void 0===o&&(o=l[0]<=r-d.actualBoundingBoxLeft&&l[2]>=r+d.actualBoundingBoxRight&&l[1]<=n-d.actualBoundingBoxAscent&&l[3]>=n+d.actualBoundingBoxDescent,this.#r.set(i,o),o)?this.recordBBox(t,e,l[0],l[2],l[1],l[3]):this.recordBBox(t,e,r-d.actualBoundingBoxLeft,r+d.actualBoundingBoxRight,n-d.actualBoundingBoxAscent,n+d.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#o.recordFullPageBBox(t),this}getSimpleIndex(t){return this.#t[t]}recordDependencies(t,e){let i=this.#s,s=this.#t,r=this.#e;for(let t of e)t in this.#t?i.add(s[t]):t in r&&r[t].forEach(i.add,i);return this}recordNamedDependency(t,e){return this.#i.has(e)&&this.#s.add(this.#i.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,[os]),this.#n){let e=ps(this.#n,t),{dependencies:i}=e;this.#s.forEach(i.add,i),this.#o._savesStack.forEach(i.add,i),this.#o._markedContentStack.forEach(i.add,i),i.delete(t),e.isRenderingOperation=!0}let i=!e&&t===this.#o._pendingBBoxIdx;return this.#o.recordOperation(t,e,[this.#s,this.#o._savesStack,this.#o._markedContentStack]),i&&this.#s.clear(),this}recordShowTextOperation(t,e=!1){let i=Array.from(this.#s);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(let t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){let i=!e&&t===this.#o._pendingBBoxIdx;return this.#o.bboxToClipBoxDropOperation(t),i&&this.#s.clear(),this}take(){return this.#r.clear(),this.#o.take()}takeDebugMetadata(){return this.#n}},fs=class t{#t;#e;#i;#s=0;#r=0;constructor(e,i,s){if(e instanceof t&&e.#i===!!s)return e;this.#t=e,this.#e=i,this.#i=!!s}get clipBox(){return this.#t.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#r++,this.#t.save(this.#e),this}restore(t){return this.#r>0&&(this.#t.restore(this.#e),this.#r--),this}recordOpenMarker(t){return this.#s++,this}getOpenMarker(){return this.#s>0?this.#e:this.#t.getOpenMarker()}recordCloseMarker(t){return this.#s--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#t.pushBaseTransform(t),this}popBaseTransform(){return this.#t.popBaseTransform(),this}recordSimpleData(t,e){return this.#t.recordSimpleData(t,this.#e),this}recordIncrementalData(t,e){return this.#t.recordIncrementalData(t,this.#e),this}resetIncrementalData(t,e){return this.#t.resetIncrementalData(t,this.#e),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this.#t.recordSimpleDataFromNamed(t,e,this.#e),this}recordFutureForcedDependency(t,e){return this.#t.recordFutureForcedDependency(t,this.#e),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#t.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#t.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#i||this.#t.resetBBox(this.#e),this}recordClipBox(t,e,i,s,r,n){return this.#i||this.#t.recordClipBox(this.#e,e,i,s,r,n),this}recordBBox(t,e,i,s,r,n){return this.#i||this.#t.recordBBox(this.#e,e,i,s,r,n),this}recordCharacterBBox(t,e,i,s,r,n,a){return this.#i||this.#t.recordCharacterBBox(this.#e,e,i,s,r,n,a),this}recordFullPageBBox(t){return this.#i||this.#t.recordFullPageBBox(this.#e),this}getSimpleIndex(t){return this.#t.getSimpleIndex(t)}recordDependencies(t,e){return this.#t.recordDependencies(this.#e,e),this}recordNamedDependency(t,e){return this.#t.recordNamedDependency(this.#e,e),this}recordOperation(t){return this.#t.recordOperation(this.#e,!0),this}recordShowTextOperation(t){return this.#t.recordShowTextOperation(this.#e,!0),this}bboxToClipBoxDropOperation(t){return this.#i||this.#t.bboxToClipBoxDropOperation(this.#e,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}},bs=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],vs=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],ys=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],As=["filter","fillColor","fillAlpha"],ws=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],xs=["transform"],_s=["transform","fillColor"],Ss=class t{#t;#e;#i=4;#s=0;#r=new t.#n(6*this.#i);static#n=qe.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#t=t.width,this.#e=t.height}record(e,i,s,r){if(this.#s===this.#i){this.#i*=2;let e=new t.#n(6*this.#i);e.set(this.#r),this.#r=e}let n,a=xi(e);if(r[0]!==1/0){let t=Vt.slice();Ke.axialAlignedBoundingBox([0,-s,i,0],a,t);let e=Ke.intersect(r,t);if(!e)return;let[o,l,h,d]=e;if(o!==t[0]||l!==t[1]||h!==t[2]||d!==t[3]){let t=Math.atan2(a[1],a[0]),e=Math.abs(Math.sin(t)),i=Math.abs(Math.cos(t));if(e<1e-6||i<1e-6||Math.abs(e-i)<1e-6)n=[o,l,o,d,h,l];else{let t=h-o,s=d-l,r=e*e,a=i*i,c=i*e,u=a-r,p=(s*a-t*c)/u;n=[o+(s*c-t*r)/u,l,o,l+p,h,d-p]}}}n||(n=[0,-s,0,0,i,-s],Ke.applyTransform(n,a,0),Ke.applyTransform(n,a,2),Ke.applyTransform(n,a,4)),n[0]/=this.#t,n[1]/=this.#e,n[2]/=this.#t,n[3]/=this.#e,n[4]/=this.#t,n[5]/=this.#e,this.#r.set(n,6*this.#s),this.#s++}take(){return this.#r.subarray(0,6*this.#s)}},Cs=class{#t=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));let e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(let t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#t.has(t.loadedName)){if(Re(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:e,src:s,style:r}=t,n=new FontFace(e,s,r);this.addNativeFontFace(n);try{await n.load(),this.#t.add(e),i?.(t)}catch{Le(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(n)}return}Oe("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){let e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw Le(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}let e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{let i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return He(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return He(this,"isSyncFontLoadingSupported",zt||qe.platform.isFirefox)}_queueLoadingCallback(t){let{loadingRequests:e}=this,i={done:!1,complete:function(){for(Re(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){let t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return He(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function s(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let r,n,a=this._document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d"),l=0;let h=`lt${Date.now()}${this.loadTestFontId++}`,d=this._loadTestFont;d=s(d,976,h.length,h);let c=1482184792,u=i(d,16);for(r=0,n=h.length-3;r<n;r+=4)u=u-c+i(h,r)|0;var p;r<h.length&&(u=u-c+i(h+"XXX",r)|0),d=s(d,16,4,(p=u,String.fromCharCode(p>>24&255,p>>16&255,p>>8&255,255&p)));let g=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(g);let 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(let e of[t.loadedName,h]){let t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++l>30)return Le("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,()=>{m.remove(),e.complete()})}},Es=class{compiledGlyphs=Object.create(null);#t;constructor(t,e=null,i,s){this.#t=t,this._inspectFont=e,i&&(this.charProcOperatorList=i),s&&Object.assign(this,s)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){let 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;let t,e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${e}}`}else t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;return this._inspectFont?.(this,e),t}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let i,s=this.loadedName+"_path_"+e;try{i=t.get(s)}catch(t){Le(`getPathGenerator - ignoring character: "${t}".`)}let r=Ni(i?.path);return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=r}get black(){return this.#t.black}get bold(){return this.#t.bold}get disableFontFace(){return this.#t.disableFontFace}set disableFontFace(t){He(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#t.fontExtraProperties}get isInvalidPDFjsFont(){return this.#t.isInvalidPDFjsFont}get isType3Font(){return this.#t.isType3Font}get italic(){return this.#t.italic}get missingFile(){return this.#t.missingFile}get remeasure(){return this.#t.remeasure}get vertical(){return this.#t.vertical}get ascent(){return this.#t.ascent}get defaultWidth(){return this.#t.defaultWidth}get descent(){return this.#t.descent}get bbox(){return this.#t.bbox}get fontMatrix(){return this.#t.fontMatrix}get fallbackName(){return this.#t.fallbackName}get loadedName(){return this.#t.loadedName}get mimetype(){return this.#t.mimetype}get name(){return this.#t.name}get data(){return this.#t.data}clearData(){this.#t.clearData()}get cssFontInfo(){return this.#t.cssFontInfo}get systemFontInfo(){return this.#t.systemFontInfo}get defaultVMetrics(){return this.#t.defaultVMetrics}},ks=class{static strings=["fontFamily","fontWeight","italicAngle"]},Ts=class{static strings=["css","loadedName","baseFontName","src"]},Ms=class{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6},Ps=class{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16},Ds=class{#t;#e=new TextDecoder;#i;constructor(t){this.#t=t,this.#i=new DataView(t)}#s(t){Re(t<ks.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#i.getUint32(e)+4;let i=this.#i.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,i))}get fontFamily(){return this.#s(0)}get fontWeight(){return this.#s(1)}get italicAngle(){return this.#s(2)}},Is=class{#t;#e=new TextDecoder;#i;constructor(t){this.#t=t,this.#i=new DataView(t)}get guessFallback(){return 0!==this.#i.getUint8(0)}#s(t){Re(t<Ts.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#i.getUint32(e)+4;let i=this.#i.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,i))}get css(){return this.#s(0)}get loadedName(){return this.#s(1)}get baseFontName(){return this.#s(2)}get src(){return this.#s(3)}get style(){let t=1;t+=4+this.#i.getUint32(t);let e=this.#i.getUint32(t),i=this.#e.decode(new Uint8Array(this.#t,t+4,e));t+=4+e;let s=this.#i.getUint32(t);return{style:i,weight:this.#e.decode(new Uint8Array(this.#t,t+4,s))}}},Fs=class{#t;#e=new TextDecoder;#i;constructor({buffer:t,extra:e}){this.#t=t,this.#i=new DataView(t),e&&Object.assign(this,e)}#s(t){Re(t<Ms.bools.length,"Invalid boolean index");let e=Math.floor(t/4),i=2*t%8,s=this.#i.getUint8(e)>>i&3;return 0===s?void 0:2===s}get black(){return this.#s(0)}get bold(){return this.#s(1)}get disableFontFace(){return this.#s(2)}get fontExtraProperties(){return this.#s(3)}get isInvalidPDFjsFont(){return this.#s(4)}get isType3Font(){return this.#s(5)}get italic(){return this.#s(6)}get missingFile(){return this.#s(7)}get remeasure(){return this.#s(8)}get vertical(){return this.#s(9)}#r(t){return Re(t<Ms.numbers.length,"Invalid number index"),this.#i.getFloat64(Ms.OFFSET_NUMBERS+8*t)}get ascent(){return this.#r(0)}get defaultWidth(){return this.#r(1)}get descent(){return this.#r(2)}#n(t,e,i,s){let r=this.#i.getUint8(t);if(0===r)return;Re(r===e,"Invalid array length."),t+=1;let n=new Array(r);for(let e=0;e<r;e++)n[e]=this.#i[i](t,!0),t+=s;return n}get bbox(){return this.#n(Ms.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#n(Ms.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#n(Ms.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#a(t){Re(t<Ms.strings.length,"Invalid string index");let e=Ms.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#i.getUint32(e)+4;let i=this.#i.getUint32(e);return this.#e.decode(new Uint8Array(this.#t,e+4,i))}get fallbackName(){return this.#a(0)}get loadedName(){return this.#a(1)}get mimetype(){return this.#a(2)}get name(){return this.#a(3)}#o(){let t=Ms.OFFSET_STRINGS;return t+=4+this.#i.getUint32(t),t+=4+this.#i.getUint32(t),t+=4+this.#i.getUint32(t),{offset:t,length:this.#i.getUint32(t)}}get data(){let{offset:t,length:e}=this.#o();return 0===e?void 0:new Uint8Array(this.#t,t+4,e)}clearData(){let{offset:t,length:e}=this.#o();0!==e&&(this.#i.setUint32(t,0),this.#t=new Uint8Array(this.#t,0,t+4).slice().buffer,this.#i=new DataView(this.#t))}get cssFontInfo(){let t=Ms.OFFSET_STRINGS;t+=4+this.#i.getUint32(t),t+=4+this.#i.getUint32(t);let e=this.#i.getUint32(t);if(0===e)return null;let i=new Uint8Array(e);return i.set(new Uint8Array(this.#t,t+4,e)),new Ds(i.buffer)}get systemFontInfo(){let t=Ms.OFFSET_STRINGS;t+=4+this.#i.getUint32(t);let e=this.#i.getUint32(t);if(0===e)return null;let i=new Uint8Array(e);return i.set(new Uint8Array(this.#t,t+4,e)),new Is(i.buffer)}},Ls=class{constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}getIR(){let t=this.view,e=this.data[Ps.KIND],i=!!this.data[Ps.HAS_BBOX],s=!!this.data[Ps.HAS_BACKGROUND],r=t.getUint32(Ps.N_COORD,!0),n=t.getUint32(Ps.N_COLOR,!0),a=t.getUint32(Ps.N_STOP,!0),o=20,l=new Float32Array(this.buffer,o,2*r);o+=8*r;let h=new Uint8Array(this.buffer,o,4*n);o+=4*n;let d=[];for(let e=0;e<a;++e){let e=t.getFloat32(o,!0);o+=4;let i=t.getUint32(o,!0);o+=4,d.push([e,`#${i.toString(16).padStart(6,"0")}`])}let c=null;if(i){c=[];for(let e=0;e<4;++e)c.push(t.getFloat32(o,!0)),o+=4}let u=null;if(s&&(u=new Uint8Array(this.buffer,o,3),o+=3),1===e)return["RadialAxial","axial",c,d,Array.from(l.slice(0,2)),Array.from(l.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",c,d,[l[0],l[1]],[l[3],l[4]],l[2],l[5]];if(3===e){let t=this.data[Ps.SHADING_TYPE],e=null;if(l.length>0){e=Vt.slice();for(let t=0,i=l.length;t<i;t+=2)Ke.pointBoundingBox(l[t],l[t+1],e)}return["Mesh",t,l,h,r,e,c,u]}throw new Error(`Unsupported pattern kind: ${e}`)}},Os=class{#t;constructor(t){this.#t=t}get path(){return qe.isFloat16ArraySupported?new Float16Array(this.#t):new Float32Array(this.#t)}};function Rs(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}var Ns=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,Bs=function(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;let[s,r,...n]=i;if(!t(s)&&!Number.isInteger(s)||!e(r))return!1;let a=n.length,o=!0;switch(r.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return 0===a;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(4!==a)return!1;o=!1;break;default:return!1}for(let t of n)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,Ns,t=>"object"==typeof t&&"string"==typeof t?.name),Us=class{#t=new Map;#e=Promise.resolve();postMessage(t,e){let i={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(let[t]of this.#t)t.call(this,i)})}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){let{signal:r}=i;if(r.aborted)return void Le("LoopbackPort - cannot use an `aborted` signal.");let n=()=>this.removeEventListener(t,e);s=()=>r.removeEventListener("abort",n),r.addEventListener("abort",n)}this.#t.set(e,s)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(let[,t]of this.#t)t?.();this.#t.clear()}},Hs=1,js=2,$s=1,Gs=2,zs=3,Vs=4,Ws=5,Xs=6,Ys=7,qs=8;function Ks(){}function Qs(t){if(t instanceof Xe||t instanceof ze||t instanceof $e||t instanceof Ve||t instanceof Ge)return t;switch(t instanceof Error||"object"==typeof t&&null!==t||Oe('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new Xe(t.message);case"InvalidPDFException":return new ze(t.message);case"PasswordException":return new $e(t.message,t.code);case"ResponseException":return new Ve(t.message,t.status,t.missing);case"UnknownErrorException":return new Ge(t.message,t.details)}return new Ge(t.message,t.toString())}var Js=class{#t=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,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),i.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#s(t);if(t.callback){let e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===Hs)i.resolve(t.data);else{if(t.callback!==js)throw new Error("Unexpected callback case");i.reject(Qs(t.reason))}return}let e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){let i=this.sourceName,s=t.sourceName,r=this.comObj;return void Promise.try(e,t.data).then(function(e){r.postMessage({sourceName:i,targetName:s,callback:Hs,callbackId:t.callbackId,data:e})},function(e){r.postMessage({sourceName:i,targetName:s,callback:js,callbackId:t.callbackId,reason:Qs(e)})})}t.streamId?this.#i(t):e(t.data)}on(t,e){let i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){let s=this.callbackId++,r=Promise.withResolvers();this.callbackCapabilities[s]=r;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){r.reject(t)}return r.promise}sendWithStream(t,e,i,s){let r=this.streamId++,n=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{let l=Promise.withResolvers();return this.streamControllers[r]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:n,targetName:a,action:t,streamId:r,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{let e=Promise.withResolvers();return this.streamControllers[r].pullCall=e,o.postMessage({sourceName:n,targetName:a,stream:Xs,streamId:r,desiredSize:t.desiredSize}),e.promise},cancel:t=>{Re(t instanceof Error,"cancel must have a valid reason");let e=Promise.withResolvers();return this.streamControllers[r].cancelCall=e,this.streamControllers[r].isClosed=!0,o.postMessage({sourceName:n,targetName:a,stream:$s,streamId:r,reason:Qs(t)}),e.promise}},i)}#i(t){let e=t.streamId,i=this.sourceName,s=t.sourceName,r=this.comObj,n=this,a=this.actionHandler[t.action],o={enqueue(t,n=1,a){if(this.isCancelled)return;let o=this.desiredSize;this.desiredSize-=n,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),r.postMessage({sourceName:i,targetName:s,stream:Vs,streamId:e,chunk:t},a)},close(){this.isCancelled||(this.isCancelled=!0,r.postMessage({sourceName:i,targetName:s,stream:zs,streamId:e}),delete n.streamSinks[e])},error(t){Re(t instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,r.postMessage({sourceName:i,targetName:s,stream:Ws,streamId:e,reason:Qs(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,Promise.try(a,t.data,o).then(function(){r.postMessage({sourceName:i,targetName:s,stream:qs,streamId:e,success:!0})},function(t){r.postMessage({sourceName:i,targetName:s,stream:qs,streamId:e,reason:Qs(t)})})}#s(t){let e=t.streamId,i=this.sourceName,s=t.sourceName,r=this.comObj,n=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case qs:t.success?n.startCall.resolve():n.startCall.reject(Qs(t.reason));break;case Ys:t.success?n.pullCall.resolve():n.pullCall.reject(Qs(t.reason));break;case Xs:if(!a){r.postMessage({sourceName:i,targetName:s,stream:Ys,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Ks).then(function(){r.postMessage({sourceName:i,targetName:s,stream:Ys,streamId:e,success:!0})},function(t){r.postMessage({sourceName:i,targetName:s,stream:Ys,streamId:e,reason:Qs(t)})});break;case Vs:if(Re(n,"enqueue should have stream controller"),n.isClosed)break;n.controller.enqueue(t.chunk);break;case zs:if(Re(n,"close should have stream controller"),n.isClosed)break;n.isClosed=!0,n.controller.close(),this.#r(n,e);break;case Ws:Re(n,"error should have stream controller"),n.controller.error(Qs(t.reason)),this.#r(n,e);break;case Gs:t.success?n.cancelCall.resolve():n.cancelCall.reject(Qs(t.reason)),this.#r(n,e);break;case $s:if(!a)break;let o=Qs(t.reason);Promise.try(a.onCancel||Ks,o).then(function(){r.postMessage({sourceName:i,targetName:s,stream:Gs,streamId:e,success:!0})},function(t){r.postMessage({sourceName:i,targetName:s,stream:Gs,streamId:e,reason:Qs(t)})}),a.sinkCapability.reject(o),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}},Zs=class{#t=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:i=null}){this.cMapUrl=t,this.standardFontDataUrl=e,this.wasmUrl=i}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Oe(`Not implemented: ${t}`)}let i=this[t];if(!i)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);let s=`${i}${e}`;return this._fetch(s,t).catch(e=>{throw new Error(`Unable to load ${this.#t[t]} data at: ${s}`)})}async _fetch(t,e){Oe("Abstract method `_fetch` called.")}},tr=class extends Zs{async _fetch(t,e){let i="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",s=await hi(t,i);return s instanceof Uint8Array?s:Ye(s)}},er=class{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");let i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#t})}}reset({canvas:t},e,i){if(!t)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.width=e,t.height=i}destroy(t){let{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){Oe("Abstract method `_createCanvas` called.")}},ir=class extends er{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){let i=this._document.createElement("canvas");return i.width=t,i.height=e,i}},sr=class{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,i,s,r){return"none"}addSelectionHCMFilter(t,e){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(t=null){return null}destroy(t=!1){}},rr=class extends sr{#t;#e;#i;#s;#r;#n;#a=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#s=t,this.#r=e}get#o(){return this.#e||=new Map}get#l(){return this.#n||=new Map}get#h(){if(!this.#i){let t=this.#r.createElement("div"),{style:e}=t;e.colorScheme="only light",e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;let i=this.#r.createElementNS(qt,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#i=this.#r.createElementNS(qt,"defs"),t.append(i),i.append(this.#i),this.#r.body.append(t)}return this.#i}#d(t){if(1===t.length){let e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;let s=i.join(",");return[s,s,s]}let[e,i,s]=t,r=new Array(256),n=new Array(256),a=new Array(256);for(let t=0;t<256;t++)r[t]=e[t]/255,n[t]=i[t]/255,a[t]=s[t]/255;return[r.join(","),n.join(","),a.join(",")]}#c(t){if(void 0===this.#t){this.#t="";let t=this.#r.URL;t!==this.#r.baseURI&&(ci(t)?Le('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=Be(t,""))}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#o.get(t);if(e)return e;let[i,s,r]=this.#d(t),n=1===t.length?i:`${i}${s}${r}`;if(e=this.#o.get(n),e)return this.#o.set(t,e),e;let a=`g_${this.#s}_transfer_map_${this.#a++}`,o=this.#c(a);this.#o.set(t,o),this.#o.set(n,o);let l=this.#g(a);return this.#f(i,s,r,l),o}addHCMFilter(t,e){let i=`${t}-${e}`,s="base",r=this.#l.get(s);if(r?.key===i||(r?(r.filter?.remove(),r.key=i,r.url="none",r.filter=null):(r={key:i,url:"none",filter:null},this.#l.set(s,r)),!t||!e))return r.url;let n=this.#v(t);t=Ke.makeHexColor(...n);let a=this.#v(e);if(e=Ke.makeHexColor(...a),this.#h.style.color="","#000000"===t&&"#ffffff"===e||t===e)return r.url;let o=new Array(256);for(let t=0;t<=255;t++){let e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}let l=o.join(","),h=`g_${this.#s}_hcm_filter`,d=r.filter=this.#g(h);this.#f(l,l,l,d),this.#p(d);let c=(t,e)=>{let i=n[t]/255,s=a[t]/255,r=new Array(e+1);for(let t=0;t<=e;t++)r[t]=i+t/e*(s-i);return r.join(",")};return this.#f(c(0,5),c(1,5),c(2,5),d),r.url=this.#c(h),r.url}addSelectionHCMFilter(t,e){return this.addHighlightHCMFilter("selection",t,e,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){let e=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return"none"!==e&&qe.platform.isFirefox?{"backdrop-filter":e,"background-color":"transparent"}:null}addAlphaFilter(t){let e=this.#o.get(t);if(e)return e;let[i]=this.#d([t]),s=`alpha_${i}`;if(e=this.#o.get(s),e)return this.#o.set(t,e),e;let r=`g_${this.#s}_alpha_map_${this.#a++}`,n=this.#c(r);this.#o.set(t,n),this.#o.set(s,n);let a=this.#g(r);return this.#b(i,a),n}addLuminosityFilter(t){let e,i,s=this.#o.get(t||"luminosity");if(s)return s;if(t?([e]=this.#d([t]),i=`luminosity_${e}`):i="luminosity",s=this.#o.get(i),s)return this.#o.set(t,s),s;let r=`g_${this.#s}_luminosity_map_${this.#a++}`,n=this.#c(r);this.#o.set(t,n),this.#o.set(i,n);let a=this.#g(r);return this.#u(a),t&&this.#b(e,a),n}addKnockoutFilter(t=0){let e=t>0?Math.min(1/t,1e6):1e6,i=`knockout_${e}`,s=this.#o.get(i);if(s)return s;let r=`g_${this.#s}_knockout_filter_${this.#a++}`,n=this.#c(r);this.#o.set(i,n);let a=this.#g(r),o=this.#r.createElementNS(qt,"feComponentTransfer");a.append(o);let l=this.#r.createElementNS(qt,"feFuncA");return l.setAttribute("type","linear"),l.setAttribute("slope",`${e}`),l.setAttribute("intercept","0"),o.append(l),n}addHighlightHCMFilter(t,e,i,s,r){let n=`${e}-${i}-${s}-${r}`,a=this.#l.get(t);if(a?.key===n||(a?(a.filter?.remove(),a.key=n,a.url="none",a.filter=null):(a={key:n,url:"none",filter:null},this.#l.set(t,a)),!e||!i))return a.url;let[o,l]=[e,i].map(this.#v.bind(this)),h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,r].map(this.#A.bind(this));d<h&&([h,d,c,u]=[d,h,u,c]),this.#h.style.color="";let p=(t,e,i)=>{let s=new Array(256),r=(d-h)/i,n=t/255,a=(e-t)/(255*i),o=0;for(let t=0;t<=i;t++){let e=Math.round(h+t*r),i=n+t*a;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#s}_hcm_${t}_filter`,m=a.filter=this.#g(g);return this.#p(m),this.#f(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),a.url=this.#c(g),a.url}destroy(t=!1){t&&this.#n?.size||(this.#i?.parentNode.parentNode.remove(),this.#i=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#a=0)}#u(t){let e=this.#r.createElementNS(qt,"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)}#p(t){let e=this.#r.createElementNS(qt,"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)}#g(t){let e=this.#r.createElementNS(qt,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#h.append(e),e}#m(t,e,i){let s=this.#r.createElementNS(qt,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#f(t,e,i,s){let r=this.#r.createElementNS(qt,"feComponentTransfer");s.append(r),this.#m(r,"feFuncR",t),this.#m(r,"feFuncG",e),this.#m(r,"feFuncB",i)}#b(t,e){let i=this.#r.createElementNS(qt,"feComponentTransfer");e.append(i),this.#m(i,"feFuncA",t)}#v(t){return this.#h.style.color=t,wi(getComputedStyle(this.#h).getPropertyValue("color"))}#y(t){return this.#h.style.color=t,Ai(getComputedStyle(this.#h).getPropertyValue("color"))}#A(t){let[e,i,s,r]=this.#y(t);if(1===r)return[e,i,s];let[n,a,o]=this.#v("Canvas");return[nr(e,n,r),nr(i,a,r),nr(s,o,r)]}};function nr(t,e,i){return Math.round(i*t+(1-i)*e)}zt&&Le("Please use the `legacy` build in Node.js environments.");var ar=class extends sr{},or=class extends er{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}},lr=class extends Zs{async _fetch(t,e){return async function(t){let e=await process.getBuiltinModule("fs/promises").readFile(t);return new Uint8Array(e)}(t)}},hr=new class{#t=null;#e=null;#i=null;#s=null;async#r(){if(!globalThis.navigator?.gpu)return!1;try{let t=await navigator.gpu.requestAdapter();return!!t&&(this.#s=navigator.gpu.getPreferredCanvasFormat(),this.#e=await t.requestDevice(),!0)}catch{return!1}}init(){return this.#t||=this.#r()}get isReady(){return null!==this.#e}loadMeshShader(){if(!this.#e||this.#i)return;let t=this.#e.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#i=this.#e.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#s}]},primitive:{topology:"triangle-list"}})}draw(t,e,i,s,r,n,a,o){this.loadMeshShader();let l=this.#e,{offsetX:h,offsetY:d,scaleX:c,scaleY:u}=s,p=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(p,0,t);let g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,0,e);let m=l.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([h,d,c,u,n,a,o,0]));let f=l.createBindGroup({layout:this.#i.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(n,a),v=b.getContext("webgpu");v.configure({device:l,format:this.#s,alphaMode:r?"opaque":"premultiplied"});let y=r?{r:r[0]/255,g:r[1]/255,b:r[2]/255,a:1}:{r:0,g:0,b:0,a:0},A=l.createCommandEncoder(),w=A.beginRenderPass({colorAttachments:[{view:v.getCurrentTexture().createView(),clearValue:y,loadOp:"clear",storeOp:"store"}]});return i>0&&(w.setPipeline(this.#i),w.setBindGroup(0,f),w.setVertexBuffer(0,p),w.setVertexBuffer(1,g),w.draw(i)),w.end(),l.queue.submit([A.finish()]),p.destroy(),g.destroy(),m.destroy(),b.transferToImageBitmap()}};var dr="Fill",cr="Stroke",ur="Shading";function pr(t,e){if(!e)return;let i=e[2]-e[0],s=e[3]-e[1],r=new Path2D;r.rect(e[0],e[1],i,s),t.clip(r)}var gr=class{isModifyingCurrentTransform(){return!1}getPattern(){Oe("Abstract method `getPattern` called.")}},mr=class extends gr{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}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;let t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let i,s=this._p0,r=this._p1;if(e&&(s=s.slice(),r=r.slice(),Ke.applyTransform(s,e),Ke.applyTransform(r,e)),"axial"===this._type)i=t.createLinearGradient(s[0],s[1],r[0],r[1]);else if("radial"===this._type){let n=this._r0,a=this._r1;if(e){let t=new Float32Array(2);Ke.singularValueDecompose2dScale(e,t),n*=t[0],a*=t[0]}i=t.createRadialGradient(s[0],s[1],n,r[0],r[1],a)}for(let t of this._colorStops)i.addColorStop(t[0],t[1]);return i}_createReversedGradient(t,e=null){let i=this._p1,s=this._p0;e&&(i=i.slice(),s=s.slice(),Ke.applyTransform(i,e),Ke.applyTransform(s,e));let r=this._r1,n=this._r0;if(e){let t=new Float32Array(2);Ke.singularValueDecompose2dScale(e,t),r*=t[0],n*=t[0]}let a=t.createRadialGradient(i[0],i[1],r,s[0],s[1],n),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(let[t,e]of o)a.addColorStop(t,e);return a}getPattern(t,e,i,s){let r;if(s===cr||s===dr){if(this.isOriginBased()){let s=Ke.transform(i,e.baseTransform);this.matrix&&(s=Ke.transform(s,this.matrix));let r=.001,n=Math.hypot(s[0],s[1]),a=Math.hypot(s[2],s[3]),o=(s[0]*s[2]+s[1]*s[3])/(n*a);if(Math.abs(o)<r){if(!this.isRadial())return this._createGradient(t,s);if(Math.abs(n-a)<r)return this._createGradient(t,s)}}let n=e.current.getClippedPathBoundingBox(s,xi(t))||[0,0,0,0],a=Math.ceil(n[2]-n[0])||1,o=Math.ceil(n[3]-n[1])||1,l=e.canvasFactory.create(a,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-n[0],-n[1]),i=Ke.transform(i,[1,0,0,1,n[0],n[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),pr(h,this._bbox),this.areConic()&&(h.fillStyle=this._createReversedGradient(h),h.fill()),h.fillStyle=this._createGradient(h),h.fill(),r=t.createPattern(l.canvas,"no-repeat"),e.canvasFactory.destroy(l);let d=new DOMMatrix(i);r.setTransform(d)}else this.areConic()&&(t.save(),pr(t,this._bbox),t.fillStyle=this._createReversedGradient(t),t.fillRect(-1e10,-1e10,2e10,2e10),t.restore()),pr(t,this._bbox),r=this._createGradient(t);return r}};function fr(t,e,i,s,r,n,a,o){let l,h=e.coords,d=e.colors,c=t.data,u=4*t.width;h[2*i+1]>h[2*s+1]&&(l=i,i=s,s=l,l=n,n=a,a=l),h[2*s+1]>h[2*r+1]&&(l=s,s=r,r=l,l=a,a=o,o=l),h[2*i+1]>h[2*s+1]&&(l=i,i=s,s=l,l=n,n=a,a=l);let p=(h[2*i]+e.offsetX)*e.scaleX,g=(h[2*i+1]+e.offsetY)*e.scaleY,m=(h[2*s]+e.offsetX)*e.scaleX,f=(h[2*s+1]+e.offsetY)*e.scaleY,b=(h[2*r]+e.offsetX)*e.scaleX,v=(h[2*r+1]+e.offsetY)*e.scaleY;if(g>=v)return;let y,A,w,x,_,S,C,E,k=d[4*n],T=d[4*n+1],M=d[4*n+2],P=d[4*a],D=d[4*a+1],I=d[4*a+2],F=d[4*o],L=d[4*o+1],O=d[4*o+2],R=Math.round(g),N=Math.round(v);for(let t=R;t<=N;t++){if(t<f){let e=t<g?0:(g-t)/(g-f);y=p-(p-m)*e,A=k-(k-P)*e,w=T-(T-D)*e,x=M-(M-I)*e}else{let e;e=t>v?1:f===v?0:(f-t)/(f-v),y=m-(m-b)*e,A=P-(P-F)*e,w=D-(D-L)*e,x=I-(I-O)*e}let e;e=t<g?0:t>v?1:(g-t)/(g-v),_=p-(p-b)*e,S=k-(k-F)*e,C=T-(T-L)*e,E=M-(M-O)*e;let i=Math.round(Math.min(y,_)),s=Math.round(Math.max(y,_)),r=u*t+4*i;for(let t=i;t<=s;t++)e=(y-t)/(y-_),e<0?e=0:e>1&&(e=1),c[r++]=A-(A-S)*e|0,c[r++]=w-(w-C)*e|0,c[r++]=x-(x-E)*e|0,c[r++]=255}}var br=class extends gr{constructor(t){super(),this._posData=t[2],this._colData=t[3],this._vertexCount=t[4],this._bounds=t[5],this._bbox=t[6],this._background=t[7],this.matrix=null,hr.loadMeshShader()}_createMeshCanvas(t,e,i){let s=Math.floor(this._bounds[0]),r=Math.floor(this._bounds[1]),n=Math.ceil(this._bounds[2])-s,a=Math.ceil(this._bounds[3])-r,o=Math.min(Math.ceil(Math.abs(n*t[0]*1.1)),3e3)||1,l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3)||1,h=n?n/o:1,d=a?a/l:1,c={coords:this._posData,colors:this._colData,offsetX:-s,offsetY:-r,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.create(u,p);if(hr.isReady&&this._vertexCount>48)g.context.drawImage(function(t,e,i,s,r,n,a,o){return hr.draw(t,e,i,s,r,n,a,o)}(this._posData,this._colData,this._vertexCount,c,e,u,p,2),0,0);else{let t=g.context.createImageData(o,l);if(e){let i=t.data;for(let t=0,s=i.length;t<s;t+=4)i[t]=e[0],i[t+1]=e[1],i[t+2]=e[2],i[t+3]=255}for(let e=0,i=this._vertexCount;e<i;e+=3)fr(t,c,e,e+1,e+2,e,e+1,e+2);g.context.putImageData(t,2,2)}return{canvas:g.canvas,offsetX:s-2*h,offsetY:r-2*d,scaleX:h,scaleY:d}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,s){pr(t,this._bbox);let r=new Float32Array(2);if(s===ur)Ke.singularValueDecompose2dScale(xi(t),r);else if(this.matrix){Ke.singularValueDecompose2dScale(this.matrix,r);let[t,i]=r;Ke.singularValueDecompose2dScale(e.baseTransform,r),r[0]*=t,r[1]*=i}else Ke.singularValueDecompose2dScale(e.baseTransform,r);let n=this._createMeshCanvas(r,s===ur?null:this._background,e.canvasFactory);s!==ur&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(n.offsetX,n.offsetY),t.scale(n.scaleX,n.scaleY);let a=t.createPattern(n.canvas,"no-repeat");return e.canvasFactory.destroy(n),a}},vr=class extends gr{getPattern(){return"hotpink"}};var yr=1,Ar=2,wr=class t{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,s){this.color=t[1],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.needsIsolation=t[9]??!0,this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=s,this.patternBaseMatrix=this.matrix?Ke.transform(s,this.matrix):s}canSkipPatternCanvas([t,e,i,s]){let[r,n,a,o]=this.bbox,l=Math.abs(this.xstep),h=Math.abs(this.ystep);if(t>l+1e-6||e>h+1e-6)return null;let d=Math.floor((i-a)/l)+1,c=Math.ceil((i+t-r)/l)-1,u=Math.floor((s-o)/h)+1,p=Math.ceil((s+e-n)/h)-1;return c<=d&&p<=u?[d,u]:null}updatePatternDims(t,e){let i=Ke.inverseTransform(this.patternBaseMatrix),s=[t[0],t[1]],r=[t[2],t[3]];Ke.applyTransform(s,i),Ke.applyTransform(r,i),e[0]=Math.abs(r[0]-s[0]),e[1]=Math.abs(r[1]-s[1]),e[2]=Math.min(s[0],r[0]),e[3]=Math.min(s[1],r[1])}_renderTileCanvas(t,e,i,s){let[r,n,a,o]=this.bbox,l=t.canvasFactory.create(i.size,s.size),h=l.context,d=this.canvasGraphicsFactory.createCanvasGraphics(h,e);return d.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(d,this.paintType,this.color),h.translate(-i.scale*r,-s.scale*n),d.transform(0,i.scale,0,0,s.scale,0,0),h.save(),d.dependencyTracker?.save(),this.clipBbox(d,r,n,a,o),d.baseTransform=xi(d.ctx),d.executeOperatorList(this.operatorList),d.endDrawing(),d.dependencyTracker?.restore(),h.restore(),l}_getCombinedScales(){let t=new Float32Array(2);Ke.singularValueDecompose2dScale(this.matrix,t);let[e,i]=t;return Ke.singularValueDecompose2dScale(this.baseTransform,t),[e*t[0],i*t[1]]}drawPattern(t,e,i=!1,[s,r],n){let[a,o,l,h]=this.bbox,d=t.dependencyTracker;if(d&&(t.dependencyTracker=new fs(d,n)),t.save(),i?t.ctx.clip(e,"evenodd"):t.ctx.clip(e),t.ctx.setTransform(...this.patternBaseMatrix),t.ctx.translate(s*this.xstep,r*this.ystep),this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){let e=l-a,i=h-o,[s,r]=this._getCombinedScales(),d=this.getSizeAndScale(e,this.ctx.canvas.width,s),c=this.getSizeAndScale(i,this.ctx.canvas.height,r),u=this._renderTileCanvas(t,n,d,c);t.ctx.drawImage(u.canvas,a,o,e,i),t.canvasFactory.destroy(u)}else this.setFillAndStrokeStyleToContext(t,this.paintType,this.color),this.clipBbox(t,a,o,l,h),t.baseTransformStack.push(t.baseTransform),t.baseTransform=xi(t.ctx),t.executeOperatorList(this.operatorList),t.baseTransform=t.baseTransformStack.pop();t.restore(),d&&(t.dependencyTracker=d)}createPatternCanvas(t,e){let[i,s,r,n]=this.bbox,a=r-i,o=n-s,{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),Fe("TilingType: "+this.tilingType);let[d,c]=this._getCombinedScales(),u=a,p=o,g=!1,m=!1;Math.ceil(l*d)>=Math.ceil(a*d)?u=l:g=!0,Math.ceil(h*c)>=Math.ceil(o*c)?p=h:m=!0;let f=this.getSizeAndScale(u,this.ctx.canvas.width,d),b=this.getSizeAndScale(p,this.ctx.canvas.height,c),v=this._renderTileCanvas(t,e,f,b);if(g||m){let e=v.canvas;g&&(u=l),m&&(p=h);let r=this.getSizeAndScale(u,this.ctx.canvas.width,d),n=this.getSizeAndScale(p,this.ctx.canvas.height,c),f=r.size,b=n.size,y=t.canvasFactory.create(f,b),A=y.context,w=g?Math.floor(a/l):0,x=m?Math.floor(o/h):0;for(let t=0;t<=w;t++)for(let i=0;i<=x;i++)A.drawImage(e,f*t,b*i,f,b,0,0,f,b);return t.canvasFactory.destroy(v),{canvas:y.canvas,canvasEntry:y,scaleX:r.scale,scaleY:n.scale,offsetX:i,offsetY:s}}return{canvas:v.canvas,canvasEntry:v,scaleX:f.scale,scaleY:b.scale,offsetX:i,offsetY:s}}getSizeAndScale(e,i,s){let r=Math.max(t.MAX_PATTERN_SIZE,i),n=Math.ceil(e*s);return n>=r?n=r:s=n/e,{scale:s,size:n}}clipBbox(t,e,i,s,r){let n=s-e,a=r-i,o=new Path2D;o.rect(e,i,n,a),Ke.axialAlignedBoundingBox([e,i,s,r],xi(t.ctx),t.current.minMax),t.ctx.clip(o),t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,i){let s=t.ctx,r=t.current;switch(r.patternFill=r.patternStroke=!1,e){case yr:let{fillStyle:t,strokeStyle:n}=this.ctx;s.fillStyle=r.fillColor=t,s.strokeStyle=r.strokeColor=n;break;case Ar:s.fillStyle=s.strokeStyle=i,r.fillColor=r.strokeColor=i;break;default:throw new We(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s,r){let n=s!==ur?Ke.transform(i,this.patternBaseMatrix):i,a=this.createPatternCanvas(e,r),o=new DOMMatrix(n);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);let l=t.createPattern(a.canvas,"repeat");return e.canvasFactory.destroy(a.canvasEntry),l.setTransform(o),l}};function xr({src:t,srcPos:e=0,dest:i,width:s,height:r,nonBlackColor:n=4294967295,inverseDecode:a=!1}){let o=qe.isLittleEndian?4278190080:255,[l,h]=a?[n,o]:[o,n],d=s>>3,c=7&s,u=l^h,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let s=0;s<r;++s){for(let s=e+d;e<s;++e,g+=8){let s=t[e];i[g]=l^-(s>>7&1)&u,i[g+1]=l^-(s>>6&1)&u,i[g+2]=l^-(s>>5&1)&u,i[g+3]=l^-(s>>4&1)&u,i[g+4]=l^-(s>>3&1)&u,i[g+5]=l^-(s>>2&1)&u,i[g+6]=l^-(s>>1&1)&u,i[g+7]=l^-(1&s)&u}if(0===c)continue;let s=e<p?t[e++]:255;for(let t=0;t<c;++t,++g)i[g]=l^-(s>>7-t&1)&u}return{srcPos:e,destPos:g}}var _r=16,Sr=new DOMMatrix,Cr=new Float32Array(2);function Er(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");let i=new Map;for(let s of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){let r=t[s];"function"!=typeof r||"function"!=typeof e[s]||(i.set(s,r),t[s]=function(...t){return e[s](...t),r.apply(this,t)})}t._removeMirroring=()=>{for(let[e,s]of i)t[e]=s;delete t._removeMirroring}}function kr(t,e,i,s,r,n,a,o,l,h){let[d,c,u,p,g,m]=xi(t);if(0===c&&0===u){let f=a*d+g,b=Math.round(f),v=o*p+m,y=Math.round(v),A=(a+l)*d+g,w=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,_=Math.abs(Math.round(x)-y)||1;return t.setTransform(Math.sign(d),0,0,Math.sign(p),b,y),t.drawImage(e,i,s,r,n,0,0,w,_),t.setTransform(d,c,u,p,g,m),[w,_]}if(0===d&&0===p){let f=o*u+g,b=Math.round(f),v=a*c+m,y=Math.round(v),A=(o+h)*u+g,w=Math.abs(Math.round(A)-b)||1,x=(a+l)*c+m,_=Math.abs(Math.round(x)-y)||1;return t.setTransform(0,Math.sign(c),Math.sign(u),0,b,y),t.drawImage(e,i,s,r,n,0,0,_,w),t.setTransform(d,c,u,p,g,m),[_,w]}return t.drawImage(e,i,s,r,n,a,o,l,h),[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}var Tr=class{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=Xt;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=de;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=Wt.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){let t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t.tilingPatternDims=this.tilingPatternDims?.slice(),t}getPathBoundingBox(t=dr,e=null){let i=this.minMax.slice();if(t===cr){e||Oe("Stroke bounding box must include transform."),Ke.singularValueDecompose2dScale(e,Cr);let t=Cr[0]*this.lineWidth/2,s=Cr[1]*this.lineWidth/2;i[0]-=t,i[1]-=s,i[2]+=t,i[3]+=s}return i}updateClipFromPath(){let t=Ke.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(Wt,0)}getClippedPathBoundingBox(t=dr,e=null){return Ke.intersect(this.clipBox,this.getPathBoundingBox(t,e))}};function Mr(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);let i,s,r,n,a,o=e.height,l=e.width,h=o%_r,d=(o-h)/_r,c=0===h?d:d+1,u=t.createImageData(l,_r),p=0,g=e.data,m=u.data;if(e.kind===fe.GRAYSCALE_1BPP){let e=g.byteLength,a=new Uint32Array(m.buffer,0,m.byteLength>>2),o=a.length,f=l+7>>3,b=4294967295,v=qe.isLittleEndian?4278190080:255;for(s=0;s<c;s++){for(n=s<d?_r:h,i=0,r=0;r<n;r++){let t=e-p,s=0,r=t>f?l:8*t-7,n=-8&r,o=0,h=0;for(;s<n;s+=8)h=g[p++],a[i++]=128&h?b:v,a[i++]=64&h?b:v,a[i++]=32&h?b:v,a[i++]=16&h?b:v,a[i++]=8&h?b:v,a[i++]=4&h?b:v,a[i++]=2&h?b:v,a[i++]=1&h?b:v;for(;s<r;s++)0===o&&(h=g[p++],o=128),a[i++]=h&o?b:v,o>>=1}for(;i<o;)a[i++]=0;t.putImageData(u,0,s*_r)}}else if(e.kind===fe.RGBA_32BPP){for(r=0,a=l*_r*4,s=0;s<d;s++)m.set(g.subarray(p,p+a)),p+=a,t.putImageData(u,0,r),r+=_r;s<c&&(a=l*h*4,m.set(g.subarray(p,p+a)),t.putImageData(u,0,r))}else{if(e.kind!==fe.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(n=_r,a=l*n,s=0;s<c;s++){for(s>=d&&(n=h,a=l*n),i=0,r=a;r--;)m[i++]=g[p++],m[i++]=g[p++],m[i++]=g[p++],m[i++]=255;t.putImageData(u,0,s*_r)}}}function Pr(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);let i=e.height,s=e.width,r=i%_r,n=(i-r)/_r,a=0===r?n:n+1,o=t.createImageData(s,_r),l=0,h=e.data,d=o.data;for(let e=0;e<a;e++){let i=e<n?_r:r;({srcPos:l}=xr({src:h,srcPos:l,dest:d,width:s,height:i,nonBlackColor:0})),t.putImageData(o,0,e*_r)}}function Dr(t,e){let i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let s of i)void 0!==t[s]&&(e[s]=t[s]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function Ir(t){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);let{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function Fr(t,e){if(e)return!0;Ke.singularValueDecompose2dScale(t,Cr);let i=Math.fround(Ci.pixelRatio*li.PDF_TO_CSS_UNITS);return Cr[0]<=i&&Cr[1]<=i}var Lr=["butt","round","square"],Or=["miter","round","bevel"],Rr={},Nr={},Br=class t{#t=0;#e=0;#i=null;#s=null;#r=null;#n=null;#a=1;#o;#l=null;#h=[];constructor(t,e,i,s,r,{optionalContentConfig:n,markedContentStack:a=null},o,l,h,d){this.ctx=t,this.current=new Tr(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=e,this.objs=i,this.canvasFactory=s,this.filterFactory=r,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=n,this.cachedPatterns=new Map,this.annotationCanvasMap=o,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=h??null,this.imagesTracker=d??null}getObject(t,e,i=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:s=null}){let r=this.ctx.canvas.width,n=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=s||"#ffffff",this.ctx.fillRect(0,0,r,n),this.ctx.fillStyle=a,i){let t=this.transparentCanvasEntry=this.canvasFactory.create(r,n);this.compositeCtx=this.ctx,({canvas:this.transparentCanvas,context:this.ctx}=t),this.ctx.save(),this.ctx.transform(...xi(this.compositeCtx))}this.ctx.save(),Ir(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[3]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=xi(this.ctx)}executeOperatorList(t,e,i,s,r){let n=t.argsArray,a=t.fnArray,o=e||0,l=n.length;if(l===o)return o;let h,d,c=l-o>10&&"function"==typeof i,u=c?Date.now()+15:0,p=0,g=this.commonObjs,m=this.objs;for(;;){if(void 0!==s){if(o===s.nextBreakPoint)return s.breakIt(o,i),o;if(s.shouldSkip(o)){if(++o===l)return o;continue}}if(!r||r(o))if(h=a[o],d=n[o]??null,h!==Se.dependency)null===d?this[h](o):this[h](o,...d);else for(let t of d){this.dependencyTracker?.recordNamedData(t,o);let e=t.startsWith("g_")?g:m;if(!e.has(t))return e.get(t,i),o}if(o++,o===l)return o;if(c&&++p>10){if(Date.now()>u)return i(),o;p=0}}}#d(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,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.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)}endDrawing(){this.#d();for(let t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(let t of this.#h)this.#v(t);this.#h.length=0,this.#i=null,this.#s=null,this.#r=null,this.#n=null,this.#a=1,this.#l=null,this.#e=0,this.#t=0,this.cachedPatterns.clear();for(let t of this._cachedBitmapsMap.values()){for(let e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#c()}#c(){if(this.pageColors){let t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){let e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){let i=t.width??t.displayWidth,s=t.height??t.displayHeight,r=[],n=Math.max(Math.hypot(e[0],e[1]),1),a=Math.max(Math.hypot(e[2],e[3]),1),o=i,l=s;for(;n>2&&o>1||a>2&&l>1;){let t=o,e=l;n>2&&o>1&&(t=Math.ceil(o/2),n/=o/t),a>2&&l>1&&(e=Math.ceil(l/2),a/=l/e),r.push({newWidth:t,newHeight:e}),o=t,l=e}if(0===r.length)return{img:t,paintWidth:i,paintHeight:s,tmpCanvas:null};if(1===r.length){let{newWidth:e,newHeight:n}=r[0],a=this.canvasFactory.create(e,n);return a.context.drawImage(t,0,0,i,s,0,0,e,n),{img:a.canvas,paintWidth:e,paintHeight:n,tmpCanvas:a}}let h=this.canvasFactory.create(1,1),d=this.canvasFactory.create(1,1),c=i,u=s,p=t;for(let{newWidth:t,newHeight:e}of r)this.canvasFactory.reset(d,t,e),d.context.drawImage(p,0,0,c,u,0,0,t,e),[h,d]=[d,h],p=h.canvas,c=t,u=e;return this.canvasFactory.destroy(d),{img:h.canvas,paintWidth:c,paintHeight:u,tmpCanvas:h}}_createMaskCanvas(t,e){let i,s,r,n,a=this.ctx,{width:o,height:l}=e,h=this.current.fillColor,d=this.current.patternFill,c=xi(a);if((e.bitmap||e.data)&&e.count>1){let n=e.bitmap||e.data.buffer;s=JSON.stringify(d?c:[c.slice(0,4),h]),i=this._cachedBitmapsMap.getOrInsertComputed(n,ii);let a=i.get(s);if(a&&!d){let e=Math.round(Math.min(c[0],c[2])+c[4]),i=Math.round(Math.min(c[1],c[3])+c[5]);return this.dependencyTracker?.recordDependencies(t,_s),{canvas:a,offsetX:e,offsetY:i}}r=a}r||(n=this.canvasFactory.create(o,l),Pr(n.context,e));let u=Ke.transform(c,[1/o,0,0,-1/l,0,0]);u=Ke.transform(u,[1,0,0,1,0,-l]);let p=Wt.slice();Ke.axialAlignedBoundingBox([0,0,o,l],u,p);let[g,m,f,b]=p,v=Math.round(f-g)||1,y=Math.round(b-m)||1,A=this.canvasFactory.create(v,y),w=A.context,x=g,_=m;w.translate(-x,-_),w.transform(...u);let S=null;if(!r){let t=this._scaleImage(n.canvas,_i(w));r=t.img,S=t.tmpCanvas,r!==n.canvas&&(this.canvasFactory.destroy(n),n=null),i&&d&&(i.set(s,r),S=null,n=null)}w.imageSmoothingEnabled=Fr(xi(w),e.interpolate),kr(w,r,0,0,r.width,r.height,0,0,o,l),S&&this.canvasFactory.destroy(S),n&&this.canvasFactory.destroy(n),w.globalCompositeOperation="source-in";let C=Ke.transform(_i(w),[1,0,0,1,-x,-_]);return w.fillStyle=d?h.getPattern(a,this,C,dr,t):h,w.fillRect(0,0,o,l),i&&!d&&i.set(s,A.canvas),this.dependencyTracker?.recordDependencies(t,_s),{canvas:A.canvas,canvasEntry:i&&!d?null:A,offsetX:Math.round(x),offsetY:Math.round(_)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=Lr[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=Or[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);let s=this.ctx;void 0!==s.setLineDash&&(s.setLineDash(e),s.lineDashOffset=i)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(let[i,s]of e)switch(i){case"LW":this.setLineWidth(t,s);break;case"LC":this.setLineCap(t,s);break;case"LJ":this.setLineJoin(t,s);break;case"ML":this.setMiterLimit(t,s);break;case"D":this.setDash(t,s[0],s[1]);break;case"RI":this.setRenderingIntent(t,s);break;case"FL":this.setFlatness(t,s);break;case"Font":this.setFont(t,s[0],s[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=s;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=s;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=s;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=s?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){t!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(t))}checkSMaskState(t){let e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){let e,{canvas:i,subtype:s,backdrop:r,transferMap:n}=t,a="Luminosity"===s||"Alpha"===s&&n;if(!(a||"Luminosity"===s&&r))return void(this.smaskPreparedFor=t);if("Luminosity"===s&&r){let[t,i,s]=Ai(r),a=Math.round(.3*t+.59*i+.11*s);e=n?.[a]??a}else e=n?.[0]??0;let o,l,h,{width:d,height:c}=this.ctx.canvas,u=d*c<4*(i.width*i.height),p=a?{url:"Alpha"===s?this.filterFactory.addAlphaFilter(n):this.filterFactory.addLuminosityFilter(n),subtype:s,transferMap:n}:null,g="Luminosity"===s?r:null;u?(o=this._bakeSMaskCanvas(i,t.offsetX,t.offsetY,d,c,g,p),l=0,h=0):(o=this._bakeSMaskCanvas(i,0,0,i.width,i.height,g,p),l=t.offsetX,h=t.offsetY),this.smaskPreparedEntry=o,this.smaskPreparedFor=t,this.smaskPreparedOffsetX=l,this.smaskPreparedOffsetY=h,this.smaskPreparedOOBAlpha=u||0===e?null:e}_bakeSMaskCanvas(t,e,i,s,r,n,a){!n&&!a&&Oe("_bakeSMaskCanvas with neither backdrop nor filter");let o=this.canvasFactory.create(s,r),l=o.context;if(l.drawImage(t,e,i),n&&(l.globalCompositeOperation="destination-atop",l.fillStyle=n,l.fillRect(0,0,s,r)),!a)return o;let h=this.canvasFactory.create(s,r),d=h.context;d.filter=a.url;let c=qe.isCanvasFilterSupported&&"none"!==d.filter&&""!==d.filter;if(d.drawImage(o.canvas,0,0),qe.isCanvasFilterSupported&&(d.filter="none"),!c){let t=d.getImageData(0,0,s,r),{data:e}=t,{transferMap:i}=a;if("Luminosity"===a.subtype)for(let t=0,s=e.length;t<s;t+=4){let s=.3*e[t]+.59*e[t+1]+.11*e[t+2]+.5|0;e[t]=e[t+1]=e[t+2]=0,e[t+3]=i?.[s]??s}else for(let t=3,s=e.length;t<s;t+=4)e[t]=i[e[t]];d.putImageData(t,0,0)}return this.canvasFactory.destroy(o),h}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let{width:e,height:i}=this.ctx.canvas,s=this.canvasFactory.create(e,i);this.smaskScratchCanvas=s,this.suspendedCtx=this.ctx;let r=this.ctx=s.context;r.setTransform(this.suspendedCtx.getTransform()),Dr(this.suspendedCtx,r),Er(r,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Dr(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#u(t,e=null,i=1){let{width:s,height:r}=t,n=e??this.canvasFactory.create(s,r),a=n.context,o=(i=Math.round(255*i)/255)<1;o&&void 0===this.#o&&(this.#o=qe.isCanvasFilterSupported?new Map:"none");let l="none";if(o&&this.#o instanceof Map&&(l=this.#o.get(i),l||(l=this.filterFactory.addKnockoutFilter(i),this.#o.set(i,l))),!o||"none"!==l)return e&&(a.save(),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,s,r),a.restore()),a.filter=l,a.drawImage(t,0,0),a.filter="none",n;let h=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,s,r),d=a.createImageData(s,r),c=h.data,u=d.data,p=i>0?1/i:1e6;for(let t=3,e=c.length;t<e;t+=4)u[t]=Math.min(Math.round(c[t]*p),255);return a.putImageData(d,0,0),n}#p(t,e,i,s){let r=t?.[e]??null;if(r&&(r.canvas.width!==i||r.canvas.height!==s)&&(this.canvasFactory.destroy(r),r=null),!r)return r=this.canvasFactory.create(i,s),t&&(t[e]=r),r;let n=r.context;return n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,i,s),n.restore(),r}#g(t,e,i={}){let{backdropCanvas:s=null,destTransform:r=[1,0,0,1,0,0],backdropOffset:n=[0,0],reuseMaskEntry:a=null,poolMeta:o=null,sourceAlpha:l=1,sourceFilter:h="none",knockoutAlpha:d=1}=i,{width:c,height:u}=e,p=this.#u(e,a,d),g=t.globalCompositeOperation;if(t.save(),t.setTransform(...r),t.globalAlpha=1,qe.isCanvasFilterSupported&&(t.filter="none"),t.globalCompositeOperation="destination-out",t.drawImage(p.canvas,0,0),s){let[e,i]=n,r=this.#p(o,"knockoutBackdropEntry",c,u),a=r.context;a.drawImage(s,e,i,c,u,0,0,c,u),a.globalCompositeOperation="destination-in",a.drawImage(p.canvas,0,0),a.globalCompositeOperation="source-over",t.globalCompositeOperation="destination-over",t.drawImage(r.canvas,0,0),o||this.canvasFactory.destroy(r)}t.globalCompositeOperation=g,t.globalAlpha=l,qe.isCanvasFilterSupported&&(t.filter=h??"none"),t.drawImage(e,0,0),t.restore(),a||this.canvasFactory.destroy(p)}#m(t=1){if(0===this.#t||this.#e>0||!this.contentVisible)return!1;this.#e++,this.#a=t;let e=this.#h.at(-1),{canvas:i}=this.ctx,s=this.#p(e,"knockoutTempEntry",i.width,i.height);this.#i=s;let r=s.context;return r.save(),r.setTransform(this.ctx.getTransform()),Dr(this.ctx,r),this.#n=r.globalCompositeOperation,r.globalCompositeOperation="source-over",Er(r,this.ctx),this.#l=e,this.#s=this.ctx,this.#r=this.suspendedCtx,this.ctx=r,this.inSMaskMode&&(this.suspendedCtx=r),!0}#f(t){if(!t)return;let e=this.#i,i=this.#s,s=this.#r,r=e.context;this.#i=null,this.#s=null,this.#r=null,this.inSMaskMode&&this.suspendedCtx===r&&this.ctx!==r&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=s),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#n,this.#n=null,Dr(this.ctx,i),this.ctx=i;let n=this.#l;this.#l=null;let a=this.#a;this.#a=1;try{this.#g(s??i,e.canvas,{backdropCanvas:n?.backdropCtx?.canvas??null,backdropOffset:n?.backdropCtx?[n.offsetX,n.offsetY]:[0,0],reuseMaskEntry:n?.knockoutMaskEntry??null,poolMeta:n,knockoutAlpha:a})}finally{r.restore(),this.#e--,n||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let e=this.current.activeSMask,i=this.suspendedCtx,s=this.#e>0&&i===this.ctx;this.composeSMask(s?null:i,e,this.ctx,t),!s&&(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,i,s){let r=s[0],n=s[1],a=s[2]-r,o=s[3]-n;if(0===a||0===o)return;let l=this.smaskPreparedEntry;if(l){let t=r,s=n,h=a,d=o,c=this.smaskPreparedOOBAlpha,u=null!==c;if(u){t=Math.max(r,e.offsetX),s=Math.max(n,e.offsetY),h=Math.min(r+a,e.offsetX+e.canvas.width)-t,d=Math.min(n+o,e.offsetY+e.canvas.height)-s}if(h>0&&d>0){let e=t-this.smaskPreparedOffsetX,r=s-this.smaskPreparedOffsetY;i.save(),i.globalAlpha=1,i.setTransform(1,0,0,1,0,0);let n=new Path2D;n.rect(t,s,h,d),i.clip(n),i.globalCompositeOperation="destination-in",i.drawImage(l.canvas,e,r,h,d,t,s,h,d),i.restore()}u&&c<255&&this._applySMaskOOBAlpha(i,r,n,a,o,t,s,t+h,s+d,c)}else this.genericComposeSMask(e,i,a,o,r,n);t&&(t.save(),t.globalAlpha=1,t.globalCompositeOperation=e.blendMode||"source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,r,n,a,o,r,n,a,o),t.restore())}_applySMaskOOBAlpha(t,e,i,s,r,n,a,o,l,h){let d=n<o&&a<l;if(d&&n===e&&a===i&&o===e+s&&l===i+r)return;let c=new Path2D;c.rect(e,i,s,r),d&&c.rect(n,a,o-n,l-a),t.save(),t.globalAlpha=h/255,t.setTransform(1,0,0,1,0,0),t.clip(c,"evenodd"),t.globalCompositeOperation="destination-in",t.fillStyle="#000000",t.fillRect(e,i,s,r),t.restore()}genericComposeSMask(t,e,i,s,r,n){let{context:a,offsetX:o,offsetY:l}=t;e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);let h=new Path2D;h.rect(r,n,i,s),e.clip(h),e.globalCompositeOperation="destination-in",e.drawImage(a.canvas,r-o,n-l,i,s,r,n,i,s),e.restore()}save(t){this.inSMaskMode&&Dr(this.ctx,this.suspendedCtx),this.ctx.save();let e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(Dr(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(t),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,r,n,a){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,i,s,r,n,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,s){let[r]=i;if(!s)return r||=i[0]=new Path2D,e!==Se.stroke&&e!==Se.closeStroke&&(this.current.tilingPatternDims=null),void this[e](t,r);if(null!==this.dependencyTracker){let i=e===Se.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,s[0]-i,s[2]+i,s[1]-i,s[3]+i).recordDependencies(t,["transform"])}r instanceof Path2D||(r=i[0]=Ni(r)),Ke.axialAlignedBoundingBox(s,xi(this.ctx),this.current.minMax);let n=this.current.tilingPatternDims;if(n&&e!==Se.stroke&&e!==Se.closeStroke&&this.current.fillColor instanceof wr){let t=Ke.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,n):this.current.tilingPatternDims=null}this[e](t,r),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){let s=i&&this.#m(this.current.strokeAlpha),r=this.ctx,n=this.current.strokeColor;if(r.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof n&&n?.getPattern){let i=n.isModifyingCurrentTransform()?r.getTransform():null;if(r.save(),r.strokeStyle=n.getPattern(r,this,_i(r),cr,t),i){let t=new Path2D;t.addPath(e,r.getTransform().invertSelf().multiplySelf(i)),e=t}this.rescaleAndStroke(e,!1),r.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,bs),i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(cr,xi(this.ctx))),r.globalAlpha=this.current.fillAlpha,this.#f(s)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){let s=i&&this.#m(this.current.fillAlpha),r=this.ctx,n=this.current.fillColor,a=this.current.patternFill,o=!1,l=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(t,vs),a){let a=this.current.tilingPatternDims,h=a&&n.canSkipPatternCanvas(a);if(h)return n.drawPattern(this,e,this.pendingEOFill,h,t),this.pendingEOFill=!1,i&&this.consumePath(t,e,l),this.current.tilingPatternDims=null,void this.#f(s);let d=n.isModifyingCurrentTransform()?r.getTransform():null;if(this.dependencyTracker?.save(t),r.save(),r.fillStyle=n.getPattern(r,this,_i(r),dr,t),d){let t=new Path2D;t.addPath(e,r.getTransform().invertSelf().multiplySelf(d)),e=t}o=!0}this.contentVisible&&null!==l&&(this.pendingEOFill?(r.fill(e,"evenodd"),this.pendingEOFill=!1):r.fill(e)),o&&(r.restore(),this.dependencyTracker?.restore(t)),i&&this.consumePath(t,e,l),this.#f(s)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){let i=this.#m(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e),this.#f(i)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){let i=this.#m(this.current.fillAlpha);this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,As).recordOperation(t),this.#f(i)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Rr}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=Nr}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){let e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){let{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(void 0!==e){let t=new Path2D,s=i.getTransform().invertSelf();for(let{transform:i,x:r,y:n,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(s).translate(r,n).scale(a,-a));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);let s=this.commonObjs.get(e),r=this.current;if(!s)throw new Error(`Can't find font for ${e}`);if(r.fontMatrix=s.fontMatrix||Xt,(0===r.fontMatrix[0]||0===r.fontMatrix[3])&&Le("Invalid font matrix for font "+e),i<0?(i=-i,r.fontDirection=-1):r.fontDirection=1,this.current.font=s,this.current.fontSize=i,s.isType3Font)return;let n=s.loadedName||"sans-serif",a=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`,o="normal";s.black?o="900":s.bold&&(o="bold");let l=s.italic?"italic":"normal",h=i;i<16?h=16:i>100&&(h=100),this.current.fontSizeScale=i/h,this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i),this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);let{current:i}=this;i.textMatrix=e,i.textMatrixScale=Math.hypot(e[0],e[1]),i.x=i.lineX=0,i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#b(t,e,i){let s=new Path2D;return s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),s}paintChar(t,e,i,s,r,n){let a,o=this.ctx,l=this.current,h=l.font,d=l.textRenderingMode,c=l.fontSize/l.fontSizeScale,u=d&ge,p=!!(d&me),g=l.patternFill&&!h.missingFile,m=l.patternStroke&&!h.missingFile;if((h.disableFontFace||p||g||m)&&!h.missingFile&&(a=h.getPathGenerator(this.commonObjs,e)),a&&(h.disableFontFace||g||m)){let e;if(o.save(),o.translate(i,s),o.scale(c,-c),this.dependencyTracker?.recordCharacterBBox(t,o,h),u===de||u===ue)if(r){e=o.getTransform(),o.setTransform(...r);let t=this.#b(a,e,r);o.fill(t)}else o.fill(a);if(u===ce||u===ue)if(n){e||=o.getTransform(),o.setTransform(...n);let{a:t,b:i,c:s,d:r}=e,l=Ke.inverseTransform(n),h=Ke.transform([t,i,s,r,0,0],l);Ke.singularValueDecompose2dScale(h,Cr),o.lineWidth*=Math.max(Cr[0],Cr[1])/c,o.stroke(this.#b(a,e,n))}else o.lineWidth/=c,o.stroke(a);o.restore()}else(u===de||u===ue)&&(o.fillText(e,i,s),this.dependencyTracker?.recordCharacterBBox(t,o,h,c,i,s,()=>o.measureText(e))),(u===ce||u===ue)&&(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,o,h,c,i,s,()=>o.measureText(e)).recordDependencies(t,bs),o.strokeText(e,i,s));p&&((this.pendingTextPaths||=[]).push({transform:xi(o),x:i,y:s,fontSize:c,path:a}),this.dependencyTracker?.recordCharacterBBox(t,o,h,c,i,s))}get isFontSubpixelAAEnabled(){let t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1),e.fillText("I",0,10);let i=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let s=!1;for(let t=3;t<i.length;t+=4)if(i[t]>0&&i[t]<255){s=!0;break}return He(this,"isFontSubpixelAAEnabled",s)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,ws).resetBBox(t),this.current.textRenderingMode&me&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());let i=this.current,s=i.font;if(s.isType3Font){let s=this.#m(i.fillAlpha);return this.showType3Text(t,e),this.dependencyTracker?.recordShowTextOperation(t),void this.#f(s)}let r=i.fontSize;if(0===r)return void this.dependencyTracker?.recordOperation(t);let n=this.#m(i.fillAlpha),a=this.ctx,o=i.fontSizeScale,l=i.charSpacing,h=i.wordSpacing,d=i.fontDirection,c=i.textHScale*d,u=e.length,p=s.vertical,g=p?1:-1,m=s.defaultVMetrics,f=r*i.fontMatrix[0],b=i.textRenderingMode===de&&!s.disableFontFace&&!i.patternFill;a.save(),i.textMatrix&&a.transform(...i.textMatrix),a.translate(i.x,i.y+i.textRise),d>0?a.scale(c,-1):a.scale(c,1);let v,y,A=i.textRenderingMode&ge,w=A===de||A===ue,x=A===ce||A===ue,_=i.lineWidth,S=i.textMatrixScale;if(0===S||0===_?x&&(_=this.getSinglePixelWidth()):_/=S,1!==o&&(a.scale(o,o),_/=o),a.lineWidth=_,w&&i.patternFill){a.save();let e=i.fillColor.getPattern(a,this,_i(a),dr,t);v=xi(a),a.restore(),a.fillStyle=e}if(x&&i.patternStroke){a.save();let e=i.strokeColor.getPattern(a,this,_i(a),cr,t);y=xi(a),a.restore(),a.strokeStyle=e}if(s.isInvalidPDFjsFont){let s=[],r=0;for(let t of e)s.push(t.unicode),r+=t.width;let o=s.join("");if(a.fillText(o,0,0),null!==this.dependencyTracker){let e=a.measureText(o);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return i.x+=r*f*c,a.restore(),this.compose(),void this.#f(n)}let C,E=0;for(C=0;C<u;++C){let i=e[C];if("number"==typeof i){E+=g*i*r/1e3;continue}let n,c,u,A=!1,w=(i.isSpace?h:0)+l,x=i.fontChar,_=i.accent,S=i.width;if(p){let t=i.vmetric||m,e=-(i.vmetric?t[1]:.5*S)*f,s=t[2]*f;S=t?-t[0]:S,n=e/o,c=(E+s)/o}else n=E/o,c=0;if(s.remeasure&&S>0){u=a.measureText(x);let t=1e3*u.width/r*o;if(S<t&&this.isFontSubpixelAAEnabled){let e=S/t;A=!0,a.save(),a.scale(e,1),n/=e}else S!==t&&(n+=(S-t)/2e3*r/o)}if(this.contentVisible&&(i.isInFont||s.missingFile))if(b&&!_)a.fillText(x,n,c),this.dependencyTracker?.recordCharacterBBox(t,a,u?{bbox:null}:s,r/o,n,c,()=>u??a.measureText(x));else if(this.paintChar(t,x,n,c,v,y),_){let e=n+r*_.offset.x/o,i=c-r*_.offset.y/o;this.paintChar(t,_.fontChar,e,i,v,y)}E+=p?S*f-w*d:S*f+w*d,A&&a.restore()}p?i.y-=E:i.x+=E*c,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t),this.#f(n)}showType3Text(t,e){let i,s,r,n,a=this.ctx,o=this.current,l=o.font,h=o.fontSize,d=o.fontDirection,c=l.vertical?1:-1,u=o.charSpacing,p=o.wordSpacing,g=o.textHScale*d,m=o.fontMatrix||Xt,f=e.length;if(o.textRenderingMode===pe||0===h)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,a.save(),o.textMatrix&&a.transform(...o.textMatrix),a.translate(o.x,o.y+o.textRise),a.scale(g,d);let b=this.dependencyTracker;for(this.dependencyTracker=b?new fs(b,t):null,i=0;i<f;++i){if(s=e[i],"number"==typeof s){n=c*s*h/1e3,this.ctx.translate(n,0),o.x+=n*g;continue}let t=(s.isSpace?p:0)+u,d=l.charProcOperatorList[s.operatorListId];d?this.contentVisible&&(this.save(),a.scale(h,h),a.transform(...m),this.executeOperatorList(d),this.restore()):Le(`Type3 character "${s.operatorListId}" is not available.`);let f=[s.width,0];Ke.applyTransform(f,m),r=f[0]*h+t,a.translate(r,0),o.x+=r*g}a.restore(),b&&(this.dependencyTracker=b)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,s,r,n,a){let o=new Path2D;o.rect(s,r,n-s,a-r),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,s,n,r,a).recordClipBox(t,this.ctx,s,n,r,a),this.endPath(t)}getColorN_Pattern(e,i){let s;if("TilingPattern"===i[0]){let e=this.baseTransform||xi(this.ctx),r={createCanvasGraphics:(e,i)=>new t(e,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new fs(this.dependencyTracker,i,!0):null)};s=new wr(i,this.ctx,r,e)}else s=this._getPattern(e,i[1],i[2]);return s}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);let i=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0,this.current.tilingPatternDims=i instanceof wr?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(t,e,i=null){let s;return this.cachedPatterns.has(e)?s=this.cachedPatterns.get(e):(s=function(t){switch(t[0]){case"RadialAxial":return new mr(t);case"Mesh":return new br(t);case"Dummy":return new vr}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e)),this.cachedPatterns.set(e,s)),i&&(s.matrix=i),s}shadingFill(t,e){if(!this.contentVisible)return;let i=this.#m(this.current.fillAlpha),s=this.ctx;this.save(t);let r=this._getPattern(t,e);s.fillStyle=r.getPattern(s,this,_i(s),ur,t);let n=_i(s);if(n){let{width:t,height:e}=s.canvas,i=Wt.slice();Ke.axialAlignedBoundingBox([0,0,t,e],n,i);let[r,a,o,l]=i;this.ctx.fillRect(r,a,o-r,l-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,xs).recordDependencies(t,vs).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t),this.#f(i)}beginInlineImage(){Oe("Should not call beginInlineImage")}beginImageData(){Oe("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=xi(this.ctx),i)){Ke.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);let[e,s,r,n]=i,a=new Path2D;a.rect(e,s,r-e,n-s),this.ctx.clip(a),this.dependencyTracker?.recordClipBox(t,this.ctx,e,r,s,n),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);let{inSMaskMode:i}=this;i&&(this.endSMaskMode(),this.current.activeSMask=null);let s=this.ctx;if(!e.isolated&&!e.knockout&&0===this.#t&&Fe("TODO: Fully support non-isolated non-knockout groups."),!e.needsIsolation&&!e.knockout&&0===this.#t&&1===s.globalAlpha&&"source-over"===s.globalCompositeOperation&&!i){if(e.bbox){let t=new Path2D,[i,r,n,a]=e.bbox;if(t.rect(i,r,n-i,a-r),e.matrix){let i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix)),t=i}s.clip(t)}return this.groupStack.push(null),this.#h.push(null),void this.groupLevel++}let r=xi(s);e.matrix&&s.transform(...e.matrix);let n,a=[0,0,s.canvas.width,s.canvas.height];e.bbox?(n=Wt.slice(),Ke.axialAlignedBoundingBox(e.bbox,xi(s),n),n=Ke.intersect(n,a)||[0,0,0,0]):n=a;let o=Math.floor(n[0]),l=Math.floor(n[1]),h=Math.max(Math.ceil(n[2])-o,1),d=Math.max(Math.ceil(n[3])-l,1);this.current.startNewPathAndClipBox([0,0,h,d]);let c=this.canvasFactory.create(h,d);e.smask&&this.smaskGroupCanvases.push(c);let u=c.context,p=e.knockout&&!e.isolated?s:null,g=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#t>0,m=e.knockout?this.canvasFactory.create(h,d):null,f=this.#t;if(e.knockout?this.#t++:this.#t=0,u.translate(-o,-l),u.transform(...r),!e.isolated&&!e.smask&&i&&e.needsIsolation&&(u.save(),u.setTransform(1,0,0,1,0,0),u.drawImage(s.canvas,-o,-l),u.restore()),e.bbox){let t=new Path2D,[i,s,r,n]=e.bbox;if(t.rect(i,s,r-i,n-s),e.matrix){let i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix)),t=i}u.clip(t)}e.smask&&this.smaskStack.push({canvas:c.canvas,context:u,offsetX:o,offsetY:l,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null}),(!e.smask||this.dependencyTracker)&&(s.setTransform(1,0,0,1,0,0),s.translate(o,l),s.save()),Dr(s,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(s),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(s),this.#h.push({backdropCtx:p,savedKnockoutLevel:f,offsetX:o,offsetY:l,hasInnerBackdrop:g,knockoutMaskEntry:m,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;let i=this.ctx,s=this.groupStack.pop(),r=this.#h.pop();if(r&&(this.#t=r.savedKnockoutLevel),null!==s)if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())),this.#v(r);else{this.ctx.restore();let e=xi(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);let n=Wt.slice();Ke.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n);let a=this.#h.at(-1);if(this.#t>0)if(r.hasInnerBackdrop){let{width:t,height:n}=i.canvas,a=this.canvasFactory.create(t,n),o=a.context;o.drawImage(s.canvas,r.offsetX,r.offsetY,t,n,0,0,t,n),o.globalCompositeOperation="source-over",o.drawImage(i.canvas,0,0);let l=this.#u(i.canvas);o.globalCompositeOperation="destination-in",o.drawImage(l.canvas,0,0);let h=this.ctx.globalCompositeOperation,d=this.ctx.globalAlpha,c=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...e),this.ctx.globalAlpha=1,qe.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(l.canvas,0,0),this.ctx.globalCompositeOperation=h,this.ctx.globalAlpha=d,qe.isCanvasFilterSupported&&(this.ctx.filter=c??"none"),this.ctx.drawImage(a.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(l),this.canvasFactory.destroy(a)}else{let t=a?.backdropCtx??null;this.#g(this.ctx,i.canvas,{backdropCanvas:t?.canvas??null,destTransform:e,backdropOffset:t?[a.offsetX+r.offsetX,a.offsetY+r.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(i.canvas,0,0);this.ctx.restore(),this.canvasFactory.destroy({canvas:i.canvas,context:i}),this.#v(r),this.compose(n)}else this.restore(t)}#v(t){t&&(t.knockoutMaskEntry&&(this.canvasFactory.destroy(t.knockoutMaskEntry),t.knockoutMaskEntry=null),t.knockoutTempEntry&&(this.canvasFactory.destroy(t.knockoutTempEntry),t.knockoutTempEntry=null),t.knockoutBackdropEntry&&(this.canvasFactory.destroy(t.knockoutBackdropEntry),t.knockoutBackdropEntry=null))}beginAnnotation(t,e,i,s,r,n){if(this.#d(),Ir(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),i){let r=i[2]-i[0],a=i[3]-i[1];if(n&&this.annotationCanvasMap){(s=s.slice())[4]-=i[0],s[5]-=i[1],(i=i.slice())[0]=i[1]=0,i[2]=r,i[3]=a,Ke.singularValueDecompose2dScale(xi(this.ctx),Cr);let{viewportScale:t}=this,n=Math.ceil(r*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(n,o);let{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(Cr[0],0,0,-Cr[1],0,a*Cr[1]),Ir(this.ctx)}else{Ir(this.ctx),this.endPath(t);let e=new Path2D;e.rect(i[0],i[1],r,a),this.ctx.clip(e)}}this.current=new Tr(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(t,...s),this.transform(t,...r),this.baseTransform=xi(this.ctx)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#c(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;let i=e.count;(e=this.getObject(t,e.data,e)).count=i;let s=this.#m(this.current.fillAlpha),r=this.ctx,n=this._createMaskCanvas(t,e),a=n.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(a,n.offsetX,n.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,n.offsetX,n.offsetX+a.width,n.offsetY,n.offsetY+a.height).recordOperation(t),r.restore(),n.canvasEntry&&this.canvasFactory.destroy(n.canvasEntry),this.compose(),this.#f(s)}paintImageMaskXObjectRepeat(t,e,i,s=0,r=0,n,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);let o=this.#m(this.current.fillAlpha),l=this.ctx;l.save();let h=xi(l);l.transform(i,s,r,n,0,0);let d=this._createMaskCanvas(t,e);l.setTransform(1,0,0,1,d.offsetX-h[4],d.offsetY-h[5]),this.dependencyTracker?.resetBBox(t);for(let e=0,o=a.length;e<o;e+=2){let o=Ke.transform(h,[i,s,r,n,a[e],a[e+1]]);l.drawImage(d.canvas,o[4],o[5]),this.dependencyTracker?.recordBBox(t,this.ctx,o[4],o[4]+d.canvas.width,o[5],o[5]+d.canvas.height)}l.restore(),d.canvasEntry&&this.canvasFactory.destroy(d.canvasEntry),this.compose(),this.dependencyTracker?.recordOperation(t),this.#f(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;let i=this.#m(this.current.fillAlpha),s=this.ctx,r=this.current.fillColor,n=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,_s);for(let i of e){let{data:e,width:a,height:o,transform:l}=i,h=this.canvasFactory.create(a,o),d=h.context;d.save(),Pr(d,this.getObject(t,e,i)),d.globalCompositeOperation="source-in",d.fillStyle=n?r.getPattern(d,this,_i(s),dr,t):r,d.fillRect(0,0,a,o),d.restore(),s.save(),s.transform(...l),s.scale(1,-1),kr(s,h.canvas,0,0,a,o,0,-1,1,1),this.canvasFactory.destroy(h),this.dependencyTracker?.recordBBox(t,s,0,a,0,o),s.restore()}this.compose(),this.dependencyTracker?.recordOperation(t),this.#f(i)}paintImageXObject(t,e){if(!this.contentVisible)return;let i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):Le("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,s,r){if(!this.contentVisible)return;let n=this.getObject(t,e);if(!n)return void Le("Dependent image isn't ready yet");let a=n.width,o=n.height,l=[];for(let t=0,e=r.length;t<e;t+=2)l.push({transform:[i,0,0,s,r[t],r[t+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(t,n,l)}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{img:t.bitmap,canvasEntry:null};let{bitmap:e,width:i,height:s}=t,r=this.canvasFactory.create(i,s),n=r.context;return n.filter=this.current.transferMaps,n.drawImage(e,0,0),n.filter="none",{img:r.canvas,canvasEntry:r}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;let i=e.width,s=e.height,r=this.#m(this.current.fillAlpha),n=this.ctx;this.save(t);let{filter:a}=n;"none"!==a&&""!==a&&(n.filter="none"),n.scale(1/i,-1/s);let o,l=null;if(e.bitmap){let t=this.applyTransferMapsToBitmap(e);o=t.img,l=t.canvasEntry}else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)o=e;else{let t=this.canvasFactory.create(i,s);Mr(t.context,e),o=this.applyTransferMapsToCanvas(t.context),l=t}let h=this._scaleImage(o,_i(n));n.imageSmoothingEnabled=Fr(xi(n),e.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(t).recordBBox(t,n,0,i,-s,0).recordDependencies(t,ys).recordOperation(t),this.imagesTracker?.record(n,i,s,this.dependencyTracker.clipBox)),kr(n,h.img,0,0,h.paintWidth,h.paintHeight,0,-s,i,s),h.tmpCanvas&&this.canvasFactory.destroy(h.tmpCanvas),l&&this.canvasFactory.destroy(l),this.compose(),this.restore(t),this.#f(r)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;let s,r=this.#m(this.current.fillAlpha),n=this.ctx,a=null;if(e.bitmap)s=e.bitmap;else{let t=e.width,i=e.height,r=this.canvasFactory.create(t,i);Mr(r.context,e),s=this.applyTransferMapsToCanvas(r.context),a=r}this.dependencyTracker?.resetBBox(t);for(let e of i)n.save(),n.transform(...e.transform),n.scale(1,-1),kr(n,s,e.x,e.y,e.w,e.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();a&&this.canvasFactory.destroy(a),this.dependencyTracker?.recordOperation(t),this.compose(),this.#f(r)}paintSolidColorImageMask(t){if(!this.contentVisible)return;let e=this.#m(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,vs).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose(),this.#f(e)}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){let s=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(i);let r=this.ctx;this.pendingClip?(s||(this.pendingClip===Nr?r.clip(e,"evenodd"):r.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let t=xi(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{let e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),s=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,s)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){let t,e,{lineWidth:i}=this.current,{a:s,b:r,c:n,d:a}=this.ctx.getTransform();if(0===r&&0===n){let r=Math.abs(s),n=Math.abs(a);if(r===n)if(0===i)t=e=1/r;else{let s=r*i;t=e=s<1?1/s:1}else if(0===i)t=1/r,e=1/n;else{let s=r*i,a=n*i;t=s<1?1/s:1,e=a<1?1/a:1}}else{let o=Math.abs(s*a-r*n),l=Math.hypot(s,r),h=Math.hypot(n,a);if(0===i)t=h/o,e=l/o;else{let s=i*o;t=h>s?h/s:1,e=l>s?l/s:1}}this._cachedScaleForStroking[0]=t,this._cachedScaleForStroking[1]=e}return this._cachedScaleForStroking}rescaleAndStroke(t,e){let{ctx:i,current:{lineWidth:s}}=this,[r,n]=this.getScaleForStroking();if(r===n)return i.lineWidth=(s||1)*r,void i.stroke(t);let a=i.getLineDash();e&&i.save(),i.scale(r,n),Sr.a=1/r,Sr.d=1/n;let o=new Path2D;if(o.addPath(t,Sr),a.length>0){let t=Math.max(r,n);i.setLineDash(a.map(e=>e/t)),i.lineDashOffset/=t}i.lineWidth=s||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};for(let t in Se)void 0!==Br.prototype[t]&&(Br.prototype[Se[t]]=Br.prototype[t]);var Ur=class{#t=null;#e=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t,this.#t=e,this.#e=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return Re(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#t(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;let i=new this.#e(this,t,e);return this._rangeReaders.add(i),i}cancelAllRequests(t){this._fullReader?.cancel(t);for(let e of new Set(this._rangeReaders))e.cancel(t)}},Hr=class{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}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(){Oe("Abstract method `read` called")}cancel(t){Oe("Abstract method `cancel` called")}},jr=class{_stream=null;constructor(t,e,i){this._stream=t}async read(){Oe("Abstract method `read` called")}cancel(t){Oe("Abstract method `cancel` called")}};function $r(t,e){let i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(let t in e){let s=e[t];void 0!==s&&i.append(t,s)}return i}function Gr(t){return URL.parse(t)?.origin??null}function zr({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){let r={contentLength:0,isRangeSupported:!1},n=parseInt(t.get("Content-Length"),10);return!Number.isInteger(n)||(r.contentLength=n,n<=2*i)||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"===(t.get("Content-Encoding")||"identity")&&(r.isRangeSupported=!0),r}function Vr(t){let e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){i=i[1];let t=a(i);return t=unescape(t),t=o(t),t=l(t),n(t)}if(i=function(t){let e,i=[],r=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(e=r.exec(t));){let[,t,s,r]=e;if(t=parseInt(t,10),t in i){if(0===t)break}else i[t]=[s,r]}let n=[];for(let t=0;t<i.length&&t in i;++t){let[e,s]=i[t];s=a(s),e&&(s=unescape(s),0===t&&(s=o(s))),n.push(s)}return n.join("")}(t),i)return n(l(i));if(i=s("filename","i").exec(t),i){i=i[1];let t=a(i);return t=l(t),n(t)}function s(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function r(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{let s=new TextDecoder(t,{fatal:!0}),r=Ye(i);i=s.decode(r),e=!1}catch{}}return i}function n(t){return e&&/[\x80-\xff]/.test(t)&&(t=r("utf-8",t),e&&(t=r("iso-8859-1",t))),t}function a(t){if(t.startsWith('"')){let e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){let i=e[t].indexOf('"');-1!==i&&(e[t]=e[t].slice(0,i),e.length=t+1),e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function o(t){let e=t.indexOf("'");return-1===e?t:r(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function l(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(t,e,i,s){if("q"===i||"Q"===i)return r(e,s=(s=s.replaceAll("_"," ")).replaceAll(/=([0-9a-f]{2})/gi,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{s=atob(s)}catch{}return r(e,s)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(ui(t))return t}return null}function Wr(t,e){return new Ve(`Unexpected server response (${t}) while retrieving PDF "${e.href}".`,t,404===t||0===t&&"file:"===e.protocol)}function Xr(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function Yr(t,e,i,s){return fetch(t,{method:"GET",headers:e,signal:s.signal,mode:"cors",credentials:i?"include":"same-origin",redirect:"follow"})}function qr(t,e){if(200!==t&&206!==t)throw Wr(t,e)}function Kr(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}var Qr=class extends Ur{_responseOrigin=null;constructor(t){super(t,Jr,Zr);let{httpHeaders:e,url:i}=t;Re(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=$r(!0,e)}},Jr=class extends Hr{_abortController=new AbortController;_reader=null;constructor(t){super(t);let{disableRange:e,disableStream:i,rangeChunkSize:s,url:r,withCredentials:n}=t._source;this._isStreamingSupported=!i;let a=new Headers(t.headers);Yr(r,a,n,this._abortController).then(i=>{t._responseOrigin=Gr(i.url),qr(i.status,r),this._reader=i.body.getReader();let n=i.headers,{contentLength:a,isRangeSupported:o}=zr({responseHeaders:n,isHttp:!0,rangeChunkSize:s,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Vr(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Xe("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;let{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Kr(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}},Zr=class extends jr{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);let{url:s,withCredentials:r}=t._source,n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`),Yr(s,n,r,this._abortController).then(e=>{Xr(Gr(e.url),t._responseOrigin),qr(e.status,s),this._reader=e.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;let{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Kr(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}};function tn(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function en(){for(let t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}var sn=class extends Ur{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,rn,nn);let{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:s}=e;if(i?.length>0){let t=tn(i);this._queuedChunks.push(t)}this._progressiveDone=s;e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#t(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0}})}#t(t,e){let i=tn(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{let e=this._rangeReaders.keys().find(e=>e._begin===t);Re(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),e._enqueue(i)}}getFullReader(){let t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){let i=super.getRangeReader(t,e);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,e)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}},rn=class extends Hr{#t=en.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);let{pdfDataRangeTransport:e,disableRange:i,disableStream:s}=t._source,{length:r,contentDispositionFilename:n}=e;this._queuedChunks=t._queuedChunks||[];for(let t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone,this._contentLength=r,this._isStreamingSupported=!s,this._isRangeSupported=!i,ui(n)&&(this._filename=n),this._headersCapability.resolve();let a=this._loaded;Promise.resolve().then(()=>{a>0&&this._loaded===a&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t()}progressiveDone(){this._done||=!0,0===this._queuedChunks.length&&this.#t()}},nn=class extends jr{#t=en.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i),this._begin=e}_enqueue(t){this._done||(0===this._requests.length?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),this.#t()),this._done=!0,this.onDone?.())}async read(){if(this._queuedChunk){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t(),this.onDone?.()}};var an=class extends Ur{#t=new WeakMap;_responseOrigin=null;constructor(t){super(t,on,ln);let{httpHeaders:e,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=$r(this.isHttp,e)}_request(t){let e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#t.set(e,i),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(let[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=t=>206===t||200===t):i.validateStatus=t=>200===t,e.responseType="arraybuffer",Re(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#i.bind(this,e),e.onprogress=this.#e.bind(this,e),e.send(null),e}#e(t,e){this.#t.get(t)?.onProgress?.(e)}#i(t,e){let i=this.#t.get(t);if(!i||(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==t.readyState)||!this.#t.has(t))return;if(this.#t.delete(t),0===t.status&&this.isHttp)return void i.onError(t.status);let s=t.status||200;if(!i.validateStatus(s))return void i.onError(t.status);let r=function(t){return"string"!=typeof t?t:Ye(t).buffer}(t.response);if(206===s){let e=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(e)?i.onDone(r):(Le('Missing or invalid "Content-Range" header.'),i.onError(0))}else r?i.onDone(r):i.onError(t.status)}_abortRequest(t){this.#t.has(t)&&(this.#t.delete(t),t.abort())}getRangeReader(t,e){let i=super.getRangeReader(t,e);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}},on=class extends Hr{#t=en.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t),this._fullRequestXhr=t._request({onHeadersReceived:this.#e.bind(this),onDone:this.#i.bind(this),onError:this.#s.bind(this),onProgress:this.#r.bind(this)})}#e(){let t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,s=this._fullRequestXhr;t._responseOrigin=Gr(s.responseURL);let r=s.getAllResponseHeaders(),n=new Headers(r?r.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{let[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{contentLength:a,isRangeSupported:o}=zr({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});this._contentLength=a,this._isRangeSupported=o,this._filename=Vr(n),this._isRangeSupported&&t._abortRequest(s),this._headersCapability.resolve()}#i(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,0===this._cachedChunks.length&&this.#t()}#s(t){this._storedError=Wr(t,this._stream.url),this._headersCapability.reject(this._storedError);for(let t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#r(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),this.#t(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}},ln=class extends jr{#t=en.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i),this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#e.bind(this),onDone:this.#i.bind(this),onError:this.#s.bind(this),onProgress:null})}#e(){let t=Gr(this._requestXhr?.responseURL);try{Xr(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#s(0)}}#i(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,this.#t(),this.onClosed?.()}#s(t){this._storedError??=Wr(t,this._stream.url);for(let t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this.#t(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}};function hn(t,e=null){let i=process.getBuiltinModule("fs"),{Readable:s}=process.getBuiltinModule("stream"),r=i.createReadStream(t,e);return s.toWeb(r)}var dn=class extends Ur{constructor(t){super(t,cn,un);let{url:e}=t;Re("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}},cn=class extends Hr{_reader=null;constructor(t){super(t);let{disableRange:e,disableStream:i,rangeChunkSize:s,url:r}=t._source;this._isStreamingSupported=!i,process.getBuiltinModule("fs/promises").lstat(r).then(t=>{let i=hn(r);this._reader=i.getReader();let{size:n}=t;this._contentLength=n,this._isRangeSupported=!e&&n>2*s,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Xe("Streaming is disabled.")),this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=Wr(0,r)),this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;let{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:Kr(t),done:!1})}cancel(t){this._reader?.cancel(t)}},un=class extends jr{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);let{url:s}=t._source;try{let t=hn(s,{start:e,end:i-1});this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;let{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:Kr(t),done:!1}}cancel(t){this._reader?.cancel(t)}};var pn=class{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#e=t}},gn=class{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}[Symbol.iterator](){return this.#t.entries()}},mn=Symbol("INTERNAL"),fn=class{#t=!1;#e=!1;#i=!1;#s=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:r}){this.#t=!!(t&Qt),this.#e=!!(t&Jt),this.name=e,this.intent=i,this.usage=s,this.rbGroups=r}get visible(){if(this.#i)return this.#s;if(!this.#s)return!1;let{print:t,view:e}=this.usage;return this.#t?"OFF"!==e?.viewState:!this.#e||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==mn&&Oe("Internal method `_setVisible` called."),this.#i=i,this.#s=e}},bn=class{#t=null;#e=new Map;#i=null;#s=null;constructor(t,e=Qt){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#s=t.order;for(let i of t.groups)this.#e.set(i.id,new fn(e,i));if("OFF"===t.baseState)for(let t of this.#e.values())t._setVisible(mn,!1);for(let e of t.on)this.#e.get(e)._setVisible(mn,!0);for(let e of t.off)this.#e.get(e)._setVisible(mn,!1);this.#i=this.getHash()}}#r(t){let e=t.length;if(e<2)return!0;let i=t[0];for(let s=1;s<e;s++){let e,r=t[s];if(Array.isArray(r))e=this.#r(r);else{if(!this.#e.has(r))return Le(`Optional content group not found: ${r}`),!0;e=this.#e.get(r).visible}switch(i){case"And":if(!e)return!1;break;case"Or":if(e)return!0;break;case"Not":return!e;default:return!0}}return"And"===i}isVisible(t){if(0===this.#e.size)return!0;if(!t)return Fe("Optional content group not defined."),!0;if("OCG"===t.type)return this.#e.has(t.id)?this.#e.get(t.id).visible:(Le(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#r(t.expression);if(!t.policy||"AnyOn"===t.policy){for(let e of t.ids){if(!this.#e.has(e))return Le(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(let e of t.ids){if(!this.#e.has(e))return Le(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(let e of t.ids){if(!this.#e.has(e))return Le(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(let e of t.ids){if(!this.#e.has(e))return Le(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Le(`Unknown optional content policy ${t.policy}.`),!0}return Le(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){let s=this.#e.get(t);if(s){if(i&&e&&s.rbGroups.length)for(let e of s.rbGroups)for(let i of e)i!==t&&this.#e.get(i)?._setVisible(mn,!1,!0);s._setVisible(mn,!!e,!0),this.#t=null}else Le(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(let s of t){switch(s){case"ON":case"OFF":case"Toggle":i=s;continue}let t=this.#e.get(s);if(t)switch(i){case"ON":this.setVisibility(s,!0,e);break;case"OFF":this.setVisibility(s,!1,e);break;case"Toggle":this.setVisibility(s,!t.visible,e)}}this.#t=null}get hasInitialVisibility(){return null===this.#i||this.getHash()===this.#i}getOrder(){return this.#e.size?this.#s?this.#s.slice():[...this.#e.keys()]:null}getGroup(t){return this.#e.get(t)||null}getHash(){if(null!==this.#t)return this.#t;let t=new ss;for(let[e,i]of this.#e)t.update(`${e}:${i.visible}`);return this.#t=t.hexdigest()}[Symbol.iterator](){return this.#e.entries()}},vn=class{#t=null;#e=null;#i=0;#s=null;#r=null;get pagesNumber(){return this.#i}set pagesNumber(t){this.#i!==t&&(this.#i=t,this.#t=null,this.#e=null)}#n(){if(this.#t)return;let t=this.#i,e=this.#t=new Uint32Array(t);for(let i=0;i<t;i++)e[i]=i+1;this.#e=new Int32Array(e)}#a(){let t=new Map,e=this.#t;for(let i=0,s=this.#i;i<s;i++){let s=e[i],r=t.get(s);r?r.push(i+1):t.set(s,[i+1])}return t}movePages(t,e,i){this.#n();let s=this.#t,r=this.#a(),n=e.length,a=new Uint32Array(n),o=0;for(let t=0;t<n;t++){let r=e[t]-1;a[t]=s[r],r<i&&o++}let l=this.#i,h=l-n,d=ri(i-o,0,h);for(let e=0,i=0;e<l;e++)t.has(e+1)||(s[i++]=s[e]);s.copyWithin(d+n,d,h),s.set(a,d),this.#o(r),s.every((t,e)=>t===e+1)&&(this.#t=null)}deletePages(t){this.#n();let e=this.#t,i=this.#a();this.#r={pageNumberToId:e.slice(),pagesNumber:this.#i,prevPageNumbers:this.#e.slice()};let s=this.#i-t.length;this.#i=s;let r=this.#t=new Uint32Array(s);this.#e=new Int32Array(s);let n=0,a=0;for(let i of t){let t=i-1;t!==n&&(r.set(e.subarray(n,t),a),a+=t-n),n=t+1}n<e.length&&r.set(e.subarray(n),a),this.#o(i,new Set(t))}cancelDelete(){this.#r&&(this.#t=this.#r.pageNumberToId,this.#i=this.#r.pagesNumber,this.#e=this.#r.prevPageNumbers,this.#r=null)}cleanSavedData(){this.#r=null}copyPages(t){this.#n(),this.#s={pageNumbers:t,pageIds:t.map(t=>this.#t[t-1])}}cancelCopy(){this.#s=null}pastePages(t){this.#n();let e=this.#t,i=this.#a(),{pageNumbers:s,pageIds:r}=this.#s,n=this.#i+s.length;this.#i=n;let a=this.#t=new Uint32Array(n);this.#e=new Int32Array(n),a.set(e.subarray(0,t),0),a.set(r,t),a.set(e.subarray(t),t+s.length),this.#o(i,null,t,s),this.#s=null}#o(t,e=null,i=-1,s=null){let r=this.#e,n=this.#t,a=i+(s?.length??0),o=new Map;for(let l=0,h=this.#i;l<h;l++){if(l>=i&&l<a){r[l]=-s[l-i];continue}let h=n[l],d=t.get(h),c=o.get(h)||0;if(e&&d)for(;c<d.length&&e.has(d[c]);)c++;r[l]=d?.[c],o.set(h,c+1)}}hasBeenAltered(){return null!==this.#t}getPageMappingForSaving(t=null){t??=this.#a();let e=0;for(let i of t.values())e=Math.max(e,i.length);let i=new Array(e);for(let t=0;t<e;t++)i[t]={document:null,pageIndices:[],includePages:[]};for(let[e,s]of t)for(let t=0,r=s.length;t<r;t++)i[t].includePages.push([e-1,s[t]-1]);for(let{includePages:t,pageIndices:e}of i){t.sort((t,e)=>t[0]-e[0]);for(let i=0,s=t.length;i<s;i++)e.push(t[i][1]),t[i]=t[i][0]}return i}extractPages(t){t=Array.from(t).sort((t,e)=>t-e);let e=new Map;for(let i=0,s=t.length;i<s;i++){let s=this.getPageId(t[i]);e.getOrInsertComputed(s,ei).push(i+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#e?.[t-1]??0}getPageNumber(t){if(!this.#t)return t;let e=this.#t;for(let i=0,s=this.#i;i<s;i++)if(e[i]===t)return i+1;return 0}getPageId(t){return this.#t?.[t-1]??t}getMapping(){return this.#t?.subarray(0,this.pagesNumber)}},yn=Symbol("INITIAL_DATA"),An=()=>({...Promise.withResolvers(),data:yn}),wn=class{#t=new Map;get(t,e=null){if(e){let i=this.#t.getOrInsertComputed(t,An);return i.promise.then(()=>e(i.data)),null}let i=this.#t.get(t);if(!i||i.data===yn)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){let e=this.#t.get(t);return!!e&&e.data!==yn}delete(t){let e=this.#t.get(t);return!(!e||e.data===yn)&&(this.#t.delete(t),!0)}resolve(t,e=null){let i=this.#t.getOrInsertComputed(t,An);if(i.data!==yn)throw new Error(`Object already resolved ${t}.`);i.data=e,i.resolve()}clear(){for(let{data:t}of this.#t.values())t?.bitmap?.close();this.#t.clear()}*[Symbol.iterator](){for(let[t,{data:e}]of this.#t)e!==yn&&(yield[t,e])}},xn=class t{#t=Promise.withResolvers();#e=null;#i=!1;#s=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#a=null;#o=0;#l=0;#h=null;#d=null;#c=0;#u=0;#p=Object.create(null);#g=[];#m=null;#f=[];#b=new WeakMap;#v=null;static#y=new Map;static#A=new Map;static#w=new WeakMap;static#x=null;static#_=new Set;constructor({textContentSource:e,images:i,container:s,viewport:r}){if(e instanceof ReadableStream)this.#m=e;else{if("object"!=typeof e)throw new Error('No "textContentSource" parameter specified.');this.#m=new ReadableStream({start(t){t.enqueue(e),t.close()}})}this.#e=this.#d=s,this.#r=i,this.#u=r.scale*Ci.pixelRatio,this.#c=r.rotation,this.#a={div:null,properties:null,ctx:null};let{pageWidth:n,pageHeight:a,pageX:o,pageY:l}=r.rawDims;this.#v=[1,0,0,-1,-o,l+a],this.#l=n,this.#o=a,t.#M(),s.style.setProperty("--min-font-size",t.#x),Si(s,r),this.#t.promise.finally(()=>{t.#_.delete(this),this.#a=null,this.#p=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:t,isFirefox:e}=qe.platform;return He(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){this.#r&&this.#e.append(this.#r.render());let e=()=>{this.#h.read().then(({value:t,done:i})=>{i?this.#t.resolve():(this.#n??=t.lang,Object.assign(this.#p,t.styles),this.#S(t.items),e())},this.#t.reject)};return this.#h=this.#m.getReader(),t.#_.add(this),e(),this.#t.promise}update({viewport:e,onBefore:i=null}){let s=e.scale*Ci.pixelRatio,r=e.rotation;if(r!==this.#c&&(i?.(),this.#c=r,Si(this.#d,{rotation:r})),s!==this.#u){i?.(),this.#u=s;let e={div:null,properties:null,ctx:t.#k(this.#n)};for(let t of this.#f)e.properties=this.#b.get(t),e.div=t,this.#E(e)}}cancel(){let t=new Xe("TextLayer task cancelled.");this.#h?.cancel(t).catch(()=>{}),this.#h=null,this.#t.reject(t)}get textDivs(){return this.#f}get textContentItemsStr(){return this.#g}#S(e){if(this.#i)return;this.#a.ctx??=t.#k(this.#n);let i=this.#f,s=this.#g;for(let t of e){if(i.length>1e5)return Le("Ignoring additional textDivs for performance reasons."),void(this.#i=!0);if(void 0!==t.str)s.push(t.str),this.#C(t);else if("beginMarkedContentProps"===t.type||"beginMarkedContent"===t.type){let e=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),t.id&&this.#e.setAttribute("id",`${t.id}`),"Artifact"===t.tag&&(this.#e.ariaHidden=!0),e.append(this.#e)}else"endMarkedContent"===t.type&&(this.#e=this.#e.parentNode)}}#C(e){let i=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:""!==e.str,hasEOL:e.hasEOL,fontSize:0};this.#f.push(i);let r=Ke.transform(this.#v,e.transform),n=Math.atan2(r[1],r[0]),a=this.#p[e.fontName];a.vertical&&(n+=Math.PI/2);let o=this.#s&&a.fontSubstitution||a.fontFamily;o=t.fontFamilyMap.get(o)||o;let l,h,d=Math.hypot(r[2],r[3]),c=d*t.#P(o,a,this.#n);0===n?(l=r[4],h=r[5]-c):(l=r[4]+c*Math.sin(n),h=r[5]-c*Math.cos(n));let u=i.style;u.left=`${(100*l/this.#l).toFixed(2)}%`,u.top=`${(100*h/this.#o).toFixed(2)}%`,u.setProperty("--font-height",`${d.toFixed(2)}px`),u.fontFamily=o,s.fontSize=d,i.setAttribute("role","presentation"),i.textContent=e.str,i.dir=e.dir,this.#s&&(i.dataset.fontName=a.fontSubstitutionLoadedName||e.fontName),0!==n&&(s.angle=n*(180/Math.PI));let p=!1;if(e.str.length>1)p=!0;else if(" "!==e.str&&e.transform[0]!==e.transform[3]){let t=Math.abs(e.transform[0]),i=Math.abs(e.transform[3]);t!==i&&Math.max(t,i)/Math.min(t,i)>1.5&&(p=!0)}if(p&&(s.canvasWidth=a.vertical?e.height:e.width),this.#b.set(i,s),this.#a.div=i,this.#a.properties=s,this.#E(this.#a),s.hasText&&this.#e.append(i),s.hasEOL){let t=document.createElement("br");t.setAttribute("role","presentation"),this.#e.append(t)}}#E(e){let{div:i,properties:s,ctx:r}=e,{style:n}=i;if(0!==s.canvasWidth&&s.hasText){let{fontFamily:e}=n,{canvasWidth:a,fontSize:o}=s;t.#T(r,o*this.#u,e);let{width:l}=r.measureText(i.textContent);l>0&&n.setProperty("--scale-x",a*this.#u/l)}0!==s.angle&&n.setProperty("--rotate",`${s.angle}deg`)}static cleanup(){if(!(this.#_.size>0)){this.#y.clear();for(let{canvas:t}of this.#A.values())t.remove();this.#A.clear()}}static#k(t=null){let e=this.#A.get(t||="");if(!e){let i=document.createElement("canvas");i.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#A.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,i){let s=this.#w.get(t);e===s.size&&i===s.family||(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static#M(){if(null!==this.#x)return;let t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#x=t.getBoundingClientRect().height,t.remove()}static#P(t,e,i){let s=this.#y.get(t);if(s)return s;let r=this.#k(i);r.canvas.width=r.canvas.height=30,this.#T(r,30,t);let n=r.measureText(""),a=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);r.canvas.width=r.canvas.height=0;let l=.8;return a?l=a/(a+o):(qe.platform.isFirefox&&Le("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#y.set(t,l),l}};function _n(t={}){let e=new Sn,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t;if("string"==typeof t){if(zt){if(/^[a-z][a-z0-9\-+.]+:/i.test(t))return new URL(t);let e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}let e=URL.parse(t,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,r=t.data?function(t){if(zt&&typeof Buffer<"u"&&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 Ye(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,n=t.httpHeaders||null,a=!0===t.withCredentials,o=t.password??null,l=t.range instanceof Cn?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536,d=t.worker instanceof Tn?t.worker:null,c=t.verbosity,u="string"!=typeof t.docBaseUrl||ci(t.docBaseUrl)?null:t.docBaseUrl,p=Rs(t.cMapUrl),g=!1!==t.cMapPacked,m=Rs(t.iccUrl),f=Rs(t.standardFontDataUrl),b=Rs(t.wasmUrl),v=!0!==t.stopAtErrors,y=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,A="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!zt,w="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!zt,x=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,_="boolean"==typeof t.disableFontFace?t.disableFontFace:zt,S=!0===t.fontExtraProperties,C=!0===t.enableXfa,E=t.ownerDocument||globalThis.document,k=!0===t.disableRange,T=!0===t.disableStream,M=!0===t.disableAutoFetch,P=!0===t.pdfBug,D=t.CanvasFactory||(zt?or:ir),I=t.FilterFactory||(zt?ar:rr),F=t.BinaryDataFactory||(zt?lr:tr),L=!0===t.enableHWA,O=!0===t.enableWebGPU?hr.init():Promise.resolve(!1),R=!1!==t.useWasm,N=t.pagesMapper||new vn,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!zt&&!_,U="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(F===tr&&p&&g&&f&&b&&fi(p,document.baseURI)&&fi(f,document.baseURI)&&fi(b,document.baseURI));!function(t){Number.isInteger(t)&&(De=t)}(c);let H={canvasFactory:new D({ownerDocument:E,enableHWA:L}),filterFactory:new I({docId:i,ownerDocument:E}),binaryDataFactory:U?null:new F({cMapUrl:p,standardFontDataUrl:f,wasmUrl:b})};d||(d=Tn.create({verbosity:c,port:pn.workerPort}),e._worker=d);let j={docId:i,apiVersion:"6.0.227",data:r,password:o,disableAutoFetch:M,rangeChunkSize:h,docBaseUrl:u,enableXfa:C,evaluatorOptions:{maxImageSize:y,disableFontFace:_,ignoreErrors:v,isOffscreenCanvasSupported:A,isImageDecoderSupported:w,canvasMaxAreaInBytes:x,fontExtraProperties:S,useSystemFonts:B,useWasm:R,useWorkerFetch:U,cMapUrl:p,cMapPacked:g,iccUrl:m,standardFontDataUrl:f,wasmUrl:b,hasGPU:!1}},$={ownerDocument:E,pdfBug:P,styleElement:null,enableHWA:L,loadingParams:{disableAutoFetch:M,enableXfa:C}};return Promise.all([d.promise,O]).then(function([,t]){if(d.destroyed)throw new Error("Worker was destroyed");j.evaluatorOptions.hasGPU=t;let o,c=d.messageHandler.sendWithPromise("GetDocRequest",j,r?[r.buffer]:null);if(!r)if(l)o=new sn({pdfDataRangeTransport:l,disableRange:k,disableStream:T});else{if(!s)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{let t=function(t){return fi(t)?Qr:zt?dn:an}(s);o=new t({url:s,httpHeaders:n,withCredentials:a,rangeChunkSize:h,disableRange:k,disableStream:T})}}return c.then(t=>{if(d.destroyed)throw new Error("Worker was destroyed");let s=new Js(i,t,d.port),r=new Mn(s,e,o,$,H,N);if(e._transport=r,e.destroyed)throw new Error("Loading aborted");s.send("Ready",null)})}).catch(e._capability.reject).finally(e._setupCapability.resolve),e}var Sn=class t{static#t=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+t.#t++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._setupCapability.promise,await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}},Cn=class{#t=Promise.withResolvers();#e=null;constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s}onDataRange(t,e){this.#e({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#t.promise.then(()=>{this.#e({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#t.promise.then(()=>{this.#e({type:"progressiveDone"})})}transportReady(t){this.#e=t,this.#t.resolve()}requestDataRange(t,e){Oe("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}},En=class{constructor(t,e){this._pdfInfo=t,this._transport=e}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return He(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()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){let{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()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}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()}},kn=class t{#t=!1;#e=null;constructor(t,e,i,s,r=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=r?new mi:null,this._pdfBug=r,this.commonObjs=i.commonObjs,this.objs=new wn,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#e=s,this.imageCoordinates=null}clone(e){let i=new t(e,this._pageInfo,this._transport,this.#e,this._pdfBug);return i.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(i),i}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1,this._transport.updatePage(this)}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:i=0,offsetY:s=0,dontFlip:r=!1}={}){return new ni({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:r})}getAnnotations({intent:t="display"}={}){let{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 He(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:s="display",annotationMode:r=re.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1,recordImages:u=!1,recordOperations:p=!1,operationsFilter:g=null}){this._stats?.time("Overall");let m=this._transport.getRenderingIntent(s,r,d,c),{renderingIntent:f,cacheKey:b}=m;this.#t=!1,o||=this._transport.getOptionalContentConfig(f);let v=this._intentStates.getOrInsertComputed(b,si);v.streamReaderCancelTimeout&&(clearTimeout(v.streamReaderCancelTimeout),v.streamReaderCancelTimeout=null);let y=!!(f&Jt);v.displayReadyCapability||(v.displayReadyCapability=Promise.withResolvers(),v.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(m));let A=!(!this._pdfBug||!globalThis.StepperManager?.enabled),w=!!e&&!this.recordedBBoxes&&(p||A),x=!!e&&!this.imageCoordinates&&u,_=t=>{if(v.renderTasks.delete(E),w){let t=E.gfx?.dependencyTracker.take();t&&(E.stepper?.setOperatorBBoxes(t,E.gfx.dependencyTracker.takeDebugMetadata()),p&&(this.recordedBBoxes=t))}x&&!t&&(this.imageCoordinates=E.gfx?.imagesTracker.take()),y&&(this.#t=!0),this.#i(),t?(E.capability.reject(t),this._abortOperatorList({intentState:v,reason:t instanceof Error?t:new Error(t)})):E.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},S=null,C=null;(w||x)&&(C=new gs(e,v.operatorList.length)),w&&(S=new ms(C,A));let E=new Dn({callback:_,params:{canvas:e,canvasContext:t,dependencyTracker:S??C,imagesTracker:x?new Ss(e):null,viewport:i,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:v.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:h,enableHWA:this._transport.enableHWA,operationsFilter:g});(v.renderTasks||=new Set).add(E);let k=E.task;return Promise.all([v.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)_();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");E.initializeGraphics({transparency:t,optionalContentConfig:e}),E.operatorListChanged()}}).catch(_),k}getOperatorList({intent:t="display",annotationMode:e=re.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){let r,n=this._transport.getRenderingIntent(t,e,i,s,!0),a=this._intentStates.getOrInsertComputed(n.cacheKey,si);return a.opListReadCapability||(r=Object.create(null),r.operatorListChanged=function(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(r))},a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(r),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(n)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#e.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>ai.textContent(t));let e=this.streamTextContent(t),i={items:[],styles:Object.create(null),lang:null};for await(let t of e)i.lang??=t.lang,Object.assign(i.styles,t.styles),i.items.push(...t.items);return i}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let t=[];for(let e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(let i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#t=!1,Promise.all(t)}cleanup(t=!1){this.#t=!0;let e=this.#i();return t&&e&&(this._stats&&=new mi),e}#i(){if(!this.#t||this.destroyed)return!1;for(let{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}_startRenderPage(t,e){let i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i<s;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(let t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#i()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:s}){let{map:r,transfer:n}=i,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#e.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:r,modifiedIds:s},void 0,n).getReader(),o=this._intentStates.get(e);o.streamReader=a;let l=()=>{a.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(let t of o.renderTasks)t.operatorListChanged();this.#i()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof di){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i))}}if(t.streamReader.cancel(new Xe(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(let[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}},Tn=class t{#t=Promise.withResolvers();#e=null;#i=null;#s=null;static#r=0;static#n=!1;static#a=new WeakMap;static{zt&&(this.#n=!0,pn.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;let s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{let e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:e=null,port:i=null,verbosity:s=Ie()}={}){if(this.name=e,this.destroyed=!1,this.verbosity=s,i){if(t.#a.has(i))throw new Error("Cannot use more than one PDFWorker per port.");t.#a.set(i,this),this.#l(i)}else this.#h()}get promise(){return this.#t.promise}#o(){this.#t.resolve(),this.#e.send("configure",{verbosity:this.verbosity})}get port(){return this.#i}get messageHandler(){return this.#e}#l(t){this.#i=t,this.#e=new Js("main","worker",t),this.#e.on("ready",()=>{}),this.#o()}#h(){if(t.#n||t.#c)return void this.#d();let{workerSrc:e}=t;try{t._isSameOrigin(window.location,e)||(e=t._createCDNWrapper(new URL(e,window.location).href));let i=new Worker(e,{type:"module"}),s=new Js("main","worker",i),r=()=>{n.abort(),s.destroy(),i.terminate(),this.destroyed?this.#t.reject(new Error("Worker was destroyed")):this.#d()},n=new AbortController;i.addEventListener("error",()=>{this.#s||r()},{signal:n.signal}),s.on("test",t=>{n.abort(),!this.destroyed&&t?(this.#e=s,this.#i=i,this.#s=i,this.#o()):r()}),s.on("ready",t=>{if(n.abort(),this.destroyed)r();else try{a()}catch{this.#d()}});let a=()=>{let t=new Uint8Array;s.send("test",t,[t.buffer])};return void a()}catch{Fe("The worker has been disabled.")}this.#d()}#d(){t.#n||(Le("Setting up fake worker."),t.#n=!0),t._setupFakeWorkerGlobal.then(e=>{if(this.destroyed)return void this.#t.reject(new Error("Worker was destroyed"));let i=new Us;this.#i=i;let s="fake"+t.#r++,r=new Js(s+"_worker",s,i);e.setup(r,i),this.#e=new Js(s,s+"_worker",i),this.#o()}).catch(t=>{this.#t.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#s?.terminate(),this.#s=null,t.#a.delete(this.#i),this.#i=null,this.#e?.destroy(),this.#e=null}static create(e){let i=this.#a.get(e?.port);if(i){if(i._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return i}return new t(e)}static get workerSrc(){if(pn.workerSrc)return pn.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#c(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return He(this,"_setupFakeWorkerGlobal",(async()=>this.#c?this.#c:(await import(this.workerSrc)).WorkerMessageHandler)())}},Mn=class{downloadInfoCapability=Promise.withResolvers();#t=null;#e=new Map;#i=null;#s=new Map;#r=new Map;#n=new Map;#a=null;constructor(t,e,i,s,r,n){this.messageHandler=t,this.loadingTask=e,this.#i=i,this.commonObjs=new wn,this.fontLoader=new Cs({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.enableHWA=s.enableHWA,this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=r.canvasFactory,this.filterFactory=r.filterFactory,this.binaryDataFactory=r.binaryDataFactory,this.pagesMapper=n,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(t){let{_pageIndex:e}=t;this.#s.set(e,t),this.#r.set(e,Promise.resolve(t))}#o(t,e=null){return this.#e.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#l({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?ri(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return He(this,"annotationStorage",new ns)}getRenderingIntent(t,e=re.ENABLE,i=null,s=!1,r=!1){let n=Qt,a=rs;switch(t){case"any":n=Kt;break;case"display":break;case"print":n=Jt;break;default:Le(`getRenderingIntent - invalid intent: ${t}`)}let o=n&Jt&&i instanceof as?i:this.annotationStorage;switch(e){case re.DISABLE:n+=ee;break;case re.ENABLE:break;case re.ENABLE_FORMS:n+=Zt;break;case re.ENABLE_STORAGE:n+=te,a=o.serializable;break;default:Le(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(n+=ie),r&&(n+=se);let{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:n,cacheKey:[n,a.hash,h].join("_"),annotationStorageSerializable:a,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#a?.reject(new Error("Worker was destroyed during onPassword callback"));let t=[];for(let e of this.#s.values())t.push(e._destroy());this.#s.clear(),this.#r.clear(),this.#n.clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();let e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),xn.cleanup(),this.#i?.cancelAllRequests(new Xe("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{Re(this.#i,"GetReader - no `BasePDFStream` instance available."),this.#t=this.#i.getFullReader(),this.#t.onProgress=t=>this.#l(t),e.onPull=()=>{this.#t.read().then(function({value:t,done:i}){i?e.close():(Re(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this.#t.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this.#t.headersReady;let{isStreamingSupported:e,isRangeSupported:i,contentLength:s}=this.#t;return e&&i&&(this.#t.onProgress=null),{isStreamingSupported:e,isRangeSupported:i,contentLength:s}}),t.on("GetRangeReader",(t,e)=>{Re(this.#i,"GetRangeReader - no `BasePDFStream` instance available.");let i=this.#i.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then(function({value:t,done:i}){i?e.close():(Re(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages,this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new En(t,this))}),t.on("DocException",t=>{e._capability.reject(Qs(t))}),t.on("PasswordRequest",t=>{this.#a=Promise.withResolvers();try{if(!e.onPassword)throw Qs(t);let i=t=>{t instanceof Error?this.#a.reject(t):this.#a.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#a.reject(t)}return this.#a.promise}),t.on("DataLoaded",t=>{this.#l({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{this.destroyed||this.#s.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,s])=>{if(this.destroyed||this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in s){let t=s.error;Le(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}let r=new Fs(s),n=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new Es(r,n,s.charProcOperatorList,s.extra);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{a.fontExtraProperties||a.clearData(),this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":let{imageRef:o}=s;Re(o,"The imageRef must be defined.");for(let t of this.#s.values())for(let[,i]of t.objs){if(i?.ref!==o)continue;if(!i.dataLen)return null;let t=structuredClone(i);return this.commonObjs.resolve(e,t),i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new Os(s));break;case"Image":this.commonObjs.resolve(e,s);break;case"Pattern":let l=new Ls(s);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,s])=>{if(this.destroyed)return;let r=this.#s.get(e);if(!r.objs.has(t)){if(0===r._intentStates.size)return void s?.bitmap?.close();switch(i){case"Image":case"Pattern":r.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}}}),t.on("DocProgress",t=>{this.destroyed||this.#l(t)}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&Le("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#t?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){let e,i={pageInfos:t},s=globalThis.ImageBitmap;if("function"==typeof s){let i=Array.isArray(t)?t:[t];for(let t of i)t?.image instanceof s&&(e||=[]).push(t.image)}if(this.annotationStorage.size>0){let t=this.annotationStorage.serializable,{map:s}=t;t.transfer?.length&&(e?e.push(...t.transfer):e=t.transfer);let r=this.pagesMapper.getMapping();if(r){let t=new Map;for(let[e,i]of s){if(void 0!==i?.pageIndex&&i.pageIndex>=0&&i.pageIndex<r.length){let s=r[i.pageIndex]-1;if(s!==i.pageIndex){t.set(e,{...i,pageIndex:s});continue}}t.set(e,i)}s=t}i.annotationStorage=s}return this.messageHandler.sendWithPromise("ExtractPages",i,e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));let e=t-1,i=this.pagesMapper.getPageId(t)-1,s=this.#r.get(e);if(s)return s;let r=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#n.set(t.refStr,i);let s=new kn(e,t,this,this.pagesMapper,this._params.pdfBug);return this.#s.set(e,s),s});return this.#r.set(e,r),r}async getPageIndex(t){if(!Ns(t))throw new Error("Invalid pageIndex request.");let e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),i=this.pagesMapper.getPageNumber(e+1);if(0===i)throw new Error("GetPageIndex: page has been removed.");return i-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#o("GetFieldObjects")}hasJSActions(){return this.#o("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)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#o("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#o("GetOptionalContentConfig").then(e=>new bn(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let t="GetMetadata";return this.#e.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new gn(t[1]):null,contentDispositionFilename:this.#t?.filename??null,contentLength:this.#t?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let t of this.#s.values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),xn.cleanup()}}cachedPageNumber(t){if(!Ns(t))return null;let e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#n.get(e);if(i>=0){let t=this.pagesMapper.getPageNumber(i+1);if(0!==t)return t}return null}},Pn=class{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){let{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;let{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}},Dn=class t{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:r,operatorList:n,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=r,this.operatorListIdx=null,this.operatorList=n,this._pageIndex=a,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new Pn(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.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._imagesTracker=e.imagesTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:i}){if(this.cancelled)return;if(this._canvas){if(t.#e.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.");t.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{viewport:s,transform:r,background:n,dependencyTracker:a,imagesTracker:o}=this.params,l=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Br(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:i},this.annotationCanvasMap,this.pageColors,a,o),this.gfx.beginDrawing({transform:r,viewport:s,transparency:e,background:n}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(e=null,i=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),t.#e.delete(this._canvas),e||=new di(`Rendering cancelled, page ${this._pageIndex+1}`,i),this.callback(e),this.task.onError?.(e)}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),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.#t=window.requestAnimationFrame(()=>{this.#t=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._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),t.#e.delete(this._canvas),this.callback())))}},In="6.0.227",Fn="241dbabbf",Ln=class t{#t=null;#e=null;#i;#s=null;#r=!1;#n=!1;#a=null;#o;#l=null;#h=null;static#d=null;static get _keyboardManager(){return He(this,"_keyboardManager",new Wi([[["Escape","mac+Escape"],t.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],t.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],t.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],t.prototype._moveToPrevious],[["Home","mac+Home"],t.prototype._moveToBeginning],[["End","mac+End"],t.prototype._moveToEnd]]))}constructor({editor:e=null,uiManager:i=null}){e?(this.#n=!1,this.#a=e):this.#n=!0,this.#h=e?._uiManager||i,this.#o=this.#h._eventBus,this.#i=e?.color?.toUpperCase()||this.#h?.highlightColors.values().next().value||"#FFFF98",t.#d||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){let t=this.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.ariaHasPopup="true",this.#a&&(t.ariaControls=`${this.#a.id}_colorpicker_dropdown`);let e=this.#h._signal;t.addEventListener("click",this.#g.bind(this),{signal:e}),t.addEventListener("keydown",this.#p.bind(this),{signal:e});let i=this.#e=document.createElement("span");return i.className="swatch",i.ariaHidden="true",i.style.backgroundColor=this.#i,t.append(i),t}renderMainDropdown(){let t=this.#s=this.#c();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#c(){let e=document.createElement("div"),i=this.#h._signal;e.addEventListener("contextmenu",bi,{signal:i}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#a&&(e.id=`${this.#a.id}_colorpicker_dropdown`);for(let[s,r]of this.#h.highlightColors){let n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",r),n.title=s,n.setAttribute("data-l10n-id",t.#d[s]);let a=document.createElement("span");n.append(a),a.className="swatch",a.style.backgroundColor=r,n.ariaSelected=r===this.#i,n.addEventListener("click",this.#u.bind(this,r),{signal:i}),e.append(n)}return e.addEventListener("keydown",this.#p.bind(this),{signal:i}),e}#u(t,e){e.stopPropagation(),this.#o.dispatch("switchannotationeditorparams",{source:this,type:le.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#t)return void this.#g(t);let e=t.target.getAttribute("data-color");e&&this.#u(e,t)}_moveToNext(t){this.#f?t.target!==this.#t?t.target.nextSibling?.focus():this.#s.firstElementChild?.focus():this.#g(t)}_moveToPrevious(t){t.target!==this.#s?.firstElementChild&&t.target!==this.#t?(this.#f||this.#g(t),t.target.previousSibling?.focus()):this.#f&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#f?this.#s.firstElementChild?.focus():this.#g(t)}_moveToEnd(t){this.#f?this.#s.lastElementChild?.focus():this.#g(t)}#p(e){t._keyboardManager.exec(this,e)}#g(t){if(this.#f)return void this.hideDropdown();if(this.#r=0===t.detail,this.#l||(this.#l=new AbortController,window.addEventListener("pointerdown",this.#m.bind(this),{signal:this.#h.combinedSignal(this.#l)})),this.#t.ariaExpanded="true",this.#s)return void this.#s.classList.remove("hidden");let e=this.#s=this.#c();this.#t.append(e)}#m(t){this.#s?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#s?.classList.add("hidden"),this.#t.ariaExpanded="false",this.#l?.abort(),this.#l=null}get#f(){return this.#s&&!this.#s.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#f)return void this.#a?.unselect();this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#s)return;let e=this.#h.highlightColors.values();for(let i of this.#s.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#s?.remove(),this.#s=null}},On=class t{#t=null;#e=!1;#i=null;#s=null;static#r=null;constructor(e){this.#i=e,this.#s=e._uiManager,t.#r||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#t)return this.#t;let{editorType:e,colorType:i,colorAndOpacityType:s,opacityType:r,color:n,opacity:a}=this.#i,o=this.#e=qe.isAlphaColorInputSupported&&void 0!==r,l=this.#t=document.createElement("input");if(l.type="color",o){l.setAttribute("alpha","");let t=Ke.hexNums[Math.round(255*(a??1))];l.value=(n||"#000000")+t}else l.value=n||"#000000";return l.className="basicColorPicker",l.tabIndex=0,l.setAttribute("data-l10n-id",t.#r[e]),l.addEventListener("input",()=>{if(o){let t=Ai(l.value);if(!t)return;let[e,n,a,o]=t,h=Ke.makeHexColor(e,n,a);void 0!==s?this.#s.updateParams(s,{color:h,opacity:o}):(this.#s.updateParams(i,h),this.#s.updateParams(r,o))}else this.#s.updateParams(i,l.value)},{signal:this.#s._signal}),l}update(t){if(this.#t)if(this.#e){let e=Ke.hexNums[Math.round(255*this.#i.opacity)];this.#t.value=t+e}else this.#t.value=t}updateOpacity(t){if(!this.#t||!this.#e)return;let e=Ke.hexNums[Math.round(255*t)];this.#t.value=this.#i.color+e}destroy(){this.#t?.remove(),this.#t=null}hideDropdown(){}};function Rn(t){return Math.floor(255*ri(t,0,1)).toString(16).padStart(2,"0")}function Nn(t){return 255*ri(t,0,1)}var Bn=class{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}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=Nn(t),t,t]}static G_HTML([t]){let e=Rn(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(Nn)}static RGB_HTML(t){return`#${t.map(Rn).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[Nn(1-Math.min(1,t+s)),Nn(1-Math.min(1,i+s)),Nn(1-Math.min(1,e+s))]}static CMYK_HTML(t){let e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){let s=1-t,r=1-e,n=1-i;return["CMYK",s,r,n,Math.min(s,r,n)]}},Un=class{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");let s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){Oe("Abstract method `_createSVG` called.")}},Hn=class extends Un{_createSVG(t){return document.createElementNS(qt,t)}},jn=new WeakSet,$n=60*(new Date).getTimezoneOffset()*1e3,Gn=class{static create(t){switch(t.data.annotationType){case be.LINK:return new Wn(t);case be.TEXT:return new Xn(t);case be.WIDGET:switch(t.data.fieldType){case"Tx":return new qn(t);case"Btn":return t.data.radioButton?new Jn(t):t.data.checkBox?new Qn(t):new Zn(t);case"Ch":return new ta(t);case"Sig":return new Kn(t)}return new Yn(t);case be.POPUP:return new ea(t);case be.FREETEXT:return new sa(t);case be.LINE:return new ra(t);case be.SQUARE:return new na(t);case be.CIRCLE:return new aa(t);case be.POLYLINE:return new oa(t);case be.CARET:return new ha(t);case be.INK:return new da(t);case be.POLYGON:return new la(t);case be.HIGHLIGHT:return new ca(t);case be.UNDERLINE:return new ua(t);case be.SQUIGGLY:return new pa(t);case be.STRIKEOUT:return new ga(t);case be.STAMP:return new ma(t);case be.FILEATTACHMENT:return new fa(t);default:return new zn(t)}}},zn=class t{#t=null;#e=!1;#i=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!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.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return t._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){let{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){let t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;let{quadPoints:e,inkLists:i,rect:s}=this.data,r=-1/0,n=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>n?(n=e[t+1],r=e[t+2]):e[t+1]===n&&(r=Math.max(r,e[t+2]));return[r,n]}if(i?.length>=1){for(let t of i)for(let e=0,i=t.length;e<i;e+=2)t[e+1]>n?(n=t[e+1],r=t[e]):t[e+1]===n&&(r=Math.max(r,t[e]));if(r!==1/0)return[r,n]}return s?[s[2],s[3]]:null}_normalizePoint(t){let{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:s,pageX:r,pageY:n}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-r)/i,t[1]=100*(t[1]-n)/s,t}get commentText(){let{data:t}=this;return this.annotationStorage.getRawValue(`${ae}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){let{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${ae}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#i?.popup||this.popup)?.remove(),this.#i=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#t||={rect:this.data.rect.slice(0)});let{rect:e,popup:i}=t;e&&this.#s(e);let s=this.#i?.popup||this.popup;!s&&i?.text&&(this._createPopup(i),s=this.#i.popup),s&&(s.updateEdited(t),i?.deleted&&(s.remove(),this.#i=null,this.popup=null))}resetEdited(){this.#t&&(this.#s(this.#t.rect),this.#i?.popup.resetEdited(),this.#t=null)}#s(t){let{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:r,pageHeight:n,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-a)/r+"%",e.top=100*(n-t[3]+o)/n+"%",0===s?(e.width=100*(t[2]-t[0])/r+"%",e.height=100*(t[3]-t[1])/n+"%"):this.setRotation(s)}_createContainer(t){let{data:e,parent:{page:i,viewport:s}}=this,r=document.createElement("section");r.setAttribute("data-annotation-id",e.id),!(this instanceof Yn)&&!(this instanceof Wn)&&(r.tabIndex=0);let{style:n}=r;if(n.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(r.title=e.alternativeText),e.noRotate&&r.classList.add("norotate"),!e.rect||this instanceof ea){let{rotation:t}=e;return!e.hasOwnCanvas&&0!==t&&this.setRotation(t,r),r}let{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){n.borderWidth=`${e.borderStyle.width}px`;let t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){let e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;n.borderRadius=e}else if(this instanceof Jn){let t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;n.borderRadius=t}switch(e.borderStyle.style){case ve:n.borderStyle="solid";break;case ye:n.borderStyle="dashed";break;case Ae:Le("Unimplemented border style: beveled");break;case we:Le("Unimplemented border style: inset");break;case xe:n.borderBottomStyle="solid"}let s=e.borderColor||null;s?(this.#e=!0,n.borderColor=Ke.makeHexColor(...s)):n.borderWidth=0}let l=Ke.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;n.left=100*(l[0]-c)/h+"%",n.top=100*(l[1]-u)/d+"%";let{rotation:p}=e;return e.hasOwnCanvas||0===p?(n.width=100*a/h+"%",n.height=100*o/d+"%"):this.setRotation(p,r),r}setRotation(t,e=this.container){if(!this.data.rect)return;let{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:r,height:n}=this;t%180!=0&&([r,n]=[n,r]),e.style.width=100*r/i+"%",e.style.height=100*n/s+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){let t=(t,e,i)=>{let s=i.detail[t],r=s[0],n=s.slice(1);i.target.style[e]=Bn[`${r}_HTML`](n),this.annotationStorage.setValue(this.data.id,{[e]:Bn[`${r}_rgb`](n)})};return He(this,"_commonActions",{display:t=>{let{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{let{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=>{let e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){let i=this._commonActions;for(let s of Object.keys(e.detail))(t[s]||i[s])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;let e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;let i=this._commonActions;for(let[s,r]of Object.entries(e)){let n=i[s];if(n){n({detail:{[s]:r},target:t}),delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:t}=this.data;if(!t)return;let[e,i,s,r]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){let[n,a,o,l]=t.subarray(2,6);if(s===n&&r===a&&e===o&&i===l)return}let n,{style:a}=this.container;if(this.#e){let{borderColor:t,borderWidth:e}=a;a.borderWidth=0,n=["url('data:image/svg+xml;utf8,",`<svg xmlns="${qt}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${t}" stroke-width="${e}">`],this.container.classList.add("hasBorder")}let o=s-e,l=r-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";let c=h.createElement("defs");d.append(c);let u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,s=t.length;i<s;i+=8){let s=t[i],a=t[i+1],d=t[i+2],c=t[i+3],p=h.createElement("rect"),g=(d-e)/o,m=(r-a)/l,f=(s-d)/o,b=(a-c)/l;p.setAttribute("x",g),p.setAttribute("y",m),p.setAttribute("width",f),p.setAttribute("height",b),u.append(p),n?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#e&&(n.push("</g></svg>')"),a.backgroundImage=n.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){let e,i,{data:s}=this;t?(e={str:t.text},i=t.date):(e=s.contentsObj,i=s.modificationDate),this.#i=new ea({data:{color:s.color,titleObj:s.titleObj,modificationDate:i,contentsObj:e,richText:s.richText,parentRect:s.rect,borderStyle:0,id:`popup_${s.id}`,rotation:s.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#i||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#i}render(){Oe("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){let i=[];if(this._fieldObjects){let s=this._fieldObjects[t];if(s)for(let{page:t,id:r,exportValues:n}of s){if(-1===t||r===e)continue;let s="string"==typeof n?n:null,a=document.querySelector(`[data-element-id="${r}"]`);!a||jn.has(a)?i.push({id:r,exportValue:s,domElement:a}):Le(`_getElementsByName - element not allowed: ${r}`)}return i}for(let s of document.getElementsByName(t)){let{exportValue:t}=s,r=s.getAttribute("data-element-id");r!==e&&jn.has(s)&&i.push({id:r,exportValue:t,domElement:s})}return i}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(){let t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(let e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}updateOC(t){this.data.oc&&t&&(t.isVisible(this.data.oc)?this.show():this.hide())}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}},Vn=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){let{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}},Wn=class extends zn{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){let{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),s=!0):t.attachment?(this.#e(i,t.attachment,t.overlaidText,t.attachmentDest),s=!0):t.setOCGState?(this.#i(i,t.setOCGState,t.overlaidText),s=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&(this.contentElement=i,this.container.append(i)),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#t(),i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),i&&(t.title=i),this.#t()}#e(t,e,i="",s=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#i(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),i&&(t.title=i),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");let i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let s of Object.keys(e.actions)){let r=i.get(s);r&&(t[r]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){let i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects)return Le('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();let{fields:t,refs:s,include:r}=e,n=[];if(0!==t.length||0!==s.length){let e=new Set(s);for(let i of t){let t=this._fieldObjects[i]||[];for(let{id:i}of t)e.add(i)}for(let t of Object.values(this._fieldObjects))for(let i of t)e.has(i.id)===r&&n.push(i)}else for(let t of Object.values(this._fieldObjects))n.push(...t);let a=this.annotationStorage,o=[];for(let t of n){let{id:e}=t;switch(o.push(e),t.type){case"text":{let i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{let i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{let i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}let i=document.querySelector(`[data-element-id="${e}"]`);i&&(jn.has(i)?i.dispatchEvent(new Event("resetform")):Le(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}},Xn=class extends zn{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let 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.hasOwnCommentButton=!0,this._createPopup()),this.container.append(t),this.container}},Yn=class extends zn{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return qe.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,r){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:r(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}r&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:r(t)}})})}_setEventListeners(t,e,i,s){for(let[r,n]of i)("Action"===n||this.data.actions?.[n])&&(("Focus"===n||"Blur"===n)&&(e||={focused:!1}),this._setEventListener(t,e,r,n,s),"Focus"!==n||this.data.actions?.Blur?"Blur"===n&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){let e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Ke.makeHexColor(...e)}_setTextStyle(t){let e,{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,r=t.style,n=t=>Math.round(10*t)/10;if(this.data.multiLine){let t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),i=t/(Math.round(t/(Yt*s))||1);e=Math.min(s,n(i/Yt))}else{let t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);e=Math.min(s,n(t/Yt))}r.fontSize=`calc(${e}px * var(--total-scale-factor))`,r.color=Ke.makeHexColor(...i),null!==this.data.textAlignment&&(r.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}},qn=class extends Yn{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){let r=this.annotationStorage;for(let n of this._getElementsByName(t.name,t.id))n.domElement&&(n.domElement[e]=i),r.setValue(n.id,{[s]:i})}render(){let t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){let s=t.getValue(e,{value:this.data.fieldValue}),r=s.value||"",n=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;n&&r.length>n&&(r=r.slice(0,n));let a=s.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));let o={userValue:r,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=a??r,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",a??r),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),jn.add(i),this.contentElement=i,i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=0;let{datetimeFormat:l,datetimeType:h,timeStep:d}=this.data,c=!!h&&this.enableScripting;l&&(i.title=l),this._setRequired(i,this.data.required),n&&(i.maxLength=n),i.addEventListener("input",s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{let e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let u=t=>{let{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;let{target:e}=t;if(c&&(e.type=h,d&&(e.step=d)),o.userValue){let t=o.userValue;if(c)if("time"===h){let i=new Date(t),s=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=s.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-$n).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);let s={value(i){o.userValue=i.detail.value??"",c||t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){let{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s);let r={formattedValue:s};c&&(r.value=s),t.setValue(e,r)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{let{charLimit:s}=i.detail,{target:r}=i;if(0===s)return void r.removeAttribute("maxLength");r.setAttribute("maxLength",s);let n=o.userValue;!n||n.length<=s||(n=n.slice(0,s),r.value=o.userValue=n,t.setValue(e,{value:n}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:1,selStart:r.selectionStart,selEnd:r.selectionEnd}}))}};this._dispatchEventFromSandbox(s,i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;let{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});let s=u;u=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);let{target:i}=t,{value:r}=i;if(c){if(r&&"time"===h){let t=r.split(":").map(t=>parseInt(t,10));r=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),i.step=""}else r.includes("T")||(r=`${r}T00:00`),r=new Date(r).valueOf();i.type="text"}o.userValue=r,o.lastCommittedValue!==r&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;let{data:i,target:s}=t,{value:r,selectionStart:n,selectionEnd:a}=s,l=n,h=a;switch(t.inputType){case"deleteWordBackward":{let t=r.substring(0,n).match(/\w*\W*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{let t=r.substring(n).match(/^\W*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":n===a&&(l-=1);break;case"deleteContentForward":n===a&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(u&&i.addEventListener("blur",u),this.data.comb){let t=(this.data.rect[2]-this.data.rect[0])/n;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},Kn=class extends Yn{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}},Qn=class extends Yn{constructor(t){super(t,{isRenderable:t.renderForms})}render(){let t=this.annotationStorage,e=this.data,i=e.id,s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let r=document.createElement("input");return jn.add(r),r.setAttribute("data-element-id",i),r.disabled=e.readOnly,this._setRequired(r,this.data.required),r.type="checkbox",r.name=e.fieldName,s&&r.setAttribute("checked",!0),r.setAttribute("exportValue",e.exportValue),r.tabIndex=0,r.addEventListener("change",s=>{let{name:r,checked:n}=s.target;for(let s of this._getElementsByName(r,i)){let i=n&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:n})}),r.addEventListener("resetform",t=>{let i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(r.addEventListener("updatefromsandbox",e=>{let s={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}),this._setEventListeners(r,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(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},Jn=class extends Yn{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let t=this.annotationStorage,e=this.data,i=e.id,s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(let s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});let r=document.createElement("input");if(jn.add(r),r.setAttribute("data-element-id",i),r.disabled=e.readOnly,this._setRequired(r,this.data.required),r.type="radio",r.name=e.fieldName,s&&r.setAttribute("checked",!0),r.tabIndex=0,r.addEventListener("change",e=>{let{name:s,checked:r}=e.target;for(let e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:r})}),r.addEventListener("resetform",t=>{let i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){let s=e.buttonValue;r.addEventListener("updatefromsandbox",e=>{let r={value:e=>{let r=s===e.detail.value;for(let s of this._getElementsByName(e.target.name)){let e=r&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(r,e)}),this._setEventListeners(r,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(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},Zn=class extends Wn{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){let t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");let e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}},ta=class extends Yn{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");jn.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=0;let r=this.data.combo&&this.data.options.length>0;this.data.combo||(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",t=>{let e=this.data.defaultFieldValue;for(let t of s.options)t.selected=t.value===e});let n=(t,e)=>{let i=e.replaceAll(" "," ");t.textContent=i,i!==e&&t.setAttribute("display-value",e)};for(let t of this.data.options){let e=document.createElement("option");n(e,t.displayValue),e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),r=!1),s.append(e)}let a=null;if(r){let t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),a=()=>{t.remove(),s.removeEventListener("input",a),a=null},s.addEventListener("input",a)}let o=t=>{let e=t?"value":"textContent",{options:i,multiple:r}=s;return r?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]},l=o(!1),h=t=>{let e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.getAttribute("display-value")||t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",i=>{let r={value(i){a?.();let r=i.detail.value,n=new Set(Array.isArray(r)?r:[r]);for(let t of s.options)t.selected=n.has(t.value);t.setValue(e,{value:o(!0)}),l=o(!1)},multipleSelection(t){s.multiple=!0},remove(i){let r=s.options,n=i.detail.remove;r[n].selected=!1,s.remove(n),r.length>0&&-1===Array.prototype.findIndex.call(r,t=>t.selected)&&(r[0].selected=!0),t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),l=o(!1)},insert(i){let{index:r,displayValue:a,exportValue:d}=i.detail.insert,c=s.children[r],u=document.createElement("option");n(u,a),u.value=d,c?c.before(u):s.append(u),t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},items(i){let{items:r}=i.detail;for(;0!==s.length;)s.remove(0);for(let t of r){let{displayValue:e,exportValue:i}=t,r=document.createElement("option");n(r,e),r.value=i,s.append(r)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:o(!0),items:h(i)}),l=o(!1)},indices(i){let s=new Set(i.detail.indices);for(let t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:o(!0)}),l=o(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(r,i)}),s.addEventListener("input",i=>{let s=o(!0),r=o(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:r,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(s,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)):s.addEventListener("input",function(i){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}},ea=class extends zn{constructor(t){let{data:e,elements:i,parent:s}=t,r=!!s._commentManager;if(super(t,{isRenderable:!r&&zn._hasPopupData(e)}),this.elements=i,r&&zn._hasPopupData(e)){let t=this.popup=this.#t();for(let e of i)e.popup=t}else this.popup=null}#t(){return new ia({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,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,commentManager:this.parent._commentManager})}render(){let{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";let e=this.popup=this.#t(),i=[];for(let t of this.elements)t.popup=e,t.container.ariaHasPopup="dialog",i.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(t=>`${ne}${t}`).join(",")),this.container}},ia=class{#t=null;#e=this.#L.bind(this);#i=this.#B.bind(this);#s=this.#N.bind(this);#r=this.#R.bind(this);#n=null;#a=null;#o=null;#l=null;#h=null;#d=null;#c=null;#u=!1;#p=null;#g=null;#m=null;#f=null;#b=null;#v=null;#y=null;#A=null;#w=null;#x=null;#_=!1;#S=null;#C=null;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:r,contentsObj:n,richText:a,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#a=t,this.#w=s,this.#o=n,this.#A=a,this.#d=o,this.#n=e,this.#y=l,this.#c=h,this.#h=i,this.#t=c,this.#S=i[0],this.#l=yi.toDateObject(r),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),c||(this.#E(),this.#a.hidden=!0,d&&this.#R())}#E(){if(this.#g)return;this.#g=new AbortController;let{signal:t}=this.#g;for(let e of this.trigger)e.addEventListener("click",this.#r,{signal:t}),e.addEventListener("pointerenter",this.#s,{signal:t}),e.addEventListener("pointerleave",this.#i,{signal:t}),e.classList.add("popupTriggerArea");for(let e of this.#h)e.container?.addEventListener("keydown",this.#e,{signal:t})}#k(){let t=this.#h.find(t=>t.hasCommentButton);t&&(this.#b=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#f)return void(this.#f.parentNode||this.#S.container.after(this.#f));if(this.#b||this.#k(),!this.#b)return;let{signal:t}=this.#g=new AbortController,e=this.#S.hasOwnCommentButton,i=()=>{this.#t.toggleCommentPopup(this,!0,void 0,!e)},s=()=>{this.#t.toggleCommentPopup(this,!1,!0,!e)},r=()=>{this.#t.toggleCommentPopup(this,!1,!1)};if(e){this.#f=this.#S.container;for(let e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#e,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",s,{signal:t}),e.addEventListener("pointerleave",r,{signal:t}),e.classList.add("popupTriggerArea")}else{let e=this.#f=document.createElement("button");e.className="annotationCommentButton";let n=this.#S.container;e.style.zIndex=parseInt(n.style.zIndex,10)+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#M(),this.#T(),e.addEventListener("keydown",this.#e,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",s,{signal:t}),e.addEventListener("pointerleave",r,{signal:t}),n.after(e)}}#T(){if(this.#S.extraPopupElement&&!this.#S.editor)return;this.#f||this.renderCommentButton();let[t,e]=this.#b,{style:i}=this.#f;i.left=`calc(${t}%)`,i.top=`calc(${e}% - var(--comment-button-dim))`}#M(){this.#S.extraPopupElement||(this.#f||this.renderCommentButton(),this.#f.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){let{color:t,opacity:e}=this.#S.commentData;return t?this.#d._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#f?.focus()},0)}getData(){let{richText:t,color:e,opacity:i,creationDate:s,modificationDate:r}=this.#S.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:s,modificationDate:r}}get elementBeforePopup(){return this.#f}get comment(){return this.#C||=this.#S.commentText,this.#C}set comment(t){t!==this.comment&&(this.#S.commentText=this.#C=t)}focus(){this.#S.container?.focus()}get parentBoundingClientRect(){return this.#S.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#f&&(this.#f.classList.toggle("selected",t),this.#f.ariaExpanded=e)}setSelectedCommentButton(t){this.#f.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#v)return this.#v;let{x:t,y:e,height:i}=this.#f.getBoundingClientRect(),{x:s,y:r,width:n,height:a}=this.#S.layer.getBoundingClientRect();return[(t-s)/n,(e+i-r)/a]}set commentPopupPosition(t){this.#v=t}hasDefaultPopupPosition(){return null===this.#v}get commentButtonPosition(){return this.#b}get commentButtonWidth(){return this.#f.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){let[e,i]=this.#v||this.commentButtonPosition.map(t=>t/100),s=this.parentBoundingClientRect,{x:r,y:n,width:a,height:o}=s;this.#t.showDialog(null,this,r+e*a,n+i*o,{...t,parentDimensions:s})}render(){if(this.#p)return;let t=this.#p=document.createElement("div");if(t.className="popup",this.#n){let e=t.style.outlineColor=Ke.makeHexColor(...this.#n);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}let e=document.createElement("span");if(e.className="header",this.#w?.str){let t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#w)}if(t.append(e),this.#l){let t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#l.valueOf()})),t.dateTime=this.#l.toISOString(),e.append(t)}Ri({html:this.#P||this.#o.str,dir:this.#o?.dir,className:"popupContent"},t),this.#a.append(t)}get#P(){let t=this.#A,e=this.#o;return t?.str&&(!e?.str||e.str===t.str)&&this.#A.html||null}get#D(){return this.#P?.attributes?.style?.fontSize||0}get#I(){return this.#P?.attributes?.style?.color||null}#F(t){let e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#I,fontSize:this.#D?`calc(${this.#D}px * var(--total-scale-factor))`:""}};for(let i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}#L(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#u)&&this.#R()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#t)return i?(this.remove(),this.#C=null):e&&(e.deleted?this.remove():(this.#M(),this.#C=e.text)),void(t&&(this.#b=null,this.#k(),this.#T()));i||e?.deleted?this.remove():(this.#E(),this.#x||={contentsObj:this.#o,richText:this.#A},t&&(this.#m=null),e&&e.text&&(this.#A=this.#F(e.text),this.#l=yi.toDateObject(e.date),this.#o=null),this.#p?.remove(),this.#p=null)}resetEdited(){this.#x&&(({contentsObj:this.#o,richText:this.#A}=this.#x),this.#x=null,this.#p?.remove(),this.#p=null,this.#m=null)}remove(){if(this.#g?.abort(),this.#g=null,this.#p?.remove(),this.#p=null,this.#_=!1,this.#u=!1,this.#f?.remove(),this.#f=null,this.trigger)for(let t of this.trigger)t.classList.remove("popupTriggerArea")}#O(){if(null!==this.#m)return;let{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:r}}}=this.#d,n=!!this.#c,a=n?this.#c:this.#y;for(let t of this.#h)if(!a||null!==Ke.intersect(t.data.rect,a)){a=t.data.rect,n=!0;break}let o=Ke.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=n?a[2]-a[0]+5:0,h=o[0]+l,d=o[1];this.#m=[100*(h-s)/e,100*(d-r)/i];let{style:c}=this.#a;c.left=`${this.#m[0]}%`,c.top=`${this.#m[1]}%`}#R(){this.#t?this.#t.toggleCommentPopup(this,!1):(this.#u=!this.#u,this.#u?(this.#N(),this.#a.addEventListener("click",this.#r),this.#a.addEventListener("keydown",this.#e)):(this.#B(),this.#a.removeEventListener("click",this.#r),this.#a.removeEventListener("keydown",this.#e)))}#N(){this.#p||this.render(),this.isVisible?this.#u&&this.#a.classList.add("focused"):(this.#O(),this.#a.hidden=!1,this.#a.style.zIndex=parseInt(this.#a.style.zIndex,10)+1e3)}#B(){this.#a.classList.remove("focused"),!this.#u&&this.isVisible&&(this.#a.hidden=!0,this.#a.style.zIndex=parseInt(this.#a.style.zIndex,10)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#a.hidden=!0)}maybeShow(){this.#t||(this.#E(),this.#_&&(this.#p||this.#N(),this.#_=!1,this.#a.hidden=!1))}get isVisible(){return!this.#t&&!1===this.#a.hidden}},sa=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=oe.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(let e of this.textContent){let i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}},ra=class extends zn{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),r=this.#t=this.svgFactory.createElement("svg:line");return r.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),r.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),r.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),r.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),r.setAttribute("stroke-width",t.borderStyle.width||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),s.append(r),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}},na=class extends zn{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),r=t.borderStyle.width,n=this.#t=this.svgFactory.createElement("svg:rect");return n.setAttribute("x",r/2),n.setAttribute("y",r/2),n.setAttribute("width",e-r),n.setAttribute("height",i-r),n.setAttribute("stroke-width",r||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),s.append(n),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}},aa=class extends zn{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let{data:t,width:e,height:i}=this,s=this.svgFactory.create(e,i,!0),r=t.borderStyle.width,n=this.#t=this.svgFactory.createElement("svg:ellipse");return n.setAttribute("cx",e/2),n.setAttribute("cy",i/2),n.setAttribute("rx",e/2-r/2),n.setAttribute("ry",i/2-r/2),n.setAttribute("stroke-width",r||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),s.append(n),this.container.append(s),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}},oa=class extends zn{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let{data:{rect:t,vertices:e,borderStyle:i,popupRef:s},width:r,height:n}=this;if(!e)return this.container;let a=this.svgFactory.create(r,n,!0),o=[];for(let i=0,s=e.length;i<s;i+=2){let s=e[i]-t[0],r=t[3]-e[i+1];o.push(`${s},${r}`)}o=o.join(" ");let l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),a.append(l),this.container.append(a),!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}},la=class extends oa{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}},ha=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}},da=class extends zn{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?oe.HIGHLIGHT:oe.INK}#i(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:t,rotation:e,inkLists:i,borderStyle:s,popupRef:r}}=this,{transform:n,width:a,height:o}=this.#i(e,t),l=this.svgFactory.create(a,o,!0),h=this.#t=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",n);for(let t=0,e=i.length;t<e;t++){let e=this.svgFactory.createElement(this.svgElementName);this.#e.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!r&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);let{thickness:e,points:i,rect:s}=t,r=this.#t;if(e>=0&&r.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#e.length;t<e;t++)this.#e[t].setAttribute("points",i[t].join(","));if(s){let{transform:t,width:e,height:i}=this.#i(this.data.rotation,s);r.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),r.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}},ca=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=oe.HIGHLIGHT}render(){let{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){let e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}},ua=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),t){let e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}},pa=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),t){let e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}},ga=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),t){let e=document.createElement("s");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}},ma=class extends zn{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=oe.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}},fa=class extends zn{#t=null;constructor(t){super(t,{isRenderable:!0});let{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");let t,{container:e,data:i}=this;i.hasAppearance||0===i.fillAlpha?t=document.createElement("div"):(t=document.createElement("img"),t.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(i.name)?"paperclip":"pushpin"}.svg`,i.fillAlpha&&i.fillAlpha<1&&(t.style=`filter: opacity(${Math.round(100*i.fillAlpha)}%);`)),t.addEventListener("dblclick",this.#e.bind(this)),this.#t=t;let{isMac:s}=qe.platform;return e.addEventListener("keydown",t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#e()}),!i.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):t.classList.add("popupTriggerArea"),e.append(t),e}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}},ba=class t{#t=null;#e=null;#i=null;#s=new Map;#r=null;#n=null;#a=[];#o=!1;zIndex=0;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:r,viewport:n,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t,this.#t=e,this.#e=i,this.#r=a||null,this.#n=l||null,this.#i=h||new ns,this.page=r,this.viewport=n,this._annotationEditorUIManager=s,this._commentManager=o||null}hasEditableAnnotations(){return this.#s.size>0}async render(t){let{annotations:e,optionalContentConfig:i}=t,s=this.div;Si(s,this.viewport);let r=new Map,n=[],a={data:null,layer:s,linkService:this.#n,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new Hn,annotationStorage:this.#i,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(let t of e){if(t.noHTML)continue;let e=t.annotationType===be.POPUP;if(e){let e=r.get(t.id);if(!e)continue;if(!this._commentManager){n.push(t);continue}a.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;a.data=t;let s=Gn.create(a);if(!s.isRenderable)continue;e||(this.#a.push(s),t.popupRef&&r.getOrInsertComputed(t.popupRef,ei).push(s));let o=s.render();t.hidden&&(o.style.visibility="hidden"),s.updateOC(i),s._isEditable&&(this.#s.set(s.data.id,s),this._annotationEditorUIManager?.renderAnnotationElement(s))}await this.#l();for(let t of n){let e=a.elements=r.get(t.id);a.data=t;let i=Gn.create(a);if(!i.isRenderable)continue;let s=i.render();i.contentElement.id=`${ne}${t.id}`,t.hidden&&(s.style.visibility="hidden"),e.at(-1).container.after(s)}this.#h()}async#l(){if(0===this.#a.length)return;this.div.replaceChildren();let t=[];if(!this.#o){this.#o=!0;for(let{contentElement:e,data:{id:i}}of this.#a){let s=e.id=`${ne}${i}`;t.push(this.#r?.getAriaAttributes(s).then(t=>{if(t)for(let[i,s]of t)e.setAttribute(i,s)}))}}this.#a.sort(({data:{rect:[t,e,i,s]}},{data:{rect:[r,n,a,o]}})=>{if(t===i&&e===s)return 1;if(r===a&&n===o)return-1;let l=(e+s)/2,h=(n+o)/2;return l>=o&&h<=e?-1:h>=s&&l<=n?1:(t+i)/2-(r+a)/2});let e=document.createDocumentFragment();for(let t of this.#a)e.append(t.container),this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render());if(this.div.append(e),await Promise.all(t),this.#t)for(let t of this.#a)this.#t.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(e){let i={data:null,layer:this.div,linkService:this.#n,svgFactory:new Hn,parent:this};for(let s of e){s.borderStyle||=t._defaultBorderStyle,i.data=s;let e=Gn.create(i);e.isRenderable&&(e.render(),e.contentElement.id=`${ne}${s.id}`,this.#a.push(e))}await this.#l()}update({viewport:t,optionalContentConfig:e}){let i=this.div;this.viewport=t,Si(i,{rotation:t.rotation});for(let t of this.#a)t.updateOC(e);this.#h(),i.hidden=!1}#h(){if(!this.#e)return;let t=this.div;for(let[e,i]of this.#e){let s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";let{firstChild:r}=s;r?"CANVAS"===r.nodeName?r.replaceWith(i):r.classList.contains("annotationContent")?r.after(i):r.before(i):s.append(i);let n=this.#s.get(e);n&&(n._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i),n._hasNoCanvas=!1):n.canvas=i)}this.#e.clear()}getEditableAnnotations(){return this.#s.values()}getEditableAnnotation(t){return this.#s.get(t)}addFakeAnnotation(t){let{div:e}=this,{id:i,rotation:s}=t,r=new Vn({data:{id:i,rect:t.getPDFRect(),rotation:s},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#n,annotationStorage:this.#i});return r.render(),r.contentElement.id=`${ne}${i}`,r.createOrUpdatePopup(),this.#a.push(r),r}removeAnnotation(t){let e=this.#a.findIndex(e=>e.data.id===t);if(e<0)return;let[i]=this.#a.splice(e,1);this.#t?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(let e of t)e.updateFakeAnnotationElement(this);this.#l()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return He(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:ve,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}},va=/\r\n?|\n/g,ya=class t extends Ji{#t="";#e=`${this.id}-editor`;#i=null;#s;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let e=t.prototype,i=t=>t.isEmpty(),s=Yi.TRANSLATE_SMALL,r=Yi.TRANSLATE_BIG;return He(this,"_keyboardManager",new Wi([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-s,0],checker:i}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-r,0],checker:i}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[s,0],checker:i}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[r,0],checker:i}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-s],checker:i}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-r],checker:i}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,s],checker:i}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,r],checker:i}]]))}static _type="freetext";static _editorType=oe.FREETEXT;constructor(e){super({...e,name:"freeTextEditor"}),this.color=e.color||t._defaultColor||Ji._defaultLineColor,this.#s=e.fontSize||t._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert(Ji._l10nAlert.freetext),this.canAddComment=!1}static initialize(t,e){Ji.initialize(t,e);let i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,i){switch(e){case le.FREETEXT_SIZE:t._defaultFontSize=i;break;case le.FREETEXT_COLOR:t._defaultColor=i}}updateParams(t,e){switch(t){case le.FREETEXT_SIZE:this.#r(e);break;case le.FREETEXT_COLOR:this.#n(e)}}static get defaultPropertiesToUpdate(){return[[le.FREETEXT_SIZE,t._defaultFontSize],[le.FREETEXT_COLOR,t._defaultColor||Ji._defaultLineColor]]}get propertiesToUpdate(){return[[le.FREETEXT_SIZE,this.#s],[le.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new On(this),[["colorPicker",this._colorPicker]]}get colorType(){return le.FREETEXT_COLOR}#r(t){let e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#s)*this.parentScale),this.#s=t,this.#o()},i=this.#s;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:le.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#n(t){let e=t=>{this.color=t,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:le.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){let e=this.parentScale;return[-t._internalPadding*e,-(t._internalPadding+this.#s)*e]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;let t=this._uiManager.combinedSignal(this.#i);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#e),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&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()}#a(){let e=[];this.editorDiv.normalize();let i=null;for(let s of this.editorDiv.childNodes)i?.nodeType===Node.TEXT_NODE&&"BR"===s.nodeName||(e.push(t.#l(s)),i=s);return e.join("\n")}#o(){let t,[e,i]=this.parentDimensions;if(this.isAttachedToDOM)t=this.div.getBoundingClientRect();else{let{currentLayer:e,div:i}=this,s=i.style.display,r=i.classList.contains("hidden");i.classList.remove("hidden"),i.style.display="hidden",e.div.append(this.div),t=i.getBoundingClientRect(),i.remove(),i.style.display=s,i.classList.toggle("hidden",r)}this.rotation%180==this.parentRotation%180?(this.width=t.width/e,this.height=t.height/i):(this.width=t.height/e,this.height=t.width/i),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let t=this.#t,e=this.#t=this.#a().trimEnd();if(t===e)return;let i=t=>{this.#t=t,t?(this.#h(),this._uiManager.rebuild(this),this.#o()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#o()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(e){t._keyboardManager.exec(this,e)}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)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(this._isCopy||this.annotationElementId)&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#e),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#s}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){let[i,s]=this.parentDimensions;if(this.annotationElementId){let{position:r}=this._initialData,[n,a]=this.getInitialTranslation();[n,a]=this.pageTranslationToScreen(n,a);let o,l,[h,d]=this.pageDimensions,[c,u]=this.pageTranslation;switch(this.rotation){case 0:o=t+(r[0]-c)/h,l=e+this.height-(r[1]-u)/d;break;case 90:o=t+(r[0]-c)/h,l=e-(r[1]-u)/d,[n,a]=[a,-n];break;case 180:o=t-this.width+(r[0]-c)/h,l=e-(r[1]-u)/d,[n,a]=[-n,-a];break;case 270:o=t+(r[0]-c-this.height*d)/h,l=e+(r[1]-u-this.width*h)/d,[n,a]=[-a,n]}this.setAt(o*i,l*s,n,a)}else this._moveAfterPaste(t,e);this.#h(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(va,"")}editorDivPaste(e){let i=e.clipboardData||window.clipboardData,{types:s}=i;if(1===s.length&&"text/plain"===s[0])return;e.preventDefault();let r=t.#c(i.getData("text")||"").replaceAll(va,"\n");if(!r)return;let n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();let a=n.getRangeAt(0);if(!r.includes("\n"))return a.insertNode(document.createTextNode(r)),this.editorDiv.normalize(),void n.collapseToStart();let{startContainer:o,startOffset:l}=a,h=[],d=[];if(o.nodeType===Node.TEXT_NODE){let e=o.parentElement;if(d.push(o.nodeValue.slice(l).replaceAll(va,"")),e!==this.editorDiv){let i=h;for(let s of this.editorDiv.childNodes)s!==e?i.push(t.#l(s)):i=d}h.push(o.nodeValue.slice(0,l).replaceAll(va,""))}else if(o===this.editorDiv){let e=h,i=0;for(let s of this.editorDiv.childNodes)i++===l&&(e=d),e.push(t.#l(s))}this.#t=`${h.join("\n")}${r}${d.join("\n")}`,this.#h();let c=new Range,u=Math.sumPrecise(h.map(t=>t.length));for(let{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){let e=t.nodeValue.length;if(u<=e){c.setStart(t,u),c.setEnd(t,u);break}u-=e}n.removeAllRanges(),n.addRange(c)}#h(){if(this.editorDiv.replaceChildren(),this.#t)for(let t of this.#t.split("\n")){let e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#d(){return this.#t.replaceAll(" "," ")}static#c(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){let e=t._internalPadding*this.parentScale;return this.getRect(e,e)}static async deserialize(e,i,s){let r=null;if(e instanceof sa){let{data:{defaultAppearanceData:{fontSize:t,fontColor:i},rect:s,rotation:n,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=e;if(!u||0===u.length)return null;r=e={annotationType:oe.FREETEXT,color:Array.from(i),fontSize:t,value:u.join("\n"),position:p,pageIndex:g-1,rect:s.slice(0),rotation:n,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}let n=await super.deserialize(e,i,s);return n.#s=e.fontSize,n.color=Ke.makeHexColor(...e.color),n.#t=t.#c(e.value),n._initialData=r,e.comment&&n.setCommentData(e),n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let e=Ji._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#s,value:this.#d()});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!this.#u(i)?null:(i.id=this.annotationElementId,i)}#u(t){let{value:e,fontSize:i,color:s,pageIndex:r}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==s[e])||t.pageIndex!==r}renderAnnotationElement(t){let e=super.renderAnnotationElement(t);if(!e)return null;let{style:i}=e;i.fontSize=`calc(${this.#s}px * var(--total-scale-factor))`,i.color=this.color,e.replaceChildren();for(let t of this.#t.split("\n")){let i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#t}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}},Aa=class{static PRECISION=1e-4;toSVGPath(){Oe("Abstract method `toSVGPath` must be implemented.")}get box(){Oe("Abstract getter `box` must be implemented.")}serialize(t,e){Oe("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,r,n){n||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)n[a]=e+t[a]*s,n[a+1]=i+t[a+1]*r;return n}static _rescaleAndSwap(t,e,i,s,r,n){n||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2)n[a]=e+t[a+1]*s,n[a+1]=i+t[a]*r;return n}static _translate(t,e,i,s){s||=new Float32Array(t.length);for(let r=0,n=t.length;r<n;r+=2)s[r]=e+t[r],s[r+1]=i+t[r+1];return s}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,s,r){switch(r){case 90:return[1-e/i,t/s];case 180:return[1-t/i,1-e/s];case 270:return[e/i,1-t/s];default:return[t/i,e/s]}}static createBezierPoints(t,e,i,s,r,n){return[(t+5*i)/6,(e+5*s)/6,(5*i+r)/6,(5*s+n)/6,(i+r)/2,(s+n)/2]}},wa=class t{#t;#e=[];#i;#s;#r=[];#n=new Float32Array(18);#a;#o;#l;#h;#d;#c;#u=[];static#p=8;static#g=2;static#m=t.#p+t.#g;constructor({x:e,y:i},s,r,n,a,o=0){this.#t=s,this.#c=n*r,this.#s=a,this.#n.set([NaN,NaN,NaN,NaN,e,i],6),this.#i=o,this.#h=t.#p*r,this.#l=t.#m*r,this.#d=r,this.#u.push(e,i)}isEmpty(){return isNaN(this.#n[8])}#f(){let t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[i,s,r,n]=this.#t;return[(this.#a+(t[0]-e[0])/2-i)/r,(this.#o+(t[1]-e[1])/2-s)/n,(this.#a+(e[0]-t[0])/2-i)/r,(this.#o+(e[1]-t[1])/2-s)/n]}add({x:t,y:e}){this.#a=t,this.#o=e;let[i,s,r,n]=this.#t,[a,o,l,h]=this.#n.subarray(8,12),d=t-l,c=e-h,u=Math.hypot(d,c);if(u<this.#l)return!1;let p=u-this.#h,g=p/u,m=g*d,f=g*c,b=a,v=o;a=l,o=h,l+=m,h+=f,this.#u?.push(t,e);let y=m/p,A=-f/p*this.#c,w=y*this.#c;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,h+w],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,h-w],16),isNaN(this.#n[6])?(0===this.#r.length&&(this.#n.set([a+A,o+w],2),this.#r.push(NaN,NaN,NaN,NaN,(a+A-i)/r,(o+w-s)/n),this.#n.set([a-A,o-w],14),this.#e.push(NaN,NaN,NaN,NaN,(a-A-i)/r,(o-w-s)/n)),this.#n.set([b,v,a,o,l,h],6),!this.isEmpty()):(this.#n.set([b,v,a,o,l,h],6),Math.abs(Math.atan2(v-o,b-a)-Math.atan2(f,m))<Math.PI/2?([a,o,l,h]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((a+l)/2-i)/r,((o+h)/2-s)/n),[a,o,b,v]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((b+a)/2-i)/r,((v+o)/2-s)/n),!0):([b,v,a,o,l,h]=this.#n.subarray(0,6),this.#r.push(((b+5*a)/6-i)/r,((v+5*o)/6-s)/n,((5*a+l)/6-i)/r,((5*o+h)/6-s)/n,((a+l)/2-i)/r,((o+h)/2-s)/n),[l,h,a,o,b,v]=this.#n.subarray(12,18),this.#e.push(((b+5*a)/6-i)/r,((v+5*o)/6-s)/n,((5*a+l)/6-i)/r,((5*o+h)/6-s)/n,((a+l)/2-i)/r,((o+h)/2-s)/n),!0))}toSVGPath(){if(this.isEmpty())return"";let t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#b();let i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#y(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#v(i),i.join(" ")}#b(){let[t,e,i,s]=this.#t,[r,n,a,o]=this.#f();return`M${(this.#n[2]-t)/i} ${(this.#n[3]-e)/s} L${(this.#n[4]-t)/i} ${(this.#n[5]-e)/s} L${r} ${n} L${a} ${o} L${(this.#n[16]-t)/i} ${(this.#n[17]-e)/s} L${(this.#n[14]-t)/i} ${(this.#n[15]-e)/s} Z`}#v(t){let e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#y(t){let[e,i,s,r]=this.#t,n=this.#n.subarray(4,6),a=this.#n.subarray(16,18),[o,l,h,d]=this.#f();t.push(`L${(n[0]-e)/s} ${(n[1]-i)/r} L${o} ${l} L${h} ${d} L${(a[0]-e)/s} ${(a[1]-i)/r}`)}newFreeDrawOutline(t,e,i,s,r,n){return new xa(t,e,i,s,r,n)}getOutlines(){let t=this.#r,e=this.#e,i=this.#n,[s,r,n,a]=this.#t,o=new Float32Array((this.#u?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#u[t]-s)/n,o[t+1]=(this.#u[t+1]-r)/a;if(o[o.length-2]=(this.#a-s)/n,o[o.length-1]=(this.#o-r)/a,isNaN(i[6])&&!this.isEmpty())return this.#A(o);let l=new Float32Array(this.#r.length+24+this.#e.length),h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#x(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#w(l,h),this.newFreeDrawOutline(l,o,this.#t,this.#d,this.#i,this.#s)}#A(t){let e=this.#n,[i,s,r,n]=this.#t,[a,o,l,h]=this.#f(),d=new Float32Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-i)/r,(e[3]-s)/n,NaN,NaN,NaN,NaN,(e[4]-i)/r,(e[5]-s)/n,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/r,(e[17]-s)/n,NaN,NaN,NaN,NaN,(e[14]-i)/r,(e[15]-s)/n],0),this.newFreeDrawOutline(d,t,this.#t,this.#d,this.#i,this.#s)}#w(t,e){let i=this.#e;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#x(t,e){let i=this.#n.subarray(4,6),s=this.#n.subarray(16,18),[r,n,a,o]=this.#t,[l,h,d,c]=this.#f();return t.set([NaN,NaN,NaN,NaN,(i[0]-r)/a,(i[1]-n)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-r)/a,(s[1]-n)/o],e),e+24}},xa=class extends Aa{#t;#e=new Float32Array(4);#i;#s;#r;#n;#a;constructor(t,e,i,s,r,n){super(),this.#a=t,this.#r=e,this.#t=i,this.#n=s,this.#i=r,this.#s=n,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#o(n);let[a,o,l,h]=this.#e;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-a)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-a)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){let t=[`M${this.#a[4]} ${this.#a[5]}`];for(let e=6,i=this.#a.length;e<i;e+=6)isNaN(this.#a[e])?t.push(`L${this.#a[e+4]} ${this.#a[e+5]}`):t.push(`C${this.#a[e]} ${this.#a[e+1]} ${this.#a[e+2]} ${this.#a[e+3]} ${this.#a[e+4]} ${this.#a[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,s],r){let n,a,o=i-t,l=s-e;switch(r){case 0:n=Aa._rescale(this.#a,t,s,o,-l),a=Aa._rescale(this.#r,t,s,o,-l);break;case 90:n=Aa._rescaleAndSwap(this.#a,t,e,o,l),a=Aa._rescaleAndSwap(this.#r,t,e,o,l);break;case 180:n=Aa._rescale(this.#a,i,e,-o,l),a=Aa._rescale(this.#r,i,e,-o,l);break;case 270:n=Aa._rescaleAndSwap(this.#a,i,s,-o,-l),a=Aa._rescaleAndSwap(this.#r,i,s,-o,-l)}return{outline:Array.from(n),points:[Array.from(a)]}}#o(t){let e=this.#a,i=e[4],s=e[5],r=[i,s,i,s],n=i,a=s,o=i,l=s,h=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,c=e.length;t<c;t+=6){let c=e[t+4],u=e[t+5];isNaN(e[t])?(Ke.pointBoundingBox(c,u,r),a>u?(n=c,a=u):a===u&&(n=h(n,c)),l<u?(o=c,l=u):l===u&&(o=h(o,c))):(d.set(Vt,0),Ke.bezierBoundingBox(i,s,...e.slice(t,t+6),d),Ke.rectBoundingBox(...d,r),a>d[1]?(n=d[0],a=d[1]):a===d[1]&&(n=h(n,d[0])),l<d[3]?(o=d[2],l=d[3]):l===d[3]&&(o=h(o,d[2]))),i=c,s=u}let c=this.#e;c[0]=r[0]-this.#i,c[1]=r[1]-this.#i,c[2]=r[2]-r[0]+2*this.#i,c[3]=r[3]-r[1]+2*this.#i,this.firstPoint=[n,a],this.lastPoint=[o,l]}get box(){return this.#e}newOutliner(t,e,i,s,r,n=0){return new wa(t,e,i,s,r,n)}getNewOutline(t,e){let[i,s,r,n]=this.#e,[a,o,l,h]=this.#t,d=r*l,c=n*h,u=i*l+a,p=s*h+o,g=this.newOutliner({x:this.#r[0]*d+u,y:this.#r[1]*c+p},this.#t,this.#n,t,this.#s,e??this.#i);for(let t=2;t<this.#r.length;t+=2)g.add({x:this.#r[t]*d+u,y:this.#r[t+1]*c+p});return g.getOutlines()}},_a=class{#t;#e;#i;#s=[];#r=[];constructor(t,e=0,i=0,s=!0){let r=Vt.slice(),n=1e-4;for(let{x:i,y:s,width:a,height:o}of t){let t=Math.floor((i-e)/n)*n,l=Math.ceil((i+a+e)/n)*n,h=Math.floor((s-e)/n)*n,d=Math.ceil((s+o+e)/n)*n,c=[t,h,d,!0],u=[l,h,d,!1];this.#s.push(c,u),Ke.rectBoundingBox(t,h,l,d,r)}let a=r[2]-r[0]+2*i,o=r[3]-r[1]+2*i,l=r[0]-i,h=r[1]-i,d=s?-1/0:1/0,c=1/0,u=this.#s.at(s?-1:-2),p=[u[0],u[2]];for(let t of this.#s){let[e,i,r,n]=t;!n&&s?i<c?(c=i,d=e):i===c&&(d=Math.max(d,e)):n&&!s&&(i<c?(c=i,d=e):i===c&&(d=Math.min(d,e))),t[0]=(e-l)/a,t[1]=(i-h)/o,t[2]=(r-h)/o}this.#t=new Float32Array([l,h,a,o]),this.#e=[d,c],this.#i=p}getOutlines(){this.#s.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);let t=[];for(let e of this.#s)e[3]?(t.push(...this.#h(e)),this.#o(e)):(this.#l(e),t.push(...this.#h(e)));return this.#n(t)}#n(t){let e=[],i=new Set;for(let i of t){let[t,s,r]=i;e.push([t,s,i],[t,r,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,s=e.length;t<s;t+=2){let s=e[t][2],r=e[t+1][2];s.push(r),r.push(s),i.add(s),i.add(r)}let s,r=[];for(;i.size>0;){let t=i.values().next().value,[e,n,a,o,l]=t;i.delete(t);let h=e,d=n;for(s=[e,a],r.push(s);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,n,a,o,l]=t,h!==e&&(s.push(h,d,e,d===n?n:a),h=e),d=d===n?a:n}s.push(h,d)}return new Sa(r,this.#t,this.#e,this.#i)}#a(t){let e=this.#r,i=0,s=e.length-1;for(;i<=s;){let r=i+s>>1,n=e[r][0];if(n===t)return r;n<t?i=r+1:s=r-1}return s+1}#o([,t,e]){let i=this.#a(t);this.#r.splice(i,0,[t,e])}#l([,t,e]){let i=this.#a(t);for(let s=i;s<this.#r.length;s++){let[i,r]=this.#r[s];if(i!==t)break;if(i===t&&r===e)return void this.#r.splice(s,1)}for(let s=i-1;s>=0;s--){let[i,r]=this.#r[s];if(i!==t)break;if(i===t&&r===e)return void this.#r.splice(s,1)}}#h(t){let[e,i,s]=t,r=[[e,i,s]],n=this.#a(s);for(let t=0;t<n;t++){let[i,s]=this.#r[t];for(let t=0,n=r.length;t<n;t++){let[,a,o]=r[t];if(!(s<=a||o<=i)){if(a>=i){if(o>s)r[t][1]=s;else{if(1===n)return[];r.splice(t,1),t--,n--}continue}r[t][2]=i,o>s&&r.push([e,s,o])}}}return r}},Sa=class extends Aa{#t;#e;constructor(t,e,i,s){super(),this.#e=t,this.#t=e,this.firstPoint=i,this.lastPoint=s}toSVGPath(){let t=[];for(let e of this.#e){let[i,s]=e;t.push(`M${i} ${s}`);for(let r=2;r<e.length;r+=2){let n=e[r],a=e[r+1];n===i?(t.push(`V${a}`),s=a):a===s&&(t.push(`H${n}`),i=n)}t.push("Z")}return t.join(" ")}serialize([t,e,i,s],r){let n=[],a=i-t,o=s-e;for(let e of this.#e){let i=new Array(e.length);for(let r=0;r<e.length;r+=2)i[r]=t+e[r]*a,i[r+1]=s-e[r+1]*o;n.push(i)}return n}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}},Ca=class extends wa{newFreeDrawOutline(t,e,i,s,r,n){return new Ea(t,e,i,s,r,n)}},Ea=class extends xa{newOutliner(t,e,i,s,r,n=0){return new Ca(t,e,i,s,r,n)}},ka=class t extends Ji{#t=null;#e=0;#i;#s=null;#r=null;#n=null;#a=null;#o=0;#l=null;#h=null;#d=null;#c=!1;#u=null;#p=null;#g=null;#m="";#f;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=oe.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let e=t.prototype;return He(this,"_keyboardManager",new Wi([[["ArrowLeft","mac+ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],e._moveCaret,{args:[3]}]]))}constructor(e){super({...e,name:"highlightEditor"}),this.color=e.color||t._defaultColor,this.#f=e.thickness||t._defaultThickness,this.opacity=e.opacity||t._defaultOpacity,this.#i=e.boxes||null,this.#b=e.methodOfCreation||"",this.#m=e.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",e.highlightId>-1?(this.#c=!0,this.#y(e),this.#S()):this.#i&&(this.#t=e.anchorNode,this.#e=e.anchorOffset,this.#a=e.focusNode,this.#o=e.focusOffset,this.#v(),this.#S(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(Ji._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#c?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#f,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#v(){let t=new _a(this.#i,.001);this.#h=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#h.box;let e=new _a(this.#i,.0025,.001,"ltr"===this._uiManager.direction);this.#n=e.getOutlines();let{firstPoint:i}=this.#h;this.#u=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];let{lastPoint:s}=this.#n;this.#p=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#y({highlightOutlines:e,highlightId:i,clipPathId:s}){this.#h=e;if(this.#n=e.getNewOutline(this.#f/2+1.5,.0025),i>=0)this.#d=i,this.#s=s,this.parent.drawLayer.finalizeDraw(i,{bbox:e.box,path:{d:e.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){let i=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:t.#C(this.#h.box,(i-this.rotation+360)%360),path:{d:e.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:t.#C(this.#n.box,i),path:{d:this.#n.toSVGPath()}})}let[r,n,a,o]=e.box;switch(this.rotation){case 0:this.x=r,this.y=n,this.width=a,this.height=o;break;case 90:{let[t,e]=this.parentDimensions;this.x=n,this.y=1-r,this.width=a*e/t,this.height=o*t/e;break}case 180:this.x=1-r,this.y=1-n,this.width=a,this.height=o;break;case 270:{let[t,e]=this.parentDimensions;this.x=1-n,this.y=r,this.width=a*e/t,this.height=o*t/e;break}}let{firstPoint:l}=e;this.#u=[(l[0]-r)/a,(l[1]-n)/o];let{lastPoint:h}=this.#n;this.#p=[(h[0]-r)/a,(h[1]-n)/o]}static initialize(e,i){Ji.initialize(e,i),t._defaultColor||=i.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(e,i){switch(e){case le.HIGHLIGHT_COLOR:t._defaultColor=i;break;case le.HIGHLIGHT_THICKNESS:t._defaultThickness=i}}translateInPage(t,e){}get toolbarPosition(){return this.#p}get commentButtonPosition(){return this.#u}updateParams(t,e){switch(t){case le.HIGHLIGHT_COLOR:this.#A(e);break;case le.HIGHLIGHT_THICKNESS:this.#w(e)}}static get defaultPropertiesToUpdate(){return[[le.HIGHLIGHT_COLOR,t._defaultColor],[le.HIGHLIGHT_THICKNESS,t._defaultThickness]]}get propertiesToUpdate(){return[[le.HIGHLIGHT_COLOR,this.color||t._defaultColor],[le.HIGHLIGHT_THICKNESS,this.#f||t._defaultThickness],[le.HIGHLIGHT_FREE,this.#c]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#r?.updateColor(this.color),super.onUpdatedColor()}#A(e){let i=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},s=this.color,r=this.opacity;this.addCommands({cmd:i.bind(this,e,t._defaultOpacity),undo:i.bind(this,s,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:le.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(e)},!0)}#w(t){let e=this.#f,i=t=>{this.#f=t,this.#x(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:le.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",this.#r=new Ln({editor:this})]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#T())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#T())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#_(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#S(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#_():t&&(this.#S(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#x(t){this.#c&&(this.#y({highlightOutlines:this.#h.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#_(){null===this.#d||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#S(t=this.parent){null===this.#d&&(({id:this.#d,clipPathId:this.#s}=t.drawLayer.draw({bbox:this.#h.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#c},path:{d:this.#h.toSVGPath()}},!1,!0)),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#c},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#c),this.#l&&(this.#l.style.clipPath=this.#s))}static#C([t,e,i,s],r){switch(r){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(e){let i,{drawLayer:s}=this.parent;this.#c?(e=(e-this.rotation+360)%360,i=t.#C(this.#h.box,e)):i=t.#C([this.x,this.y,this.width,this.height],e),s.updateProperties(this.#d,{bbox:i,root:{"data-main-rotation":e}}),s.updateProperties(this.#g,{bbox:t.#C(this.#n.box,e),root:{"data-main-rotation":e}})}render(){if(this.div)return this.div;let t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#c?t.classList.add("free"):this.div.addEventListener("keydown",this.#E.bind(this),{signal:this._uiManager._signal});let e=this.#l=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#s,this.setDims(),ji(this,this.#l,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#E(e){t._keyboardManager.exec(this,e)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#k(!0);break;case 1:case 3:this.#k(!1)}}#k(t){if(!this.#t)return;let e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#a,this.#o)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#c||this.#k(!1))}get _mustFixPosition(){return!this.#c}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#T(){return this.#c?this.rotation:0}#M(){if(this.#c)return null;let[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,r=this.#i,n=new Float32Array(8*r.length),a=0;for(let{x:o,y:l,width:h,height:d}of r){let r=o*t+i,c=(1-l)*e+s;n[a]=n[a+4]=r,n[a+1]=n[a+3]=c,n[a+2]=n[a+6]=r+h*t,n[a+5]=n[a+7]=c-d*e,a+=8}return n}#P(t){return this.#h.serialize(t,this.#T())}static startHighlighting(t,e,{target:i,x:s,y:r}){let{x:n,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#I(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",vi,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",bi,{signal:d}),i.addEventListener("pointermove",this.#D.bind(this,t),{signal:d}),this._freeHighlight=new Ca({x:s,y:r},[n,a,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#D(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#I(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(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 async deserialize(t,e,i){let s=null;if(t instanceof ca){let{data:{quadPoints:e,rect:i,rotation:r,id:n,color:a,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:oe.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:r,annotationElementId:n,id:n,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}else if(t instanceof da){let{data:{inkLists:e,rect:i,rotation:r,id:n,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;s=t={annotationType:oe.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:r,annotationElementId:n,id:n,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}let{color:r,quadPoints:n,inkLists:a,outlines:o,opacity:l}=t,h=await super.deserialize(t,e,i);h.color=Ke.makeHexColor(...r),h.opacity=l||1,a&&(h.#f=t.thickness),h._initialData=s,t.comment&&h.setCommentData(t);let[d,c]=h.pageDimensions,[u,p]=h.pageTranslation;if(n){let t=h.#i=[];for(let e=0;e<n.length;e+=8)t.push({x:(n[e]-u)/d,y:1-(n[e+1]-p)/c,width:(n[e+2]-n[e])/d,height:(n[e+1]-n[e+5])/c});h.#v(),h.#S(),h.rotate(h.rotation)}else if(a||o){h.#c=!0;let t=(a||o.points)[0],i={x:t[0]-u,y:c-(t[1]-p)},s=new Ca(i,[0,0,d,c],1,h.#f/2,!0,.001);for(let e=0,r=t.length;e<r;e+=2)i.x=t[e]-u,i.y=c-(t[e+1]-p),s.add(i);let{id:r,clipPathId:n}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:s.toSVGPath()}},!0,!0);h.#y({highlightOutlines:s.getOutlines(),highlightId:r,clipPathId:n}),h.#S(),h.rotate(h.parentRotation)}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();let e=Ji._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#f,quadPoints:this.#M(),outlines:this.#P(i.rect)}),this.addComment(i),this.annotationElementId&&!this.#F(i)?null:(i.id=this.annotationElementId,i)}#F(t){let{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}},Ta=class{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(let[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){let t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){Oe("Not implemented")}},Ma=class t extends Ji{#t=null;#e;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#i=null;static#s=null;static#r=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){t.drawOutlines&&(this.#n(t),this.#l())}#n({drawOutlines:t,drawId:e,drawingOptions:i}){this.#t=t,this._drawingOptions||=i,this.annotationElementId||this._uiManager.a11yAlert(Ji._l10nAlert[this.editorType]),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#a(t,this.parent),this.#c(t.box)}#a(e,i){let{id:s}=i.drawLayer.draw(t._mergeSVGProperties(this._drawingOptions.toSVGProperties(),e.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){let i=new Set(Object.keys(t));for(let[s,r]of Object.entries(e))i.has(s)?Object.assign(t[s],r):t[s]=r;return t}static getDefaultDrawingOptions(t){Oe("Not implemented")}static get typesMap(){Oe("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(e,i){let s=this.typesMap.get(e);s&&this._defaultDrawingOptions.updateProperty(s,i),this._currentParent&&(t.#i.updateProperty(s,i),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){let i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){let t=[],e=this._defaultDrawingOptions;for(let[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){let t=[],{_drawingOptions:e}=this;for(let[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){let s=this._drawingOptions,r=s[e],n=i=>{s.updateProperty(e,i);let r=this.#t.updateProperty(e,i);r&&this.#c(r),this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:n.bind(this,i),undo:n.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){let i=this.constructor.typesMap.get(this.colorType),s=this.constructor.typesMap.get(this.opacityType),r=this._drawingOptions,n=r[i],a=r[s],o=(t,e)=>{r.updateProperty(i,t),r.updateProperty(s,e),this.#t.updateProperty(i,t),this.#t.updateProperty(s,e),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:o.bind(this,t,e),undo:o.bind(this,n,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:le.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,t._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#d()),{bbox:this.#u()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,t._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#d()),{bbox:this.#u()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#u()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,t._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#d(),this.parentDimensions),{bbox:this.#u()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#o(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#l(),this.#c(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#o()):t&&(this._uiManager.addShouldRescale(this),this.#l(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#o(){null===this._drawId||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#l(t=this.parent){if(null===this._drawId||this.parent!==t){if(null!==this._drawId)return void this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);this._drawingOptions.updateAll(),this._drawId=this.#a(this.#t,t)}}#h([t,e,i,s]){let{parentDimensions:[r,n],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(n/r),s*(r/n)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(n/r),s*(r/n)];default:return[t,e,i,s]}}#d(){let{x:t,y:e,width:i,height:s,parentDimensions:[r,n],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(r/n),s*(n/r)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(r/n),s*(n/r)];default:return[t,e,i,s]}}#c(t){[this.x,this.y,this.width,this.height]=this.#h(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#u(){let{x:t,y:e,width:i,height:s,rotation:r,parentRotation:n,parentDimensions:[a,o]}=this;switch((4*r+n)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(a/o),s*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),s*(o/a)];case 6:return[1-t-s*(o/a),1-e,s*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-s*(o/a),i*(a/o),s*(o/a)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/a),e,s*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-s*(o/a),i*(a/o),s*(o/a)];case 14:return[1-t,1-e-i*(a/o),s*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),s*(o/a)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,t._mergeSVGProperties({bbox:this.#u()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#c(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);let i=super.render();i.classList.add("draw");let s=document.createElement("div");return i.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,s,r){Oe("Not implemented")}static startDrawing(e,i,s,r){let{target:n,offsetX:a,offsetY:o,pointerId:l,pointerType:h}=r;if($i.isInitializedAndDifferentPointerType(h))return;let{viewport:{rotation:d}}=e,{width:c,height:u}=n.getBoundingClientRect(),p=t.#s=new AbortController,g=e.combinedSignal(p);$i.setPointer(h,l),window.addEventListener("pointerup",t=>{$i.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:g}),window.addEventListener("pointercancel",t=>{$i.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:g}),window.addEventListener("pointerdown",e=>{$i.isSamePointerType(e.pointerType)&&($i.initializeAndAddPointerId(e.pointerId),t.#i.isCancellable()&&(t.#i.removeLastElement(),t.#i.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",bi,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",t=>{$i.isSameTimeStamp(t.timeStamp)&&vi(t)},{signal:g}),e.toggleDrawing(),i._editorUndoBar?.hide(),t.#i?e.drawLayer.updateProperties(this._currentDrawId,t.#i.startNew(a,o,c,u,d)):(i.updateUIForDefaultProperties(this),t.#i=this.createDrawerInstance(a,o,c,u,d),t.#r=this.getDefaultDrawingOptions(),this._currentParent=e,({id:this._currentDrawId}=e.drawLayer.draw(this._mergeSVGProperties(t.#r.toSVGProperties(),t.#i.defaultSVGProperties),!0,!1)))}static _drawMove(e){if($i.isSameTimeStamp(e.timeStamp),!t.#i)return;let{offsetX:i,offsetY:s,pointerId:r}=e;if($i.isSamePointerId(r)){if($i.isUsingMultiplePointers())return void this._endDraw(e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,t.#i.add(i,s)),$i.setTimeStamp(e.timeStamp),vi(e)}}static _cleanup(e){e&&(this._currentDrawId=-1,this._currentParent=null,t.#i=null,t.#r=null,$i.clearTimeStamp()),t.#s&&(t.#s.abort(),t.#s=null,$i.clearPointerIds())}static _endDraw(e){let i=this._currentParent;if(i){if(i.toggleDrawing(!0),this._cleanup(!1),e?.target===i.div&&i.drawLayer.updateProperties(this._currentDrawId,t.#i.end(e.offsetX,e.offsetY)),this.supportMultipleDrawings){let e=t.#i,s=this._currentDrawId,r=e.getLastElement();return void i.addCommands({cmd:()=>{i.drawLayer.updateProperties(s,e.setLastElement(r))},undo:()=>{i.drawLayer.updateProperties(s,e.removeLastElement())},mustExec:!1,type:le.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(e){let i=this._currentParent;if(!i)return null;if(i.toggleDrawing(!0),i.cleanUndoStack(le.DRAW_STEP),!t.#i.isEmpty()){let{pageDimensions:[s,r],scale:n}=i,a=i.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:t.#i.getOutlines(s*n,r*n,n,this._INNER_MARGIN),drawingOptions:t.#r,mustBeCommitted:!e});return this._cleanup(!0),a}return i.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,r,n){Oe("Not implemented")}static async deserialize(t,e,i){let{rawDims:{pageWidth:s,pageHeight:r,pageX:n,pageY:a}}=e.viewport,o=this.deserializeDraw(n,a,s,r,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#n({drawOutlines:o}),l.#l(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){let[e,i]=this.pageTranslation,[s,r]=this.pageDimensions;return this.#t.serialize([e,i,s,r],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}},Pa=class{#t=new Float64Array(6);#e;#i;#s;#r;#n;#a="";#o=0;#l=new Da;#h;#d;constructor(t,e,i,s,r,n){this.#h=i,this.#d=s,this.#s=r,this.#r=n,[t,e]=this.#c(t,e);let a=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#i=[{line:a,points:this.#n}],this.#t.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#r=e)}#c(t,e){return Aa._normalizePoint(t,e,this.#h,this.#d,this.#s)}isEmpty(){return!this.#i||0===this.#i.length}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#c(t,e);let[i,s,r,n]=this.#t.subarray(2,6),a=t-r,o=e-n;return Math.hypot(this.#h*a,this.#d*o)<=2?null:(this.#n.push(t,e),isNaN(i)?(this.#t.set([r,n,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([i,s,r,n,t,e],0),this.#e.push(...Aa.createBezierPoints(i,s,r,n,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){return this.add(t,e)||(2===this.#n.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,r){this.#h=i,this.#d=s,this.#s=r,[t,e]=this.#c(t,e);let n=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];let a=this.#i.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#i.push({line:n,points:this.#n}),this.#t.set(n,0),this.#o=0,this.toSVGPath(),null}getLastElement(){return this.#i.at(-1)}setLastElement(t){return this.#i?(this.#i.push(t),this.#e=t.line,this.#n=t.points,this.#o=0,{path:{d:this.toSVGPath()}}):this.#l.setLastElement(t)}removeLastElement(){if(!this.#i)return this.#l.removeLastElement();this.#i.pop(),this.#a="";for(let t=0,e=this.#i.length;t<e;t++){let{line:e,points:i}=this.#i[t];this.#e=e,this.#n=i,this.#o=0,this.toSVGPath()}return{path:{d:this.#a}}}toSVGPath(){let t=Aa.svgRound(this.#e[4]),e=Aa.svgRound(this.#e[5]);if(2===this.#n.length)return this.#a=`${this.#a} M ${t} ${e} Z`,this.#a;if(this.#n.length<=6){let i=this.#a.lastIndexOf("M");this.#a=`${this.#a.slice(0,i)} M ${t} ${e}`,this.#o=6}if(4===this.#n.length){let t=Aa.svgRound(this.#e[10]),e=Aa.svgRound(this.#e[11]);return this.#a=`${this.#a} L ${t} ${e}`,this.#o=12,this.#a}let i=[];0===this.#o&&(i.push(`M ${t} ${e}`),this.#o=6);for(let t=this.#o,e=this.#e.length;t<e;t+=6){let[e,s,r,n,a,o]=this.#e.slice(t,t+6).map(Aa.svgRound);i.push(`C${e} ${s} ${r} ${n} ${a} ${o}`)}return this.#a+=i.join(" "),this.#o=this.#e.length,this.#a}getOutlines(t,e,i,s){let r=this.#i.at(-1);return r.line=new Float32Array(r.line),r.points=new Float32Array(r.points),this.#l.build(this.#i,t,e,i,this.#s,this.#r,s),this.#t=null,this.#e=null,this.#i=null,this.#a=null,this.#l}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}},Da=class extends Aa{#t;#e=0;#i;#s;#r;#n;#a;#o;#l;build(t,e,i,s,r,n,a){this.#r=e,this.#n=i,this.#a=s,this.#o=r,this.#l=n,this.#i=a??0,this.#s=t,this.#c()}get thickness(){return this.#l}setLastElement(t){return this.#s.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#s.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){let t=[];for(let{line:e}of this.#s)if(t.push(`M${Aa.svgRound(e[4])} ${Aa.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Aa.svgRound(e[10])} ${Aa.svgRound(e[11])}`);else for(let i=6,s=e.length;i<s;i+=6){let[s,r,n,a,o,l]=e.subarray(i,i+6).map(Aa.svgRound);t.push(`C${s} ${r} ${n} ${a} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,s],r){let n,a,o,l,h,d,c,u,p,g=[],m=[],[f,b,v,y]=this.#d();switch(this.#o){case 0:p=Aa._rescale,n=t,a=e+s,o=i,l=-s,h=t+f*i,d=e+(1-b-y)*s,c=t+(f+v)*i,u=e+(1-b)*s;break;case 90:p=Aa._rescaleAndSwap,n=t,a=e,o=i,l=s,h=t+b*i,d=e+f*s,c=t+(b+y)*i,u=e+(f+v)*s;break;case 180:p=Aa._rescale,n=t+i,a=e,o=-i,l=s,h=t+(1-f-v)*i,d=e+b*s,c=t+(1-f)*i,u=e+(b+y)*s;break;case 270:p=Aa._rescaleAndSwap,n=t+i,a=e+s,o=-i,l=-s,h=t+(1-b-y)*i,d=e+(1-f-v)*s,c=t+(1-b)*i,u=e+(1-f)*s}for(let{line:t,points:e}of this.#s)g.push(p(t,n,a,o,l,r?new Array(t.length):null)),m.push(p(e,n,a,o,l,r?new Array(e.length):null));return{lines:g,points:m,rect:[h,d,c,u]}}static deserialize(t,e,i,s,r,{paths:{lines:n,points:a},rotation:o,thickness:l}){let h,d,c,u,p,g=[];switch(o){case 0:p=Aa._rescale,h=-t/i,d=e/s+1,c=1/i,u=-1/s;break;case 90:p=Aa._rescaleAndSwap,h=-e/s,d=-t/i,c=1/s,u=1/i;break;case 180:p=Aa._rescale,h=t/i+1,d=-e/s,c=-1/i,u=1/s;break;case 270:p=Aa._rescaleAndSwap,h=e/s+1,d=t/i+1,c=-1/s,u=-1/i}if(!n){n=[];for(let t of a){let e=t.length;if(2===e){n.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){n.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}let i=new Float32Array(3*(e-2));n.push(i);let[s,r,a,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,s,r],0);for(let n=4;n<e;n+=2){let e=t[n],l=t[n+1];i.set(Aa.createBezierPoints(s,r,a,o,e,l),3*(n-2)),[s,r,a,o]=[a,o,e,l]}}}for(let t=0,e=n.length;t<e;t++)g.push({line:p(n[t].map(t=>t??NaN),h,d,c,u),points:p(a[t].map(t=>t??NaN),h,d,c,u)});let m=new this.prototype.constructor;return m.build(g,i,s,1,o,l,r),m}#h(t=this.#l){let e=this.#i+t/2*this.#a;return this.#o%180==0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){let[t,e,i,s]=this.#t,[r,n]=this.#h(0);return[t+r,e+n,i-2*r,s-2*n]}#c(){let t=this.#t=Wt.slice();for(let{line:e}of this.#s){if(e.length<=12){for(let i=4,s=e.length;i<s;i+=6)Ke.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],s=e[5];for(let r=6,n=e.length;r<n;r+=6){let[n,a,o,l,h,d]=e.subarray(r,r+6);Ke.bezierBoundingBox(i,s,n,a,o,l,h,d,t),i=h,s=d}}let[e,i]=this.#h();t[0]=ri(t[0]-e,0,1),t[1]=ri(t[1]-i,0,1),t[2]=ri(t[2]+e,0,1),t[3]=ri(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return"stroke-width"===t?this.#u(e):null}#u(t){let[e,i]=this.#h();this.#l=t;let[s,r]=this.#h(),[n,a]=[s-e,r-i],o=this.#t;return o[0]-=n,o[1]-=a,o[2]+=2*n,o[3]+=2*a,o}updateParentDimensions([t,e],i){let[s,r]=this.#h();this.#r=t,this.#n=e,this.#a=i;let[n,a]=this.#h(),o=n-s,l=a-r,h=this.#t;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(Aa.svgRound).join(" ")}get defaultProperties(){let[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Aa.svgRound(t)} ${Aa.svgRound(e)}`}}}get rotationTransform(){let[,,t,e]=this.#t,i=0,s=0,r=0,n=0,a=0,o=0;switch(this.#e){case 90:s=e/t,r=-t/e,a=t;break;case 180:i=-1,n=-1,a=t,o=e;break;case 270:s=-e/t,r=t/e,o=e;break;default:return""}return`matrix(${i} ${s} ${r} ${n} ${Aa.svgRound(a)} ${Aa.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,s]){let[r,n]=this.#h(),[a,o,l,h]=this.#t;if(Math.abs(l-r)<=Aa.PRECISION||Math.abs(h-n)<=Aa.PRECISION){let r=t+i/2-(a+l/2),n=e+s/2-(o+h/2);return{path:{"transform-origin":`${Aa.svgRound(t)} ${Aa.svgRound(e)}`,transform:`${this.rotationTransform} translate(${r} ${n})`}}}let d=(i-2*r)/(l-2*r),c=(s-2*n)/(h-2*n),u=l/i,p=h/s;return{path:{"transform-origin":`${Aa.svgRound(a)} ${Aa.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Aa.svgRound(r)} ${Aa.svgRound(n)}) scale(${d} ${c}) translate(${Aa.svgRound(-r)} ${Aa.svgRound(-n)})`}}}getPathResizedSVGProperties([t,e,i,s]){let[r,n]=this.#h(),a=this.#t,[o,l,h,d]=a;if(a[0]=t,a[1]=e,a[2]=i,a[3]=s,Math.abs(h-r)<=Aa.PRECISION||Math.abs(d-n)<=Aa.PRECISION){let r=t+i/2-(o+h/2),n=e+s/2-(l+d/2);for(let{line:t,points:e}of this.#s)Aa._translate(t,r,n,t),Aa._translate(e,r,n,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Aa.svgRound(t)} ${Aa.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}let c=(i-2*r)/(h-2*r),u=(s-2*n)/(d-2*n),p=-c*(o+r)+t+r,g=-u*(l+n)+e+n;if(1!==c||1!==u||0!==p||0!==g)for(let{line:t,points:e}of this.#s)Aa._rescale(t,p,g,c,u,t),Aa._rescale(e,p,g,c,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Aa.svgRound(t)} ${Aa.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){let[s,r]=i,n=this.#t,a=t-n[0],o=e-n[1];if(this.#r===s&&this.#n===r)for(let{line:t,points:e}of this.#s)Aa._translate(t,a,o,t),Aa._translate(e,a,o,e);else{let t=this.#r/s,e=this.#n/r;this.#r=s,this.#n=r;for(let{line:i,points:s}of this.#s)Aa._rescale(i,a,o,t,e,i),Aa._rescale(s,a,o,t,e,s);n[2]*=t,n[3]*=e}return n[0]=t,n[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Aa.svgRound(t)} ${Aa.svgRound(e)}`}}}get defaultSVGProperties(){let t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Aa.svgRound(t[0])} ${Aa.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}},Ia=class t extends Ta{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:Ji._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){let e=new t(this._viewParameters);return e.updateAll(this),e}},Fa=class t extends Ma{static _type="ink";static _editorType=oe.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){Ji.initialize(t,e),this._defaultDrawingOptions=new Ia(e.viewParameters)}static getDefaultDrawingOptions(t){let e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return He(this,"typesMap",new Map([[le.INK_THICKNESS,"stroke-width"],[le.INK_COLOR,"stroke"],[le.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,s,r){return new Pa(t,e,i,s,r,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,s,r,n){return Da.deserialize(t,e,i,s,r,n)}static async deserialize(t,e,i){let s=null;if(t instanceof da){let{data:{inkLists:e,rect:i,rotation:r,id:n,color:a,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;s=t={annotationType:oe.INK,color:Array.from(a),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:r,annotationElementId:n,id:n,deleted:!1,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:p}}let r=await super.deserialize(t,e,i);return r._initialData=s,t.comment&&r.setCommentData(t),r}get toolbarButtons(){return this._colorPicker||=new On(this),[["colorPicker",this._colorPicker]]}get colorType(){return le.INK_COLOR}get colorAndOpacityType(){return le.INK_COLOR_AND_OPACITY}get opacityType(){return le.INK_OPACITY}updateParams(t,e){t!==le.INK_COLOR_AND_OPACITY?super.updateParams(t,e):this._updateColorAndOpacity(e.color,e.opacity)}static updateDefaultParams(t,e){if(t===le.INK_COLOR_AND_OPACITY)return super.updateDefaultParams(le.INK_COLOR,e.color),void super.updateDefaultParams(le.INK_OPACITY,e.opacity);super.updateDefaultParams(t,e)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();let{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){let t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:e,thickness:i,opacity:s}){this._drawingOptions=t.getDefaultDrawingOptions({stroke:Ke.makeHexColor(...e),"stroke-width":i,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:s,"stroke-opacity":r,"stroke-width":n}}=this,a=Object.assign(super.serialize(t),{color:Ji._colorManager.convert(s),opacity:r,thickness:n,paths:{lines:e,points:i}});return this.addComment(a),t?(a.isCopy=!0,a):this.annotationElementId&&!this.#t(a)?null:(a.id=this.annotationElementId,a)}#t(t){let{color:e,thickness:i,opacity:s,pageIndex:r}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==s||t.pageIndex!==r}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}},La=class extends Da{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}},Oa=class{static#t={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#e(t,e,i,s){return s-=e,0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#i=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#s(t,e,i,s,r,n,a){let o=this.#e(i,s,r,n);for(let r=0;r<8;r++){let n=(-r+o-a+16)%8;if(0!==t[(i+this.#i[2*n])*e+(s+this.#i[2*n+1])])return n}return-1}static#r(t,e,i,s,r,n,a){let o=this.#e(i,s,r,n);for(let r=0;r<8;r++){let n=(r+o+a+16)%8;if(0!==t[(i+this.#i[2*n])*e+(s+this.#i[2*n+1])])return n}return-1}static#n(t,e,i,s){let r=t.length,n=new Int32Array(r);for(let e=0;e<r;e++)n[e]=t[e]<=s?1:0;for(let t=1;t<i-1;t++)n[t*e]=n[t*e+e-1]=0;for(let t=0;t<e;t++)n[t]=n[e*i-1-t]=0;let a,o=1,l=[];for(let t=1;t<i-1;t++){a=1;for(let i=1;i<e-1;i++){let s=t*e+i,r=n[s];if(0===r)continue;let h=t,d=i;if(1===r&&0===n[s-1])o+=1,d-=1;else{if(!(r>=1&&0===n[s+1])){1!==r&&(a=Math.abs(r));continue}o+=1,d+=1,r>1&&(a=r)}let c,u=[i,t],p=d===i+1,g={isHole:p,points:u,id:o,parent:0};l.push(g);for(let t of l)if(t.id===a){c=t;break}c?c.isHole?g.parent=p?c.parent:a:g.parent=p?a:c.parent:g.parent=p?a:0;let m=this.#s(n,e,t,i,h,d,0);if(-1===m){n[s]=-o,1!==n[s]&&(a=Math.abs(n[s]));continue}let f=this.#i[2*m],b=this.#i[2*m+1],v=t+f,y=i+b;h=v,d=y;let A=t,w=i;for(;;){let r=this.#r(n,e,A,w,h,d,1);f=this.#i[2*r],b=this.#i[2*r+1];let l=A+f,c=w+b;u.push(c,l);let p=A*e+w;if(0===n[p+1]?n[p]=-o:1===n[p]&&(n[p]=o),l===t&&c===i&&A===v&&w===y){1!==n[s]&&(a=Math.abs(n[s]));break}h=A,d=w,A=l,w=c}}}return l}static#a(t,e,i,s){if(i-e<=4){for(let r=e;r<i-2;r+=2)s.push(t[r],t[r+1]);return}let r=t[e],n=t[e+1],a=t[i-4]-r,o=t[i-3]-n,l=Math.hypot(a,o),h=a/l,d=o/l,c=h*n-d*r,u=o/a,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),v=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*v),Math.atan(Math.abs(f-m)*v)),A=0,w=e;for(let s=e+2;s<i-2;s+=2){let e=Math.abs(c-h*t[s+1]+d*t[s]);e>A&&(w=s,A=e)}A>(l*y)**2?(this.#a(t,e,w+2,s),this.#a(t,w,i,s)):s.push(r,n)}static#o(t){let e=[],i=t.length;return this.#a(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#l(t,e,i,s,r,n){let a=new Float32Array(n**2),o=-2*s**2,l=n>>1;for(let t=0;t<n;t++){let e=(t-l)**2;for(let i=0;i<n;i++)a[t*n+i]=Math.exp((e+(i-l)**2)/o)}let h=new Float32Array(256),d=-2*r**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/d);let c=t.length,u=new Uint8Array(c),p=new Uint32Array(256);for(let s=0;s<i;s++)for(let r=0;r<e;r++){let o=s*e+r,d=t[o],c=0,g=0;for(let o=0;o<n;o++){let u=s+o-l;if(!(u<0||u>=i))for(let i=0;i<n;i++){let s=r+i-l;if(s<0||s>=e)continue;let p=t[u*e+s],m=a[o*n+i]*h[Math.abs(p-d)];c+=p*m,g+=m}}p[u[o]=Math.round(c/g)]++}return[u,p]}static#h(t){let e=new Uint32Array(256);for(let i of t)e[i]++;return e}static#d(t){let e=t.length,i=new Uint8ClampedArray(e>>2),s=-1/0,r=1/0;for(let e=0,n=i.length;e<n;e++){let n=i[e]=t[e<<2];s=Math.max(s,n),r=Math.min(r,n)}let n=255/(s-r);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-r)*n;return i}static#c(t){let e,i=-1/0,s=-1/0,r=t.findIndex(t=>0!==t),n=r,a=r;for(e=r;e<256;e++){let r=t[e];r>i&&(e-n>s&&(s=e-n,a=e-1),i=r,n=e)}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#u(t){let e=t,{width:i,height:s}=t,{maxDim:r}=this.#t,n=i,a=s;if(i>r||s>r){let o=i,l=s,h=Math.log2(Math.max(i,s)/r),d=Math.floor(h);h=h===d?d-1:d;for(let i=0;i<h;i++){n=Math.ceil(o/2),a=Math.ceil(l/2);let i=new OffscreenCanvas(n,a);i.getContext("2d").drawImage(t,0,0,o,l,0,0,n,a),o=n,l=a,t!==e&&t.close(),t=i.transferToImageBitmap()}let c=Math.min(r/n,r/a);n=Math.round(n*c),a=Math.round(a*c)}let o=new OffscreenCanvas(n,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,n,a),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,n,a);let l=o.getImageData(0,0,n,a).data;return[this.#d(l),n,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:s},r,n,a,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1}),d=h.font=`${i} ${s} 200px ${e}`,{actualBoundingBoxLeft:c,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),v=1.5,y=Math.ceil(Math.max(Math.abs(c)+Math.abs(u)||0,b)*v),A=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*v);l=new OffscreenCanvas(y,A),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=d,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,y,A),h.fillStyle="black",h.fillText(t,.5*y/2,1.5*A/2);let w=this.#d(h.getImageData(0,0,y,A).data),x=this.#h(w),_=this.#c(x),S=this.#n(w,y,A,_);return this.processDrawnLines({lines:{curves:S,width:y,height:A},pageWidth:r,pageHeight:n,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,s,r){let[n,a,o]=this.#u(t),[l,h]=this.#l(n,a,o,Math.hypot(a,o)*this.#t.sigmaSFactor,this.#t.sigmaR,this.#t.kernelSize),d=this.#c(h),c=this.#n(l,a,o,d);return this.processDrawnLines({lines:{curves:c,width:a,height:o},pageWidth:e,pageHeight:i,rotation:s,innerMargin:r,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:r,mustSmooth:n,areContours:a}){s%180!=0&&([e,i]=[i,e]);let{curves:o,width:l,height:h}=t,d=t.thickness??0,c=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(let{points:t}of o){let e=n?this.#o(t):t;if(!e)continue;m.push(e);let i=e.length,s=new Float32Array(i),r=new Float32Array(3*(2===i?2:i-2));if(c.push({line:r,points:s}),2===i){s[0]=e[0]*p,s[1]=e[1]*g,r.set([NaN,NaN,NaN,NaN,s[0],s[1]],0);continue}let[a,o,l,h]=e;a*=p,o*=g,l*=p,h*=g,s.set([a,o,l,h],0),r.set([NaN,NaN,NaN,NaN,a,o],0);for(let t=4;t<i;t+=2){let i=s[t]=e[t]*p,n=s[t+1]=e[t+1]*g;r.set(Aa.createBezierPoints(a,o,l,h,i,n),3*(t-2)),[a,o,l,h]=[l,h,i,n]}}if(0===c.length)return null;let f=a?new La:new Da;return f.build(c,e,i,1,s,a?0:d,r),{outline:f,newCurves:m,areContours:a,thickness:d,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:s,height:r}){let n,a=1/0,o=-1/0,l=0;for(let e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){let i=e[t]-e[t-2];a=Math.min(a,i),o=Math.max(o,i)}}n=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;let h=t.length,d=8+3*h,c=new Uint32Array(d),u=0;c[u++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*n.BYTES_PER_ELEMENT,c[u++]=0,c[u++]=s,c[u++]=r,c[u++]=e?0:1,c[u++]=Math.max(0,Math.floor(i??0)),c[u++]=h,c[u++]=n.BYTES_PER_ELEMENT;for(let e of t)c[u++]=e.length-2,c[u++]=e[0],c[u++]=e[1];let p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(c);let m=n.prototype.constructor;for(let e of t){let t=new m(e.length-2);for(let i=2,s=e.length;i<s;i++)t[i-2]=e[i]-e[i-2];g.write(t)}return g.close(),(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{let e=Uint8Array.fromBase64(t),{readable:i,writable:s}=new DecompressionStream("deflate-raw"),r=s.getWriter();await r.ready,r.write(e).then(async()=>{await r.ready,await r.close()}).catch(()=>{});let n=null,a=0;for await(let t of i)n||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),n.set(t,a),a+=t.length;let o=new Uint32Array(n.buffer,0,n.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);let h,d=o[2],c=o[3],u=0===o[4],p=o[5],g=o[6],m=o[7],f=[],b=(8+3*g)*Uint32Array.BYTES_PER_ELEMENT;switch(m){case Int8Array.BYTES_PER_ELEMENT:h=new Int8Array(n.buffer,b);break;case Int16Array.BYTES_PER_ELEMENT:h=new Int16Array(n.buffer,b);break;case Int32Array.BYTES_PER_ELEMENT:h=new Int32Array(n.buffer,b)}a=0;for(let t=0;t<g;t++){let e=o[3*t+8],i=new Float32Array(e+2);f.push(i);for(let e=0;e<2;e++)i[e]=o[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+h[a++]}return{areContours:u,thickness:p,outlines:f,width:d,height:c}}catch(t){return Le(`decompressSignature: ${t}`),null}}},Ra=class t extends Ta{constructor(){super(),super.updateProperties({fill:Ji._defaultLineColor,"stroke-width":0})}clone(){let e=new t;return e.updateAll(this),e}},Na=class t extends Ia{constructor(t){super(t),super.updateProperties({stroke:Ji._defaultLineColor,"stroke-width":1})}clone(){let e=new t(this._viewParameters);return e.updateAll(this),e}},Ba=class t extends Ma{#t=!1;#e=null;#i=null;#s=null;static _type="signature";static _editorType=oe.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#i=t.signatureData||null,this.#e=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){Ji.initialize(t,e),this._defaultDrawingOptions=new Ra,this._defaultDrawnSignatureOptions=new Na(e.viewParameters)}static getDefaultDrawingOptions(t){let e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return He(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#e}}static computeTelemetryFinalData(t){let e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let e,i,{_isCopy:s}=this;if(s&&(this._isCopy=!1,e=this.x,i=this.y),super.render(),null===this._drawId)if(this.#i){let{lines:e,mustSmooth:i,areContours:s,description:r,uuid:n,heightInPage:a}=this.#i,{rawDims:{pageWidth:o,pageHeight:l},rotation:h}=this.parent.viewport,d=Oa.processDrawnLines({lines:e,pageWidth:o,pageHeight:l,rotation:h,innerMargin:t._INNER_MARGIN,mustSmooth:i,areContours:s});this.addSignature(d,a,r,n)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#e||""}));return s&&(this._isCopy=!0,this._moveAfterPaste(e,i)),this.div}setUuid(t){this.#s=t,this.addEditToolbar()}getUuid(){return this.#s}get description(){return this.#e}set description(t){this.#e=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){let{newCurves:t,areContours:e,thickness:i,width:s,height:r}=this.#i,n=Math.max(s,r);return{areContours:e,outline:Oa.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:s,height:r},pageWidth:n,pageHeight:n,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(e,i,s,r){let n,{x:a,y:o}=this,{outline:l}=this.#i=e;this.#t=l instanceof La,this.description=s,this.#t?n=t.getDefaultDrawingOptions():(n=t._defaultDrawnSignatureOptions.clone(),n.updateProperties({"stroke-width":l.thickness})),this._addOutlines({drawOutlines:l,drawingOptions:n});let[,h]=this.pageDimensions,d=i/h;d=d>=1?.5:d,this.width*=d/this.height,this.width>=1&&(d*=.9/this.width,this.width=.9),this.height=d,this.setDims(),this.x=a,this.y=o,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(r),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!r,hasDescription:!!s}}),this.div.hidden=!1}getFromImage(e){let{rawDims:{pageWidth:i,pageHeight:s},rotation:r}=this.parent.viewport;return Oa.process(e,i,s,r,t._INNER_MARGIN)}getFromText(e,i){let{rawDims:{pageWidth:s,pageHeight:r},rotation:n}=this.parent.viewport;return Oa.extractContoursFromText(e,i,s,r,n,t._INNER_MARGIN)}getDrawnSignature(e){let{rawDims:{pageWidth:i,pageHeight:s},rotation:r}=this.parent.viewport;return Oa.processDrawnLines({lines:e,pageWidth:i,pageHeight:s,rotation:r,innerMargin:t._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:e,thickness:i}){e?this._drawingOptions=t.getDefaultDrawingOptions():(this._drawingOptions=t._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":i}))}serialize(t=!1){if(this.isEmpty())return null;let{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":s}}=this,r=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#t,color:[0,0,0],thickness:this.#t?0:s});return this.addComment(r),t?(r.paths={lines:e,points:i},r.uuid=this.#s,r.isCopy=!0):r.lines=e,this.#e&&(r.accessibilityData={type:"Figure",alt:this.#e}),r}static deserializeDraw(t,e,i,s,r,n){return n.areContours?La.deserialize(t,e,i,s,r,n):Da.deserialize(t,e,i,s,r,n)}static async deserialize(t,e,i){let s=await super.deserialize(t,e,i);return s.#t=t.areContours,s.description=t.accessibilityData?.alt||"",s.#s=t.uuid,s}},Ua=class extends Ji{#t=null;#e=null;#i=null;#s=null;#r=null;#n="";#a=null;#o=!1;#l=null;#h=!1;#d=!1;static _type="stamp";static _editorType=oe.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#s=t.bitmapUrl,this.#r=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){Ji.initialize(t,e)}static isHandlingMimeForPasting(t){return Ei.includes(t)}static paste(t,e){e.pasteEditor({mode:oe.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){let e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#c(t,e=!1){t?(this.#t=t.bitmap,e||(this.#e=t.id,this.#h=t.isSvg),t.file&&(this.#n=t.file.name),this.#g()):this.remove()}#u(){if(this.#i=null,this._uiManager.enableWaiting(!1),this.#a){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t)return void this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;let{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");let{data:s,width:r,height:n}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:s,width:r,height:n,channels:s.length/(r*n)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");let o=a.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#p(){if(this.#e)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#e).then(t=>this.#c(t,!0)).finally(()=>this.#u());if(this.#s){let t=this.#s;return this.#s=null,this._uiManager.enableWaiting(!0),void(this.#i=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#c(t)).finally(()=>this.#u()))}if(this.#r){let t=this.#r;return this.#r=null,this._uiManager.enableWaiting(!0),void(this.#i=this._uiManager.imageManager.getFromFile(t).then(t=>this.#c(t)).finally(()=>this.#u()))}let t=document.createElement("input");t.type="file",t.accept=Ei.join(",");let e=this._uiManager._signal;this.#i=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);let e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#c(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#a?.remove(),this.#a=null,this.#l&&(clearTimeout(this.#l),this.#l=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#e&&null===this.#a&&this.#p(),this.isAttachedToDOM||this.parent.add(this))):this.#e&&this.#p()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#i||this.#t||this.#s||this.#r||this.#e||this.#o)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#o||(this.#t?this.#g():this.#p()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){let{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#e=i,s&&(this.#t=s),this.#o=!1,this.#g())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#l&&clearTimeout(this.#l);this.#l=setTimeout(()=>{this.#l=null,this.#f()},200)}#g(){let{div:t}=this,{width:e,height:i}=this.#t,[s,r]=this.pageDimensions,n=.75;if(this.width)e=this.width*s,i=this.height*r;else if(e>n*s||i>n*r){let t=Math.min(n*s/e,n*r/i);e*=t,i*=t}this._uiManager.enableWaiting(!1);let a=this.#a=document.createElement("canvas");a.setAttribute("role","img"),this.addContainer(a),this.width=e/s,this.height=i/r,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#f(),this.#d||(this.parent.addUndoableEditor(this),this.#d=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&this.div.setAttribute("aria-description",this.#n),this.annotationElementId||this._uiManager.a11yAlert(Ji._l10nAlert.stamp)}copyCanvas(t,e,i=!1){t||(t=224);let{width:s,height:r}=this.#t,n=new Ci,a=this.#t,o=s,l=r,h=null;if(e){if(s>e||r>e){let t=Math.min(e/s,e/r);o=Math.floor(s*t),l=Math.floor(r*t)}h=document.createElement("canvas");let t=h.width=Math.ceil(o*n.sx),i=h.height=Math.ceil(l*n.sy);this.#h||(a=this.#m(t,i));let d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":ki.isDarkMode&&(c="#8f8f9d",u="#42414d");let p=15,g=p*n.sx,m=p*n.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let d=null;if(i){let e,i;if(n.symmetric&&a.width<t&&a.height<t)e=a.width,i=a.height;else if(a=this.#t,s>t||r>t){let n=Math.min(t/s,t/r);e=Math.floor(s*n),i=Math.floor(r*n),this.#h||(a=this.#m(e,i))}let o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#m(t,e){let{width:i,height:s}=this.#t,r=i,n=s,a=this.#t;for(;r>2*t||n>2*e;){let i=r,s=n;r>2*t&&(r=Math.ceil(r/2)),n>2*e&&(n=Math.ceil(n/2));let o=new OffscreenCanvas(r,n);o.getContext("2d").drawImage(a,0,0,i,s,0,0,r,n),a=o.transferToImageBitmap()}return a}#f(){let[t,e]=this.parentDimensions,{width:i,height:s}=this,r=new Ci,n=Math.ceil(i*t*r.sx),a=Math.ceil(s*e*r.sy),o=this.#a;if(!o||o.width===n&&o.height===a)return;o.width=n,o.height=a;let l=this.#h?this.#t:this.#m(n,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,n,a)}#b(t){if(t){if(this.#h){let t=this._uiManager.imageManager.getSvgUrl(this.#e);if(t)return t}let t=document.createElement("canvas");return({width:t.width,height:t.height}=this.#t),t.getContext("2d").drawImage(this.#t,0,0),t.toDataURL()}if(this.#h){let[t,e]=this.pageDimensions,i=Math.round(this.width*t*li.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*li.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,s);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,s),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,i){let s=null,r=!1;if(t instanceof ma){let n,a,{data:{rect:o,rotation:l,id:h,structParent:d,popupRef:c,richText:u,contentsObj:p,creationDate:g,modificationDate:m},container:f,parent:{page:{pageNumber:b}},canvas:v}=t;v?(delete t.canvas,({id:n,bitmap:a}=i.imageManager.getFromCanvas(f.id,v)),v.remove()):(r=!0,t._hasNoCanvas=!0);let y=(await e._structTree.getAriaAttributes(`${ne}${h}`))?.get("aria-label")||"";s=t={annotationType:oe.STAMP,bitmapId:n,bitmap:a,pageIndex:b-1,rect:o.slice(0),rotation:l,annotationElementId:h,id:h,deleted:!1,accessibilityData:{decorative:!1,altText:y},isSvg:!1,structParent:d,popupRef:c,richText:u,comment:p?.str||null,creationDate:g,modificationDate:m}}let n=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;r?(i.addMissingCanvas(t.id,n),n.#o=!0):h&&i.imageManager.isValidId(h)?(n.#e=h,o&&(n.#t=o)):n.#s=l,n.#h=d;let[u,p]=n.pageDimensions;return n.width=(a[2]-a[0])/u,n.height=(a[3]-a[1])/p,c&&(n.altTextData=c),n._initialData=s,t.comment&&n.setCommentData(t),n.#d=!!s,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let i=Object.assign(super.serialize(t),{bitmapId:this.#e,isSvg:this.#h});if(this.addComment(i),t)return i.bitmapUrl=this.#b(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;let{decorative:s,altText:r}=this.serializeAltText(!1);if(!s&&r&&(i.accessibilityData={type:"Figure",alt:r}),this.annotationElementId){let t=this.#v(i);return t.isSame?null:(t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(null===e)return i;e.stamps||=new Map;let n=this.#h?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#e)){if(this.#h){let t=e.stamps.get(this.#e);n>t.area&&(t.area=n,t.serialized.bitmap.close(),t.serialized.bitmap=this.#b(!1))}}else e.stamps.set(this.#e,{area:n,serialized:i}),i.bitmap=this.#b(!1);return i}#v(t){let{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,r=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&s&&r,isSameAltText:r}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}},Ha=class t{#t;#e=!1;#i=null;#s=null;#r=null;#n=new Map;#a=!1;#o=!1;#l=!1;#h=null;#d=null;#c=null;#u=null;#p=null;#g=-1;#m;static _initialized=!1;static#f=new Map([ya,Fa,Ua,ka,Ba].map(t=>[t._editorType,t]));constructor({uiManager:e,pageIndex:i,div:s,structTreeLayer:r,accessibilityManager:n,annotationLayer:a,drawLayer:o,textLayer:l,viewport:h,l10n:d}){let c=[...t.#f.values()];if(!t._initialized){t._initialized=!0;for(let t of c)t.initialize(d,e)}e.registerEditorTypes(c),this.#m=e,this.pageIndex=i,this.div=s,this.#t=n,this.#i=a,this.viewport=h,this.#c=l,this.drawLayer=o,this._structTree=r,this.#m.addLayer(this)}get isEmpty(){return 0===this.#n.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===oe.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(e=this.#m.getMode()){switch(this.#x(),e){case oe.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case oe.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case oe.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:i}=this.div;if(i.toggle("nonEditing",!1),e===oe.POPUP)i.toggle("commentEditing",!0);else{i.toggle("commentEditing",!1);for(let s of t.#f.values())i.toggle(`${s._type}Editing`,e===s._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#c?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#i?.togglePointerEvents(t)}get#b(){return 0!==this.#n.size?this.#n.values():this.#m.getEditors(this.pageIndex)}async enable(){this.#l=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#p?.abort(),this.#p=null;let t=new Set;for(let e of this.#b)e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));let e=this.#i;if(e)for(let i of e.getEditableAnnotations()){if(i.hide(),this.#m.isDeletedAnnotationElement(i.data.id)||t.has(i.data.id))continue;let e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#l=!1,this.#m._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#o=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#c&&!this.#p){this.#p=new AbortController;let t=this.#m.combinedSignal(this.#p);this.#c.div.addEventListener("pointerdown",t=>{let{clientX:e,clientY:i,timeStamp:s}=t;if(s-this.#g>500)return void(this.#g=s);this.#g=-1;let{classList:r}=this.div;r.toggle("getElements",!0);let n=document.elementsFromPoint(e,i);if(r.toggle("getElements",!1),!this.div.contains(n[0]))return;let a,o=new RegExp(`^${ae}[0-9]+$`);for(let t of n)if(o.test(t.id)){a=t.id;break}if(!a)return;let l=this.#n.get(a);null===l?.annotationElementId&&(vi(t),l.dblclick(t))},{signal:t,capture:!0})}let e=this.#i,i=[];if(e){let t=new Map,s=new Map;for(let e of this.#b)e.disableEditing(),e.annotationElementId?null===e.serialize()?(s.set(e.annotationElementId,e),this.getEditableAnnotation(e.annotationElementId)?.show(),e.remove()):t.set(e.annotationElementId,e):i.push(e);for(let i of e.getEditableAnnotations()){let{id:e}=i.data;if(this.#m.isDeletedAnnotationElement(e)){i.updateEdited({deleted:!0});continue}let r=s.get(e);r?(r.resetAnnotationElement(i),r.show(!1),i.show()):(r=t.get(e),r&&(this.#m.addChangedExistingAnnotation(r),r.renderAnnotationElement(i)&&r.show(!1)),i.show())}}this.#x(),this.isEmpty&&(this.div.hidden=!0);let{classList:s}=this.div;for(let e of t.#f.values())s.remove(`${e._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e?.updateFakeAnnotations(i),this.#o=!1}getEditableAnnotation(t){return this.#i?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#c?.div&&!this.#u){this.#u=new AbortController;let t=this.#m.combinedSignal(this.#u);this.#c.div.addEventListener("pointerdown",this.#v.bind(this),{signal:t}),this.#c.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#c?.div&&this.#u&&(this.#u.abort(),this.#u=null,this.#c.div.classList.remove("highlighting"))}#v(t){this.#m.unselectAll();let{target:e}=t;if(e===this.#c.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent")||e.classList.contains("textLayerImages")||e.classList.contains("textLayerImagePlaceholder"))&&this.#c.div.contains(e)){let{isMac:e}=qe.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#c.div.classList.add("free"),this.toggleDrawing(),ka.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#c.div,x:t.x,y:t.y}),this.#c.div.addEventListener("pointerup",()=>{this.#c.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#s)return;this.#s=new AbortController;let t=this.#m.combinedSignal(this.#s);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});let e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#s?.abort(),this.#s=null}attach(t){this.#n.set(t.id,t);let{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#o&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t),Ji.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.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){let e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#l),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;let{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#m._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.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})}getEditorByUID(t){for(let e of this.#n.values())if(e.uid===t)return e;return null}get#y(){return t.#f.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#A(t){let e=this.#y;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#y?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#m.updateMode(t.mode);let{offsetX:i,offsetY:s}=this.#w(),r=this.#m.getId(),n=this.#A({parent:this,id:r,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});n&&this.add(n)}async deserialize(e){return await(t.#f.get(e.annotationType??e.annotationEditorType)?.deserialize(e,this,this.#m))||null}createAndAddNewEditor(t,e,i={}){let s=this.#m.getId(),r=this.#A({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return r&&this.add(r),r}get boundingClientRect(){return this.div.getBoundingClientRect()}#w(){let{x:t,y:e,width:i,height:s}=this.boundingClientRect,r=Math.max(0,t),n=Math.max(0,e),a=(r+Math.min(window.innerWidth,t+i))/2-t,o=(n+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#w(),!0,t)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){let{isMac:e}=qe.platform;if(0!==t.button||t.ctrlKey&&e||t.target!==this.div||!this.#a||(this.#a=!1,this.#y?.isDrawer&&this.#y.supportMultipleDrawings))return;if(!this.#e)return void(this.#e=!0);let i=this.#m.getMode();i!==oe.STAMP&&i!==oe.POPUP&&i!==oe.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#m.unselectAll()}pointerdown(t){if(this.#m.getMode()===oe.HIGHLIGHT&&this.enableTextSelection(),this.#a)return void(this.#a=!1);let{isMac:e}=qe.platform;if(0!==t.button||t.ctrlKey&&e||t.target!==this.div)return;if(this.#a=!0,this.#y?.isDrawer)return void this.startDrawingSession(t);let i=this.#m.getActive();this.#e=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#h)return void this.#y.startDrawing(this,this.#m,!1,t);this.#m.setCurrentDrawingSession(this),this.#h=new AbortController;let e=this.#m.combinedSignal(this.#h);this.div.addEventListener("blur",({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#y.startDrawing(this,this.#m,!1,t)}pause(t){if(t){let{activeElement:t}=document;return void(this.div.contains(t)&&(this.#d=t))}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#h?(this.#m.setCurrentDrawingSession(null),this.#h.abort(),this.#h=null,this.#d=null,this.#y.endDrawing(t)):null}findNewParent(t,e,i){let s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}commitOrRemove(){return!!this.#h&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#h&&this.#y.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(let t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#m.removeLayer(this)}#x(){for(let t of this.#n.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t,Si(this.div,t);for(let t of this.#m.getEditors(this.pageIndex))this.add(t),t.rebuild();await this.#m.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#x();let e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,Si(this.div,{rotation:i}),e!==i)for(let t of this.#n.values())t.rotate(i)}get pageDimensions(){let{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}};function ja(t,e){return t===e?0:t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function $a(t){return t?t.nodeType===Node.ELEMENT_NODE?t.closest(".textLayer"):t.parentElement?.closest(".textLayer")||null:null}function Ga(t,e,i,s){if(t===i)return e<=s;let r=t.compareDocumentPosition(i);return!!(r&Node.DOCUMENT_POSITION_FOLLOWING)||!(r&Node.DOCUMENT_POSITION_PRECEDING)&&null}function za(t,e,i){if(t.nodeType!==Node.ELEMENT_NODE||!t.classList.contains("textLayer")||e!==t.childNodes.length)return{container:t,offset:e};let s=t.lastChild;return s?.nodeType===Node.ELEMENT_NODE&&s.classList.contains("endOfContent")&&(s=s.previousSibling),s&&i.contains(s)?s.nodeType===Node.TEXT_NODE?{container:s,offset:s.textContent.length}:{container:s,offset:s.childNodes.length}:null}var Va=class t{#t=null;#e=new Map;#i=null;#s=null;#r=null;#n=null;#a=new Map;static#o=0;static#l=0;static#h=null;static#d=new Set;static#c=!1;static#u=new Set;static#p=new WeakMap;constructor({filterFactory:e=null,pageColors:i=null,pageIndex:s,textLayer:r=null}){if(this.pageIndex=s,this.#s=e,this.#r=i,r){let e=t.#p.get(r);if(e?.selectionDiv&&(e.selectionDiv.remove(),t.#d.delete(e.selectionDiv)),t.#p.set(r,{drawLayer:this}),t.#u.add(r),this.#i=r,this.#n=new MutationObserver(e=>{if(this.#t&&this.#i?.isConnected&&t.#m())for(let{addedNodes:i}of e)for(let e of i)if(e.nodeType===Node.ELEMENT_NODE&&e.classList.contains("endOfContent"))return void t.#b()}),this.#n.observe(r,{childList:!0}),null===t.#h){t.#h=new AbortController;let{signal:e}=t.#h;document.addEventListener("selectionchange",t.#b.bind(t),{signal:e}),document.addEventListener("pointerdown",()=>{t.#c=!0},{signal:e}),document.addEventListener("pointerup",()=>{t.#c=!1},{signal:e}),window.addEventListener("blur",()=>{t.#c=!1},{signal:e})}}}setParent(e){if(!this.#t)return this.#t=e,void(this.#i?.isConnected&&t.#m()&&t.#b());if(this.#t!==e){if(this.#e.size>0)for(let t of this.#e.values())t.remove(),e.append(t);this.#t=e}}static#g(t){let e=this.#p.get(t);e?.selectionDiv&&(e.selectionDiv.remove(),this.#d.delete(e.selectionDiv),e.selectionDiv=null,e.path=null)}static#m(){let t=document.getSelection();return!!t&&!t.isCollapsed}static#f(){return[...this.#u].filter(t=>t.isConnected).sort(ja)}static#b(){let e=document.getSelection();if(!e||e.isCollapsed){for(let t of this.#d)t.remove();return void this.#d.clear()}let i=new WeakMap,s=this.#f(),r=[];for(let t=0,i=e.rangeCount;t<i;t++){let i=e.getRangeAt(t);if(i.collapsed)continue;let{startContainer:n,startOffset:a,endContainer:o,endOffset:l}=i,h=$a(n),d=$a(o),c=null===h,u=null===d;if(this.#c&&c!==u)return;if(1===e.rangeCount){let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=e,c=$a(t),u=$a(s),p=Ga(t,i,s,r);c&&u&&null!==p&&(p?(n=t,a=i,h=c,o=s,l=r,d=u):(n=s,a=r,h=u,o=t,l=i,d=c))}let p=s.filter(t=>i.intersectsNode(t));if(0===p.length)continue;let g=!1;if(h||(h=p[0],n=h,a=0,g=!0),d||(d=p.at(-1),o=d,l=d.childNodes.length,g=!0),o.nodeType===Node.ELEMENT_NODE)if(o.classList.contains("endOfContent")){let t=o.previousSibling;if(!t)continue;o=t,l=t.nodeType===Node.TEXT_NODE?t.textContent.length:t.childNodes.length}else if(o.classList.contains("textLayer")&&o.childNodes.length===l){let t=za(o,l,d);if(!t)continue;o=t.container,l=t.offset}if(n.nodeType===Node.ELEMENT_NODE){let t=za(n,a,h);if(!t)continue;n=t.container,a=t.offset}if(h!==d||g||!p.includes(h))for(let t of p){let e=t.firstChild;if(!e)continue;let i=document.createRange();if(t===h?i.setStart(n,a):i.setStartBefore(e),t===d)i.setEnd(o,l);else{let e=t.lastChild;if(!e)continue;if(e.nodeType===Node.ELEMENT_NODE&&e.classList.contains("endOfContent")){let t=e.previousSibling;if(!t)continue;i.setEndAfter(t)}else i.setEndAfter(e)}i.collapsed||r.push([i,t])}else r.push([i,h])}let n=new Set(r.map(t=>t[1]));for(let t of this.#u)n.has(t)||this.#g(t);for(let[e,s]of r){let r=t.#p.get(s);if(!r)continue;let n=i.get(s);if(!n){let t=s.getBoundingClientRect();n=(e,i,s,r)=>({x:(e-t.x)/t.width,y:(i-t.y)/t.height,width:s/t.width,height:r/t.height}),i.set(s,n)}let a=[];for(let{x:t,y:i,width:s,height:r}of e.getClientRects())0===s||0===r||(({x:t,y:i,width:s,height:r}=n(t,i,s,r)),(1!==s||1!==r)&&a.push(`M${t} ${i} h${s} v${r} h-${s} Z`));if(0===a.length)continue;let o=r.drawLayer,l=r.selectionDiv,h=r.path;if(!l){let e="clip_selection_"+t.#l++;l=document.createElement("div"),l.className="selection",l.style.clipPath=`url(#${e})`;let i=o.#s?.createSelectionStyle(o.#r);if(i)for(let[t,e]of Object.entries(i))l.style.setProperty(t,e);let s=t._svgFactory.create(1,1,!0);s.setAttribute("aria-hidden","true"),s.setAttribute("width","100%"),s.setAttribute("height","100%");let n=t._svgFactory.createElement("clipPath");n.setAttribute("id",e),n.setAttribute("clipPathUnits","objectBoundingBox"),h=t._svgFactory.createElement("path"),n.append(h),s.append(n),l.append(s),r.path=h,r.selectionDiv=l}!l.parentNode&&o.#t&&(o.#t.append(l),this.#d.add(l)),h.setAttribute("d",a.join(" "))}}static get _svgFactory(){return He(this,"_svgFactory",new Hn)}static#v(t,[e,i,s,r]){let{style:n}=t;n.top=100*i+"%",n.left=100*e+"%",n.width=100*s+"%",n.height=100*r+"%"}#y(){let e=t._svgFactory.create(1,1,!0);return this.#t.append(e),e.setAttribute("aria-hidden","true"),e}#A(e,i){let s=t._svgFactory.createElement("clipPath");e.append(s);let r=`clip_${i}`;s.setAttribute("id",r),s.setAttribute("clipPathUnits","objectBoundingBox");let n=t._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${i}`),n.classList.add("clip"),r}#w(t,e){for(let[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(e,i=!1,s=!1){let r=t.#o++,n=this.#y(),a=t._svgFactory.createElement("defs");n.append(a);let o=t._svgFactory.createElement("path");a.append(o);let l=`path_${r}`;o.setAttribute("id",l),o.setAttribute("vector-effect","non-scaling-stroke"),i&&this.#a.set(r,o);let h=s?this.#A(a,l):null,d=t._svgFactory.createElement("use");return n.append(d),d.setAttribute("href",`#${l}`),this.updateProperties(n,e),this.#e.set(r,n),{id:r,clipPathId:`url(#${h})`}}drawOutline(e,i){let s=t.#o++,r=this.#y(),n=t._svgFactory.createElement("defs");r.append(n);let a=t._svgFactory.createElement("path");n.append(a);let o,l=`path_${s}`;if(a.setAttribute("id",l),a.setAttribute("vector-effect","non-scaling-stroke"),i){let e=t._svgFactory.createElement("mask");n.append(e),o=`mask_${s}`,e.setAttribute("id",o),e.setAttribute("maskUnits","objectBoundingBox");let i=t._svgFactory.createElement("rect");e.append(i),i.setAttribute("width","1"),i.setAttribute("height","1"),i.setAttribute("fill","white");let r=t._svgFactory.createElement("use");e.append(r),r.setAttribute("href",`#${l}`),r.setAttribute("stroke","none"),r.setAttribute("fill","black"),r.setAttribute("fill-rule","nonzero"),r.classList.add("mask")}let h=t._svgFactory.createElement("use");r.append(h),h.setAttribute("href",`#${l}`),o&&h.setAttribute("mask",`url(#${o})`);let d=h.cloneNode();return r.append(d),h.classList.add("mainOutline"),d.classList.add("secondaryOutline"),this.updateProperties(r,e),this.#e.set(s,r),s}finalizeDraw(t,e){this.#a.delete(t),this.updateProperties(t,e)}updateProperties(e,i){if(!i)return;let{root:s,bbox:r,rootClass:n,path:a}=i,o="number"==typeof e?this.#e.get(e):e;if(o){if(s&&this.#w(o,s),r&&t.#v(o,r),n){let{classList:t}=o;for(let[e,i]of Object.entries(n))t.toggle(e,i)}if(a){let t=o.firstElementChild.firstElementChild;this.#w(t,a)}}}updateParent(t,e){if(e===this)return;let i=this.#e.get(t);i&&(e.#t.append(i),this.#e.delete(t),e.#e.set(t,i))}remove(t){this.#a.delete(t),null!==this.#t&&(this.#e.get(t).remove(),this.#e.delete(t))}destroy(){this.#t=null;for(let t of this.#e.values())t.remove();this.#e.clear(),this.#a.clear(),this.#n?.disconnect(),this.#n=null,this.#i&&(t.#p.get(this.#i)?.drawLayer===this&&(t.#g(this.#i),t.#p.delete(this.#i),t.#u.delete(this.#i),0===t.#u.size&&(t.#h?.abort(),t.#h=null,t.#c=!1)),this.#i=null)}};function Wa(t){return`${(100*t).toFixed(2)}%`}var Xa=class t{#t=[];#e=new Map;#i=null;#s=0;#r=0;#n=0;static#a=null;constructor(t,e,i,s){this.#s=t,this.#t=e,this.#r=i.rawDims.pageWidth,this.#n=i.rawDims.pageHeight,this.#i=s}render(){let e=document.createElement("div");e.className="textLayerImages";for(let t=0;t<this.#t.length;t+=6){let i=this.#o(this.#t.subarray(t,t+6));i&&e.append(i)}return e.addEventListener("contextmenu",e=>{if(!(e.target instanceof HTMLCanvasElement))return;let i=e.target,s=this.#e.get(i);if(!s)return;let r=t.#a?.deref();if(r===i)return;r&&(r.width=0,r.height=0),t.#a=new WeakRef(i);let{inverseTransform:n,x1:a,y1:o,width:l,height:h}=s,d=this.#i(),c=Math.ceil(a*d.width),u=Math.ceil(o*d.height),p=Math.floor((a+l/this.#r)*d.width),g=Math.floor((o+h/this.#n)*d.height);i.width=p-c,i.height=g-u;let m=i.getContext("2d");m.setTransform(...n),m.translate(-c,-u),m.drawImage(d,0,0)}),e}#o([t,e,i,s,r,n]){let a=Math.hypot((r-t)*this.#r,(n-e)*this.#n),o=Math.hypot((i-t)*this.#r,(s-e)*this.#n);if(a<this.#s||o<this.#s)return null;let l=[(r-t)*this.#r/a,(n-e)*this.#n/a,(i-t)*this.#r/o,(s-e)*this.#n/o,0,0],h=Ke.inverseTransform(l),d=document.createElement("canvas");return d.className="textLayerImagePlaceholder",d.width=0,d.height=0,Object.assign(d.style,{opacity:0,position:"absolute",left:Wa(t),top:Wa(e),width:Wa(a/this.#r),height:Wa(o/this.#n),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`}),this.#e.set(d,{inverseTransform:h,width:a,height:o,x1:t,y1:e}),d}};globalThis._pdfjsTestingUtils={HighlightOutliner:_a},globalThis.pdfjsLib={AbortException:Xe,AnnotationEditorLayer:Ha,AnnotationEditorParamsType:le,AnnotationEditorType:oe,AnnotationEditorUIManager:Yi,AnnotationLayer:ba,AnnotationMode:re,AnnotationType:be,applyOpacity:Mi,build:Fn,ColorPicker:Ln,createValidAbsoluteUrl:Ne,CSSConstants:Ti,DOMSVGFactory:Hn,DrawLayer:Va,FeatureTest:qe,fetchData:hi,findContrastColor:Oi,getDocument:_n,getFilenameFromUrl:pi,getPdfFilenameFromUrl:gi,getRGB:wi,getRGBA:Ai,getUuid:ti,GlobalWorkerOptions:pn,ImageKind:fe,InvalidPDFException:ze,isDataScheme:ci,isPdfFile:ui,isValidExplicitDest:Bs,makeArr:ei,makeMap:ii,makeObj:si,MathClamp:ri,noContextMenu:bi,normalizeUnicode:Ze,OPS:Se,OutputScale:Ci,PasswordResponses:Pe,PDFDataRangeTransport:Cn,PDFDateString:yi,PDFWorker:Tn,PermissionFlag:he,PixelsPerInch:li,RenderingCancelledException:di,renderRichText:Ri,ResponseException:Ve,setLayerDimensions:Si,shadow:He,SignatureExtractor:Oa,stopEvent:vi,SupportedImageMimeTypes:Ei,TextLayer:xn,TextLayerImages:Xa,TouchManager:Qi,updateUrlHash:Be,Util:Ke,VerbosityLevel:_e,version:In,XfaLayer:oi};export{Xe as AbortException,Ha as AnnotationEditorLayer,le as AnnotationEditorParamsType,oe as AnnotationEditorType,Yi as AnnotationEditorUIManager,ba as AnnotationLayer,re as AnnotationMode,be as AnnotationType,Ti as CSSConstants,Ln as ColorPicker,Hn as DOMSVGFactory,Va as DrawLayer,qe as FeatureTest,pn as GlobalWorkerOptions,fe as ImageKind,ze as InvalidPDFException,ri as MathClamp,Se as OPS,Ci as OutputScale,Cn as PDFDataRangeTransport,yi as PDFDateString,Tn as PDFWorker,Pe as PasswordResponses,he as PermissionFlag,li as PixelsPerInch,di as RenderingCancelledException,Ve as ResponseException,Oa as SignatureExtractor,Ei as SupportedImageMimeTypes,xn as TextLayer,Xa as TextLayerImages,Qi as TouchManager,Ke as Util,_e as VerbosityLevel,oi as XfaLayer,Mi as applyOpacity,Fn as build,Ne as createValidAbsoluteUrl,hi as fetchData,Oi as findContrastColor,_n as getDocument,pi as getFilenameFromUrl,gi as getPdfFilenameFromUrl,wi as getRGB,Ai as getRGBA,ti as getUuid,ci as isDataScheme,ui as isPdfFile,Bs as isValidExplicitDest,ei as makeArr,ii as makeMap,si as makeObj,bi as noContextMenu,Ze as normalizeUnicode,Ri as renderRichText,Si as setLayerDimensions,He as shadow,vi as stopEvent,Be as updateUrlHash,In as version};