| 12345678910111213141516171819202122232425262728 |
- /**
- * @licstart The following is the entire license notice for the
- * JavaScript code in this page
- *
- * Copyright 2024 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @licend The above is the entire license notice for the
- * JavaScript code in this page
- */
- /**
- * pdfjsVersion = 5.4.296
- * pdfjsBuild = f56dc8601
- */const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[.001,0,0,.001,0,0],i=1.35,s=1,n=2,r=4,a=16,o=32,l=64,h=128,d=256,c={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u="pdfjs_internal_editor_",p={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},g={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},m={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},f=0,b=1,w=2,y=3,A=3,v=4,x={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},E={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},C=1,_=2,S=3,T=4,D=5,M={ERRORS:0,WARNINGS:1,INFOS:5},k={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},P=0,I=1,F=2,R=3,L={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let B=M.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(B=t)}function getVerbosityLevel(){return B}function info(t){B>=M.INFOS&&console.info(`Info: ${t}`)}function warn(t){B>=M.WARNINGS&&console.warn(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(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=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?URL.parse(t,e):URL.parse(t);return function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s)?s:null}function updateUrlHash(t,e,i=!1){const s=URL.parse(t);if(s){s.hash=e;return s.href}return i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const O=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends O{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends O{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends O{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends O{constructor(t,e,i){super(t,"ResponseException");this.status=e;this.missing=i}}class FormatError extends O{constructor(t){super(t,"FormatError")}}class AbortException extends O{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("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 r=Math.min(n+i,e),a=t.subarray(n,r);s.push(String.fromCharCode.apply(null,a))}return s.join("")}function stringToBytes(t){"string"!=typeof t&&unreachable("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 util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return 1===new Uint32Array(t.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){const{platform:t,userAgent:e}=navigator;return shadow(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const N=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class Util{static makeHexColor(t,e,i){return`#${N[t]}${N[e]}${N[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static 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],r=e[2],a=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],d=t[i+e+1];t[i+e]=h*s+d*r+o;t[i+e+1]=h*n+d*a+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],r=e[2],a=e[3],o=e[4],l=e[5],h=t[0],d=t[1],c=t[2],u=t[3];let p=s*h+o,g=p,m=s*c+o,f=m,b=a*d+l,w=b,y=a*u+l,A=y;if(0!==n||0!==r){const t=n*h,e=n*c,i=r*d,s=r*u;p+=i;f+=i;m+=s;g+=s;b+=t;A+=t;y+=e;w+=e}i[0]=Math.min(i[0],p,m,g,f);i[1]=Math.min(i[1],b,y,w,A);i[2]=Math.max(i[2],p,m,g,f);i[3]=Math.max(i[3],b,y,w,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],r=t[3],a=i**2+s**2,o=i*n+s*r,l=n**2+r**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){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return 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])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[i,n,s,r]}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,r,a,o,l,h){if(l<=0||l>=1)return;const 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*n+3*l*r)+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,n,r,a,o,l,h,d,c){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,r,a,o,-d/h,c);return}const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,r,a,o,(-h+p)/g,c);this.#t(t,e,i,s,n,r,a,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,n,r,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,n,a,e,s,r,o,3*(3*(i-n)-t+a),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,a,e,s,r,o,3*(3*(s-r)-e+o),6*(e-2*s+r),3*(s-e),l)}}let U=null,H=null;function normalizeUnicode(t){if(!U){U=/([\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;H=new Map([["ſt","ſt"]])}return t.replaceAll(U,(t,e,i)=>e?e.normalize("NFKC"):H.get(i))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}const z="pdfjs_internal_id_";function MathClamp(t,e,i){return Math.min(Math.max(t,e),i)}function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}"function"!=typeof Promise.try&&(Promise.try=function(t,...e){return new Promise(i=>{i(t(...e))})});"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const r=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==r.value&&(t.textContent=r.value);if("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){r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{null!==r.value&&t.setAttribute("value",r.value);if("print"===n)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("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:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${s}`);for(const[e,i]of Object.entries(r))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&&n.addLinkAttributes(t,r.href,r.newWindow);i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",r=document.createElement(s.name);s.attributes&&this.setAttributes({html:r,element:s,intent:n,linkService:i});const a="richText"!==n,o=t.div;o.append(r);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);r.append(t);a&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,r]];for(;h.length>0;){const[t,s,r]=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:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t);r.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);r.append(c);o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);a&&XfaText.shouldBuildText(d)&&l.push(t);c.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}}const G="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)})}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=r;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;d=0;c=0;u=1;break;case 90:h=0;d=1;c=1;u=0;break;case 270:h=0;d=-1;c=-1;u=0;break;case 0:h=1;d=0;c=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){c=-c;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+r;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+r;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const t=this.viewBox;return shadow(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 PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){const i=[t,e];Util.applyTransform(i,this.transform);return i}convertToViewportRectangle(t){const e=[t[0],t[1]];Util.applyTransform(e,this.transform);const i=[t[2],t[3]];Util.applyTransform(i,this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];Util.applyInverseTransform(i,this.transform);return i}}class RenderingCancelledException extends O{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t){[t]=t.split(/[#?]/,1);return t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if("string"!=typeof t)return e;if(isDataScheme(t)){warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return 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 decode=t=>{try{let e=decodeURIComponent(t);if(e.includes("/")){e=e.split("/").at(-1);return e.test(/^\.pdf$/i)?e:t}return e}catch{return t}},s=/\.pdf$/i,n=i.pathname.split("/").at(-1);if(s.test(n))return decode(n);if(i.searchParams.size>0){const t=Array.from(i.searchParams.values()).reverse();for(const e of t)if(s.test(e))return decode(e);const e=Array.from(i.searchParams.keys()).reverse();for(const t of e)if(s.test(t))return decode(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return decode(t[0])}return e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:s,end:n}of this.times)t.push(`${i.padEnd(e)} ${n-s}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}class PDFDateString{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#i.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 r=parseInt(e[4],10);r=r>=0&&r<=23?r: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;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===l){r+=h;a+=d}else if("+"===l){r-=h;a-=d}return new Date(Date.UTC(i,s,n,r,a,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,r=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:r,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map(t=>parseInt(t));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform();return[e,i,s,n,r,a]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform().invertSelf();return[e,i,s,n,r,a]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:r}=t,a=util_FeatureTest.isCSSRoundSupported,o=`var(--total-scale-factor) * ${s}px`,l=`var(--total-scale-factor) * ${n}px`,h=a?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,d=a?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;if(i&&e.rotation%180!=0){r.width=d;r.height=h}else{r.width=h;r.height=d}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;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 r=1/0,a=1/0,o=1/0;(i=OutputScale.capPixels(i,n))>0&&(r=Math.sqrt(i/(t*e)));if(-1!==s){a=s/t;o=s/e}const l=Math.min(r,a,o);if(this.sx>l||this.sy>l){this.sx=l;this.sy=l;return!0}return!1}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 W=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ColorScheme{static get isDarkMode(){return shadow(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class CSSConstants{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);t.remove();return shadow(this,"commentForegroundColor",getRGB(i))}}function applyOpacity(t,e,i,s){const n=255*(1-(s=Math.min(Math.max(s??1,0),1)));return[t=Math.round(t*s+n),e=Math.round(e*s+n),i=Math.round(i*s+n)]}function RGBToHSL(t,e){const i=t[0]/255,s=t[1]/255,n=t[2]/255,r=Math.max(i,s,n),a=Math.min(i,s,n),o=(r+a)/2;if(r===a)e[0]=e[1]=0;else{const t=r-a;e[1]=o<.5?t/(r+a):t/(2-r-a);switch(r){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 HSLToRGB(t,e){const i=t[0],s=t[1],n=t[2],r=(1-Math.abs(2*n-1))*s,a=r*(1-Math.abs(i/60%2-1)),o=n-r/2;switch(Math.floor(i/60)){case 0:e[0]=r+o;e[1]=a+o;e[2]=o;break;case 1:e[0]=a+o;e[1]=r+o;e[2]=o;break;case 2:e[0]=o;e[1]=r+o;e[2]=a+o;break;case 3:e[0]=o;e[1]=a+o;e[2]=r+o;break;case 4:e[0]=a+o;e[1]=o;e[2]=r+o;break;case 5:case 6:e[0]=r+o;e[1]=o;e[2]=a+o}}function computeLuminance(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function contrastRatio(t,e,i){HSLToRGB(t,i);i.map(computeLuminance);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];HSLToRGB(e,i);i.map(computeLuminance);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];return s>n?(s+.05)/(n+.05):(n+.05)/(s+.05)}const V=new Map;function findContrastColor(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let s=V.get(i);if(s)return s;const n=new Float32Array(9),r=n.subarray(0,3),a=n.subarray(3,6);RGBToHSL(t,a);const o=n.subarray(6,9);RGBToHSL(e,o);const l=o[2]<.5,h=l?12:4.5;a[2]=l?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]);if(contrastRatio(a,o,r)<h){let t,e;if(l){t=a[2];e=1}else{t=0;e=a[2]}const i=.005;for(;e-t>i;){const i=a[2]=(t+e)/2;l===contrastRatio(a,o,r)<h?t=i:e=i}a[2]=l?e:t}HSLToRGB(a,r);s=Util.makeHexColor(Math.round(255*r[0]),Math.round(255*r[1]),Math.round(255*r[2]));V.set(i,s);return s}function renderRichText({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 XfaLayer.render({xfaHtml:t,div:n,intent:"richText"});n.firstChild.classList.add("richText",i);s.append(n)}class EditorToolbar{#s=null;#n=null;#r;#a=null;#o=null;#l=null;#h=null;#d=null;static#c=null;constructor(t){this.#r=t;EditorToolbar.#c||=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.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;if(e instanceof AbortSignal&&!e.aborted){t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#u,{signal:e})}const i=this.#a=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.#s}static#u(t){t.stopPropagation()}#p(t){this.#r._focusEventsAllowed=!1;stopEvent(t)}#g(t){this.#r._focusEventsAllowed=!0;stopEvent(t)}#m(t){const e=this.#r._uiManager._signal;if(!(e instanceof AbortSignal)||e.aborted)return!1;t.addEventListener("focusin",this.#p.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#g.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});return!0}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown();this.#l?.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",EditorToolbar.#c[t]);this.#m(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal});this.#a.append(i)}get#f(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#m(e);this.#a.append(e,this.#f);this.#o=t}addComment(t,e=null){if(this.#l)return;const i=t.renderForToolbar();if(!i)return;this.#m(i);const s=this.#h=this.#f;if(e){this.#a.insertBefore(i,e);this.#a.insertBefore(s,e)}else this.#a.append(i,s);this.#l=t;t.toolbar=this}addColorPicker(t){if(this.#n)return;this.#n=t;const e=t.renderButton();this.#m(e);this.#a.append(e,this.#f)}async addEditSignatureButton(t){const e=this.#d=await t.renderEditButton(this.#r);this.#m(e);this.#a.append(e,this.#f)}removeButton(t){if("comment"===t){this.#l?.removeToolbarCommentButton();this.#l=null;this.#h?.remove();this.#h=null}}async addButton(t,e){switch(t){case"colorPicker":this.addColorPicker(e);break;case"altText":await this.addAltText(e);break;case"editSignature":await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":this.addComment(e)}}async addButtonBefore(t,e,i){const s=this.#a.querySelector(i);s&&"comment"===t&&this.addComment(e,s)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class FloatingToolbar{#a=null;#s=null;#b;constructor(t){this.#b=t}#w(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");const e=this.#b._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#a=document.createElement("div");i.className="buttons";t.append(i);this.#b.hasCommentManager()&&this.#y("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#b.commentSelection("floating_button")});this.#y("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#b.highlightSelection("floating_button")});return t}#A(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(t<i)continue;const r=n.x+(e?n.width:0);if(t>i){s=r;i=t}else e?r>s&&(s=r):r<s&&(s=r)}return[e?1-s:s,i]}show(t,e,i){const[s,n]=this.#A(e,i),{style:r}=this.#s||=this.#w();t.append(this.#s);r.insetInlineEnd=100*s+"%";r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#s.remove()}#y(t,e,i,s){const n=document.createElement("button");n.classList.add("basic",t);n.tabIndex=0;n.setAttribute("data-l10n-id",e);const r=document.createElement("span");n.append(r);r.className="visuallyHidden";r.setAttribute("data-l10n-id",i);const a=this.#b._signal;if(a instanceof AbortSignal&&!a.aborted){n.addEventListener("contextmenu",noContextMenu,{signal:a});n.addEventListener("click",s,{signal:a})}this.#a.append(n)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#v=0;get id(){return`${u}${this.#v++}`}}class ImageManager{#x=getUuid();#v=0;#E=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';return shadow(this,"_isSVGFittingCanvas",e.decode().then(()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]}))}async#C(t,e){this.#E||=new Map;let i=this.#E.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#x}_${this.#v++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,r=new Promise((t,r)=>{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=r});s.readAsDataURL(t);await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#E.set(t,i);i&&this.#E.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#C(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#C(t,t)}async getFromBlob(t,e){const i=await e;return this.#C(t,i)}async getFromId(t){this.#E||=new Map;const e=this.#E.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#E||=new Map;let i=this.#E.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#x}_${this.#v++}`,refCounter:1,isSvg:!1};this.#E.set(t,i);this.#E.set(i.id,i);return i}getSvgUrl(t){const e=this.#E.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#E||=new Map;const e=this.#E.get(t);if(!e)return;e.refCounter-=1;if(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.#x}_`)}}class CommandManager{#_=[];#S=!1;#T;#D=-1;constructor(t=128){this.#T=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){s&&t();if(this.#S)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#D){this.#_.length>0&&(this.#_.length=0);this.#D=0;this.#_.push(o);return}if(r&&this.#_[this.#D].type===n){a&&(o.undo=this.#_[this.#D].undo);this.#_[this.#D]=o;return}const l=this.#D+1;if(l===this.#T)this.#_.splice(0,1);else{this.#D=l;l<this.#_.length&&this.#_.splice(l)}this.#_.push(o)}undo(){if(-1===this.#D)return;this.#S=!0;const{undo:t,post:e}=this.#_[this.#D];t();e?.();this.#S=!1;this.#D-=1}redo(){if(this.#D<this.#_.length-1){this.#D+=1;this.#S=!0;const{cmd:t,post:e}=this.#_[this.#D];t();e?.();this.#S=!1}}hasSomethingToUndo(){return-1!==this.#D}hasSomethingToRedo(){return this.#D<this.#_.length-1}cleanType(t){if(-1!==this.#D){for(let e=this.#D;e>=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#D-e);this.#D=e;return}this.#_.length=0;this.#D=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#M(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("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#M(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:r=[],checker:a=null}}=i;if(!a||a(t,e)){s.bind(t,...r,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(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,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(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 ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#k=new AbortController;#P=null;#I=null;#F=new Map;#R=new Map;#L=null;#B=null;#O=null;#N=new CommandManager;#U=null;#H=null;#z=null;#G=0;#W=new Set;#V=null;#$=null;#j=new Set;_editorUndoBar=null;#q=!1;#X=!1;#K=!1;#Y=null;#Q=null;#J=null;#Z=null;#tt=!1;#et=null;#it=new IdManager;#st=!1;#nt=!1;#rt=!1;#at=null;#ot=null;#lt=null;#ht=null;#dt=null;#ct=p.NONE;#ut=new Set;#pt=null;#gt=null;#mt=null;#ft=null;#bt=null;#wt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#yt=[0,0];#At=null;#vt=null;#xt=null;#Et=null;#Ct=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#vt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["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:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#vt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#vt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,r,a,o,l,h,d,c,u,p,g,m){const f=this._signal=this.#k.signal;this.#vt=t;this.#xt=e;this.#Et=i;this.#L=s;this.#U=n;this.#gt=r;this.#bt=o;this._eventBus=a;a._on("editingaction",this.onEditingAction.bind(this),{signal:f});a._on("pagechanging",this.onPageChanging.bind(this),{signal:f});a._on("scalechanging",this.onScaleChanging.bind(this),{signal:f});a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f});a._on("setpreference",this.onSetPreference.bind(this),{signal:f});a._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f});window.addEventListener("pointerdown",()=>{this.#nt=!0},{capture:!0,signal:f});window.addEventListener("pointerup",()=>{this.#nt=!1},{capture:!0,signal:f});this.#_t();this.#St();this.#Tt();this.#B=o.annotationStorage;this.#Y=o.filterFactory;this.#mt=l;this.#Z=h||null;this.#q=d;this.#X=c;this.#K=u;this.#dt=p||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=g||null;this._supportsPinchToZoom=!1!==m;n?.setSidebarUiManager(this)}destroy(){this.#Ct?.resolve();this.#Ct=null;this.#k?.abort();this.#k=null;this._signal=null;for(const t of this.#R.values())t.destroy();this.#R.clear();this.#F.clear();this.#j.clear();this.#ht?.clear();this.#P=null;this.#ut.clear();this.#N.destroy();this.#L?.destroy();this.#U?.destroy();this.#gt?.destroy();this.#et?.hide();this.#et=null;this.#lt?.destroy();this.#lt=null;this.#I=null;if(this.#Q){clearTimeout(this.#Q);this.#Q=null}if(this.#At){clearTimeout(this.#At);this.#At=null}this._editorUndoBar?.destroy();this.#bt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#dt}get useNewAltTextFlow(){return this.#X}get useNewAltTextWhenAddingImage(){return this.#K}get hcmFilter(){return shadow(this,"hcmFilter",this.#mt?this.#Y.addHCMFilter(this.#mt.foreground,this.#mt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#vt).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#Z?new Map(this.#Z.split(",").map(t=>{(t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase();return t})):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return shadow(this,"highlightColors",null);const e=new Map,i=!!this.#mt;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 shadow(this,"highlightColors",e)}get highlightColorNames(){return shadow(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){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#z=t}setMainHighlightColorPicker(t){this.#lt=t}editAltText(t,e=!1){this.#L?.editAltText(this,t,e)}hasCommentManager(){return!!this.#U}editComment(t,e,i,s){this.#U?.showDialog(this,t,e,i,s)}selectComment(t,e){const i=this.#R.get(t),s=i?.getEditorByUID(e);s?.toggleComment(!0,!0)}updateComment(t){this.#U?.updateComment(t.getData())}updatePopupColor(t){this.#U?.updatePopupColor(t)}removeComment(t){this.#U?.removeComments([t.uid])}toggleComment(t,e,i=void 0){this.#U?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#U?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#U?.dialogElement||null}async waitForEditorsRendered(t){if(this.#R.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),onEditorsRendered=i=>{if(i.pageNumber===t){this._eventBus._off("editorsrendered",onEditorsRendered);e()}};this._eventBus.on("editorsrendered",onEditorsRendered);await i}getSignature(t){this.#gt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#gt}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.#K=e}onPageChanging({pageNumber:t}){this.#G=t-1}focusMainContainer(){this.#vt.focus()}findParent(t,e){for(const i of this.#R.values()){const{x:s,y:n,width:r,height:a}=i.div.getBoundingClientRect();if(t>=s&&t<=s+r&&e>=n&&e<=n+a)return i}return null}disableUserSelect(t=!1){this.#xt.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*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging();this.#z?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Dt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Mt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#R.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:r,focusOffset:a}=i,o=i.toString(),l=this.#Dt(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const d=this.#Mt(l),c=this.#ct===p.NONE,callback=()=>{const i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:s,anchorOffset:n,focusNode:r,focusOffset:a,text:o});c&&this.showAllEditors("highlight",!0,!0);e&&i?.editComment()};c?this.switchToMode(p.HIGHLIGHT,callback):callback()}commentSelection(t=""){this.highlightSelection(t,!0)}#kt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Dt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#et||=new FloatingToolbar(this);this.#et.show(e,i,"ltr"===this.direction)}}getAndRemoveDataFromAnnotationStorage(t){if(!this.#B)return null;const e=`${u}${t}`,i=this.#B.getRawValue(e);i&&this.#B.remove(e);return i}addToAnnotationStorage(t){t.isEmpty()||!this.#B||this.#B.has(t.id)||this.#B.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Et;if(i){i.setAttribute("data-l10n-id",t);e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args")}}#Pt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#pt){this.#et?.hide();this.#pt=null;this.#It({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#pt)return;const i=this.#Dt(t).closest(".textLayer");if(i){this.#et?.hide();this.#pt=e;this.#It({hasSelectedText:!0});if(this.#ct===p.HIGHLIGHT||this.#ct===p.NONE){this.#ct===p.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#tt=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#ct===p.HIGHLIGHT?this.#Mt(i):null;t?.toggleDrawing();if(this.#nt){const e=new AbortController,i=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Ft("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:i});window.addEventListener("blur",pointerup,{signal:i})}else{t?.toggleDrawing(!0);this.#Ft("main_toolbar")}}}}else if(this.#pt){this.#et?.hide();this.#pt=null;this.#It({hasSelectedText:!1})}}#Ft(t=""){this.#ct===p.HIGHLIGHT?this.highlightSelection(t):this.#q&&this.#kt()}#_t(){document.addEventListener("selectionchange",this.#Pt.bind(this),{signal:this._signal})}#Rt(){if(this.#J)return;this.#J=new AbortController;const t=this.combinedSignal(this.#J);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Lt(){this.#J?.abort();this.#J=null}blur(){this.isShiftKeyDown=!1;if(this.#tt){this.#tt=!1;this.#Ft("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#ut)if(e.div.contains(t)){this.#ot=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#ot)return;const[t,e]=this.#ot;this.#ot=null;e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal});e.focus()}#Tt(){if(this.#at)return;this.#at=new AbortController;const t=this.combinedSignal(this.#at);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Bt(){this.#at?.abort();this.#at=null}#Ot(){if(this.#H)return;this.#H=new AbortController;const t=this.combinedSignal(this.#H);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})}#Nt(){this.#H?.abort();this.#H=null}#St(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Tt();this.#Ot()}removeEditListeners(){this.#Bt();this.#Nt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#$)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#$)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#ut){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.#$)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}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 cmd=()=>{for(const e of t)this.#Ut(e);this.#Ht(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#ct===p.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#tt){this.#tt=!1;this.#Ft("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")}}#It(t){if(Object.entries(t).some(([t,e])=>this.#wt[t]!==e)){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#wt,t)});this.#ct===p.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#zt([[g.HIGHLIGHT_FREE,!0]])}}#zt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Rt();this.#Ot();this.#It({isEditing:this.#ct!==p.NONE,isEmpty:this.#Gt(),hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:this.#N.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Lt();this.#Nt();this.#It({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#$){this.#$=t;for(const t of this.#$)this.#zt(t.defaultPropertiesToUpdate)}}getId(){return this.#it.id}get currentLayer(){return this.#R.get(this.#G)}getLayer(t){return this.#R.get(t)}get currentPageIndex(){return this.#G}addLayer(t){this.#R.set(t.pageIndex,t);this.#st?t.enable():t.disable()}removeLayer(t){this.#R.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,s=!1,n=!1){if(this.#ct!==t){if(this.#Ct){await this.#Ct.promise;if(!this.#Ct)return}this.#Ct=Promise.withResolvers();this.#z?.commitOrRemove();this.#ct===p.POPUP&&this.#U?.hideSidebar();this.#U?.destroyPopup();this.#ct=t;if(t!==p.NONE){for(const t of this.#F.values())t.addStandaloneCommentButton();t===p.SIGNATURE&&await(this.#gt?.loadSignatures());this.setEditingState(!0);await this.#Wt();this.unselectAll();for(const e of this.#R.values())e.updateMode(t);if(t===p.POPUP){this.#I||=await this.#bt.getAnnotationsByType(new Set(this.#$.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#F.values()){const{annotationElementId:s,hasComment:n,deleted:r}=i;s&&t.add(s);n&&!r&&e.push(i.getData())}for(const i of this.#I){const{id:s,popupRef:n,contentsObj:r}=i;n&&r?.str&&!t.has(s)&&!this.#W.has(s)&&e.push(i)}this.#U?.showSidebar(e)}if(e){for(const t of this.#F.values())if(t.uid===e){this.setSelected(t);n?t.editComment():s?t.enterInEditMode():t.focus()}else t.unselect();this.#Ct.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#Ct.resolve()}}else{this.setEditingState(!1);this.#Vt();for(const t of this.#F.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide();this.toggleComment(null);this.#Ct.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#ct&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#$){switch(t){case g.CREATE:this.currentLayer.addNewEditor(e);return;case g.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ft||=new Map).set(t,e);this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#ut)i.updateParams(t,e);else for(const i of this.#$)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#F.values())i.editorType===t&&i.show(e);(this.#ft?.get(g.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#zt([[g.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#rt!==t){this.#rt=t;for(const e of this.#R.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Wt(){if(!this.#st){this.#st=!0;const t=[];for(const e of this.#R.values())t.push(e.enable());await Promise.all(t);for(const t of this.#F.values())t.enable()}}#Vt(){this.unselectAll();if(this.#st){this.#st=!1;for(const t of this.#R.values())t.disable();for(const t of this.#F.values())t.disable()}}*getEditors(t){for(const e of this.#F.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#F.get(t)}addEditor(t){this.#F.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#Q&&clearTimeout(this.#Q);this.#Q=setTimeout(()=>{this.focusMainContainer();this.#Q=null},0)}this.#F.delete(t.id);t.annotationElementId&&this.#ht?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#W.has(t.annotationElementId)||this.#B?.remove(t.id)}addDeletedAnnotationElement(t){this.#W.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#W.has(t)}removeDeletedAnnotationElement(t){this.#W.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Ut(t){const e=this.#R.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#zt(t.propertiesToUpdate)}}get#$t(){let t=null;for(t of this.#ut);return t}updateUI(t){this.#$t===t&&this.#zt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#zt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#ut.has(t)){this.#ut.delete(t);t.unselect();this.#It({hasSelectedEditor:this.hasSelection})}else{this.#ut.add(t);t.select();this.#zt(t.propertiesToUpdate);this.#It({hasSelectedEditor:!0})}}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.id});this.#z?.commitOrRemove();for(const e of this.#ut)e!==t&&e.unselect();this.#ut.clear();this.#ut.add(t);t.select();this.#zt(t.propertiesToUpdate);this.#It({hasSelectedEditor:!0})}isSelected(t){return this.#ut.has(t)}get firstSelectedEditor(){return this.#ut.values().next().value}unselect(t){t.unselect();this.#ut.delete(t);this.#It({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#ut.size}get isEnterHandled(){return 1===this.#ut.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#N.undo();this.#It({hasSomethingToUndo:this.#N.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Gt()});this._editorUndoBar?.hide()}redo(){this.#N.redo();this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:this.#N.hasSomethingToRedo(),isEmpty:this.#Gt()})}addCommands(t){this.#N.add(t);this.#It({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Gt()})}cleanUndoStack(t){this.#N.cleanType(t)}#Gt(){if(0===this.#F.size)return!0;if(1===this.#F.size)for(const t of this.#F.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.#ut],undo=()=>{for(const t of e)this.#Ut(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#Ht(t){for(const t of this.#ut)t.unselect();this.#ut.clear();for(const e of t)if(!e.isEmpty()){this.#ut.add(e);e.select()}this.#It({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#ut)t.commit();this.#Ht(this.#F.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#ct!==p.NONE)return}if(!this.#z?.commitOrRemove()&&this.hasSelection){for(const t of this.#ut)t.unselect();this.#ut.clear();this.#It({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#yt[0]+=t;this.#yt[1]+=e;const[s,n]=this.#yt,r=[...this.#ut];this.#At&&clearTimeout(this.#At);this.#At=setTimeout(()=>{this.#At=null;this.#yt[0]=this.#yt[1]=0;this.addCommands({cmd:()=>{for(const t of r)if(this.#F.has(t.id)){t.translateInPage(s,n);t.translationDone()}},undo:()=>{for(const t of r)if(this.#F.has(t.id)){t.translateInPage(-s,-n);t.translationDone()}},mustExec:!1})},1e3);for(const i of r){i.translateInPage(t,e);i.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#V=new Map;for(const t of this.#ut)this.#V.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#V)return!1;this.disableUserSelect(!1);const t=this.#V;this.#V=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},r]of t){r.newX=i;r.newY=s;r.newPageIndex=n;e||=i!==r.savedX||s!==r.savedY||n!==r.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#F.has(t.id)){const n=this.#R.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#V)for(const i of this.#V.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#ut.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#ct}isEditingMode(){return this.#ct!==p.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}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:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(t,e,a,o)=>({x:(e-s)/r,y:1-(t+a-i)/n,width:o/r,height:a/n});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/n,y:1-(e+o-s)/r,width:a/n,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-s)/r,y:(t-i)/n,width:o/r,height:a/n});break;default:a=(t,e,a,o)=>({x:(t-i)/n,y:(e-s)/r,width:a/n,height:o/r})}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(a(t,e,s,n))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#O||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#O?.delete(t)}renderAnnotationElement(t){const e=this.#O?.get(t.data.id);if(!e)return;const i=this.#B.getRawValue(e);i&&(this.#ct!==p.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const s=this.#ht?.get(t);if(s){s.setCanvas(e,i);this.#ht.delete(t)}}addMissingCanvas(t,e){(this.#ht||=new Map).set(t,e)}}class AltText{#o=null;#jt=!1;#qt=null;#Xt=null;#Kt=null;#Yt=null;#Qt=!1;#Jt=null;#r=null;#Zt=null;#te=null;#ee=!1;static#ie=null;static _l10n=null;constructor(t){this.#r=t;this.#ee=t._uiManager.useNewAltTextFlow;AltText.#ie||=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){AltText._l10n??=t}async render(){const t=this.#qt=document.createElement("button");t.className="altText";t.tabIndex="0";const e=this.#Xt=document.createElement("span");t.append(e);if(this.#ee){t.classList.add("new");t.setAttribute("data-l10n-id",AltText.#ie.missing);e.setAttribute("data-l10n-id",AltText.#ie["missing-label"])}else{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",noContextMenu,{signal:i});t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=t=>{t.preventDefault();this.#r._uiManager.editAltText(this.#r);this.#ee&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#se}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#Qt=!0;onClick(e)}},{signal:i});await this.#ne();return t}get#se(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#qt){this.#qt.focus({focusVisible:this.#Qt});this.#Qt=!1}}isEmpty(){return this.#ee?null===this.#o:!this.#o&&!this.#jt}hasData(){return this.#ee?null!==this.#o||!!this.#Zt:this.isEmpty()}get guessedText(){return this.#Zt}async setGuessedText(t){if(null===this.#o){this.#Zt=t;this.#te=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#ne()}}toggleAltTextBadge(t=!1){if(this.#ee&&!this.#o){if(!this.#Jt){const t=this.#Jt=document.createElement("div");t.className="noAltTextBadge";this.#r.div.append(t)}this.#Jt.classList.toggle("hidden",!t)}else{this.#Jt?.remove();this.#Jt=null}}serialize(t){let e=this.#o;t||this.#Zt!==e||(e=this.#te);return{altText:e,decorative:this.#jt,guessedText:this.#Zt,textWithDisclaimer:this.#te}}get data(){return{altText:this.#o,decorative:this.#jt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Zt=i;this.#te=s}if(this.#o!==t||this.#jt!==e){if(!n){this.#o=t;this.#jt=e}this.#ne()}}toggle(t=!1){if(this.#qt){if(!t&&this.#Yt){clearTimeout(this.#Yt);this.#Yt=null}this.#qt.disabled=!t}}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#se}})}destroy(){this.#qt?.remove();this.#qt=null;this.#Xt=null;this.#Kt=null;this.#Jt?.remove();this.#Jt=null}async#ne(){const t=this.#qt;if(!t)return;if(this.#ee){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#ie[this.#se]);this.#Xt?.setAttribute("data-l10n-id",AltText.#ie[`${this.#se}-label`]);if(!this.#o){this.#Kt?.remove();return}}else{if(!this.#o&&!this.#jt){t.classList.remove("done");this.#Kt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Kt;if(!e){this.#Kt=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.#Yt);this.#Yt=null},{once:!0});t.addEventListener("mouseenter",()=>{this.#Yt=setTimeout(()=>{this.#Yt=null;this.#Kt.classList.add("show");this.#r._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:s});t.addEventListener("mouseleave",()=>{if(this.#Yt){clearTimeout(this.#Yt);this.#Yt=null}this.#Kt?.classList.remove("show")},{signal:s})}if(this.#jt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#r.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#re=null;#ae=null;#oe=!1;#r=null;#le=null;#he=null;#de=null;#ce=null;#ue=!1;#pe=null;constructor(t){this.#r=t}renderForToolbar(){const t=this.#ae=document.createElement("button");t.className="comment";return this.#w(t,!1)}renderForStandalone(){const t=this.#re=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.#w(t,!0)}focusButton(){setTimeout(()=>{(this.#re??this.#ae)?.focus()},0)}onUpdatedColor(){if(!this.#re)return;const t=this.#r.commentButtonColor;t&&(this.#re.style.backgroundColor=t);this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#re?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#pe)return this.#pe;if(!this.#re)return null;const{x:t,y:e,height:i}=this.#re.getBoundingClientRect(),{x:s,y:n,width:r,height:a}=this.#r.parent.boundingClientRect;return[(t-s)/r,(e+i-n)/a]}set commentPopupPositionInLayer(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}removeStandaloneCommentButton(){this.#re?.remove();this.#re=null}removeToolbarCommentButton(){this.#ae?.remove();this.#ae=null}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#re){this.#re.classList.toggle("selected",t);this.#re.ariaExpanded=e}}#w(t,e){if(!this.#r._uiManager.hasCommentManager())return null;t.tabIndex="0";t.ariaHasPopup="dialog";if(e){t.ariaControls="commentPopup";t.setAttribute("data-l10n-id","pdfjs-show-comment-button")}else{t.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()];t.setAttribute("data-l10n-id","pdfjs-editor-edit-comment-button")}const i=this.#r._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i});if(e){t.addEventListener("focusin",t=>{this.#r._focusEventsAllowed=!1;stopEvent(t)},{capture:!0,signal:i});t.addEventListener("focusout",t=>{this.#r._focusEventsAllowed=!0;stopEvent(t)},{capture:!0,signal:i})}t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=e=>{e.preventDefault();t===this.#ae?this.edit():this.#r.toggleComment(!0)};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#oe=!0;onClick(e)}},{signal:i});t.addEventListener("pointerenter",()=>{this.#r.toggleComment(!1,!0)},{signal:i});t.addEventListener("pointerleave",()=>{this.#r.toggleComment(!1,!1)},{signal:i});return 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:r}=this.#r;i=n+i*t;s=r+s*e}const n=this.#r.parent.boundingClientRect,{x:r,y:a,width:o,height:l}=n;this.#r._uiManager.editComment(this.#r,r+i*o,a+s*l,{...t,parentDimensions:n})}finish(){if(this.#ae){this.#ae.focus({focusVisible:this.#oe});this.#oe=!1}}isDeleted(){return this.#ue||""===this.#de}isEmpty(){return null===this.#de}hasBeenEdited(){return this.isDeleted()||this.#de!==this.#le}serialize(){return this.data}get data(){return{text:this.#de,richText:this.#he,date:this.#ce,deleted:this.isDeleted()}}set data(t){t!==this.#de&&(this.#he=null);if(null!==t){this.#de=t;this.#ce=new Date;this.#ue=!1}else{this.#de="";this.#ue=!0}}setInitialText(t,e=null){this.#le=t;this.data=t;this.#ce=null;this.#he=e}shown(){}destroy(){this.#ae?.remove();this.#ae=null;this.#re?.remove();this.#re=null;this.#de="";this.#he=null;this.#ce=null;this.#r=null;this.#oe=!1;this.#ue=!1}}class TouchManager{#vt;#ge=!1;#me=null;#fe;#be;#we;#ye;#Ae=null;#ve;#xe=null;#Ee;#Ce=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#vt=t;this.#me=i;this.#fe=e;this.#be=s;this.#we=n;this.#ye=r;this.#Ee=new AbortController;this.#ve=AbortSignal.any([a,this.#Ee.signal]);t.addEventListener("touchstart",this.#_e.bind(this),{passive:!1,signal:this.#ve})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#_e(t){if(this.#fe?.())return;if(1===t.touches.length){if(this.#Ae)return;const t=this.#Ae=new AbortController,e=AbortSignal.any([this.#ve,t.signal]),i=this.#vt,s={capture:!0,signal:e,passive:!1},cancelPointerDown=t=>{if("touch"===t.pointerType){this.#Ae?.abort();this.#Ae=null}};i.addEventListener("pointerdown",t=>{if("touch"===t.pointerType){stopEvent(t);cancelPointerDown(t)}},s);i.addEventListener("pointerup",cancelPointerDown,s);i.addEventListener("pointercancel",cancelPointerDown,s);return}if(!this.#Ce){this.#Ce=new AbortController;const t=AbortSignal.any([this.#ve,this.#Ce.signal]),e=this.#vt,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Se.bind(this),i);const s=this.#Te.bind(this);e.addEventListener("touchend",s,i);e.addEventListener("touchcancel",s,i);i.capture=!0;e.addEventListener("pointerdown",stopEvent,i);e.addEventListener("pointermove",stopEvent,i);e.addEventListener("pointercancel",stopEvent,i);e.addEventListener("pointerup",stopEvent,i);this.#be?.()}stopEvent(t);if(2!==t.touches.length||this.#me?.()){this.#xe=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#xe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Se(t){if(!this.#xe||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:r,screenY:a}=i,o=this.#xe,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=r-s,m=a-n,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#ge&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=r;o.touch1Y=a;if(!this.#ge){this.#ge=!0;return}const w=[(s+r)/2,(n+a)/2];this.#we?.(w,b,f)}#Te(t){if(!(t.touches.length>=2)){if(this.#Ce){this.#Ce.abort();this.#Ce=null;this.#ye?.()}if(this.#xe){stopEvent(t);this.#xe=null;this.#ge=!1}}}destroy(){this.#Ee?.abort();this.#Ee=null;this.#Ae?.abort();this.#Ae=null}}class AnnotationEditor{#De=null;#Me=null;#o=null;#l=null;#re=null;#ke=!1;#Pe=null;#Ie="";#Fe=null;#Re=null;#Le=null;#Be=null;#Oe=null;#Ne="";#Ue=!1;#He=null;#ze=!1;#Ge=!1;#We=!1;#Ve=null;#$e=0;#je=0;#qe=null;#Xe=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#Ke=!1;#Ye=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["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"],AnnotationEditor.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;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,r];const[a,o]=this.parentDimensions;this.x=t.x/a;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}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 shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._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"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Ke}set _isDraggable(t){this.#Ke=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.#Ye}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else{this.#Qe();this.#Be?.remove();this.#Be=null}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ue?this.#Ue=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!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,r]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/r;this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s);this._onTranslated()}#Je([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.#Je(this.parentDimensions,t,e)}translateInPage(t,e){this.#He||=[this.x,this.y,this.width,this.height];this.#Je(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#He||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o;a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`;h.top=`${(100*a).toFixed(2)}%`;this._onTranslating(r,a);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#He&&(this.#He[0]!==this.x||this.#He[1]!==this.y)}get _hasBeenResized(){return!!this.#He&&(this.#He[2]!==this.width||this.#He[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,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:r,width:a,height:o}=this;a*=i;o*=s;n*=i;r*=s;if(this._mustFixPosition)switch(t){case 0:n=MathClamp(n,0,i-a);r=MathClamp(r,0,s-o);break;case 90:n=MathClamp(n,0,i-o);r=MathClamp(r,a,s);break;case 180:n=MathClamp(n,a,i);r=MathClamp(r,o,s);break;case 270:n=MathClamp(n,o,i);r=MathClamp(r,0,s-a)}this.x=n/=i;this.y=r/=s;const[l,h]=this.getBaseTranslation();n+=l;r+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*r).toFixed(2)}%`;this.moveInDOM()}static#Ze(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 AnnotationEditor.#Ze(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Ze(t,e,360-this.parentRotation)}#ti(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]}#ei(){if(this.#Fe)return;this.#Fe=document.createElement("div");this.#Fe.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.#Fe.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#ii.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#Fe)}#ii(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#Re=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#si.bind(this,t),{passive:!0,capture:!0,signal:r});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:r});window.addEventListener("contextmenu",noContextMenu,{signal:r});this.#Le={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const 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;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=a;this.div.style.cursor=o;this.#ni()};window.addEventListener("pointerup",pointerUpCallback,{signal:r});window.addEventListener("blur",pointerUpCallback,{signal:r})}#ri(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;this.setDims();this.fixAndSetPosition();this._onResized()}_onResized(){}#ni(){if(!this.#Le)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#Le;this.#Le=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===i&&o===s||this.addCommands({cmd:this.#ri.bind(this,n,r,a,o),undo:this.#ri.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#si(t,e){const[i,s]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,d=this.#ti(this.rotation),transf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],c=this.#ti(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(a,o),b=p(a,o);let w=transf(...b);const y=AnnotationEditor._round(n+w[0]),A=AnnotationEditor._round(r+w[1]);let v,x,E=1,C=1;if(e.fromKeyboard)({deltaX:v,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#Re;[v,x]=this.screenToPageTranslation(t-s,i-n);this.#Re[0]=t;this.#Re[1]=i}[v,x]=(_=v/i,S=x/s,[c[0]*_+c[2]*S,c[1]*_+c[3]*S]);var _,S;if(g){const t=Math.hypot(a,o);E=C=Math.max(Math.min(Math.hypot(b[0]-f[0]-v,b[1]-f[1]-x)/t,1/a,1/o),l/a,h/o)}else m?E=MathClamp(Math.abs(b[0]-f[0]-v),l,1)/a:C=MathClamp(Math.abs(b[1]-f[1]-x),h,1)/o;const T=AnnotationEditor._round(a*E),D=AnnotationEditor._round(o*C);w=transf(...p(T,D));const M=y-w[0],k=A-w[1];this.#He||=[this.x,this.y,this.width,this.height];this.width=T;this.height=D;this.x=M;this.y=k;this.setDims();this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#Ge)return this._editToolbar;this._editToolbar=new EditorToolbar(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);this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton());this._editToolbar.addButton("delete");return this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove();this._editToolbar=null;this.#o?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#De){this.#o.data=this.#De;this.#De=null}}return this.#o}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}focusCommentButton(){this.#l?.focusButton()}addCommentButton(){return this.#l||=new Comment(this)}addStandaloneCommentButton(){if(this.#re)this._uiManager.isEditingMode()&&this.#re.classList.remove("hidden");else if(this.hasComment){this.#re=this.#l.renderForStandalone();this.div.append(this.#re)}}removeStandaloneCommentButton(){this.#l.removeStandaloneCommentButton();this.#re=null}hideStandaloneCommentButton(){this.#re?.classList.add("hidden")}get comment(){const{data:{richText:t,text:e,date:i,deleted:s}}=this.#l;return{text:e,richText:t,date:i,deleted:s,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#l||=new Comment(this);this.#l.data=t;if(this.hasComment){this.removeCommentButtonFromToolbar();this.addStandaloneCommentButton();this._uiManager.updateComment(this)}else{this.addCommentButtonInToolbar();this.removeStandaloneCommentButton();this._uiManager.removeComment(this)}}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;this.#l||=new Comment(this);this.#l.setInitialText(t,i);if(!this.annotationElementId)return;const s=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);s&&this.updateFromAnnotationLayer(s)}get hasEditedComment(){return this.#l?.hasBeenEdited()}get hasDeletedComment(){return this.#l?.isDeleted()}get hasComment(){return!!this.#l&&!this.#l.isEmpty()&&!this.#l.isDeleted()}async editComment(t){this.#l||=new Comment(this);this.#l.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#l.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,s]=t.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,a=r+n+1,o=s-i,l=a+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[a,o,l,s]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#l.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.#ke?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#ai();const[e,i]=this.parentDimensions;if(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();this.translate(s,n);bindEvents(this,t,["keydown","pointerdown","dblclick"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Xe||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#oi.bind(this),onPinching:this.#li.bind(this),onPinchEnd:this.#hi.bind(this),signal:this._uiManager._signal}));this.addStandaloneCommentButton();this._uiManager._editorUndoBar?.hide();return t}#oi(){this.#Le={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#li(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#ti(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[r,a]=this.parentDimensions,o=this.x,l=this.y,h=this.width,d=this.height,c=AnnotationEditor.MIN_SIZE/r,u=AnnotationEditor.MIN_SIZE/a;s=Math.max(Math.min(s,1/h,1/d),c/h,u/d);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(d*s);if(p===h&&g===d)return;this.#He||=[o,l,h,d];const m=transf(h/2,d/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),w=transf(p/2,g/2);this.x=f-w[0];this.y=b-w[1];this.width=p;this.height=g;this.setDims();this.fixAndSetPosition();this._onResizing()}#hi(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#ni()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#Ue=!0;this._isDraggable?this.#di(t):this.#ci(t)}}#ci(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#di(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),r={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#Pe=null;this.#Ue=!1;this._uiManager.endDragSession()||this.#ci(t);i&&this._onStopDragging()};if(e){this.#$e=t.clientX;this.#je=t.clientY;this.#Pe=t.pointerId;this.#Ie=t.pointerType;window.addEventListener("pointermove",t=>{if(!i){i=!0;this._uiManager.toggleComment(this,!0,!1);this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#Pe){stopEvent(t);return}const[r,a]=this.screenToPageTranslation(e-this.#$e,s-this.#je);this.#$e=e;this.#je=s;this._uiManager.dragSelectedEditors(r,a)},r);window.addEventListener("touchmove",stopEvent,r);window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ie&&(this.#Xe||t.isPrimary)&&cancelDrag(t);stopEvent(t)},r)}const pointerUpCallback=t=>{this.#Pe&&this.#Pe!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Ve&&clearTimeout(this.#Ve);this.#Ve=setTimeout(()=>{this.#Ve=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,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*n,c=this.y*r,u=this.width*n,p=this.height*r;switch(i){case 0:return[d+l+a,r-c-h-p+o,d+l+u+a,r-c-h+o];case 90:return[d+h+a,r-c+l+o,d+h+p+a,r-c+l+u+o];case 180:return[d-l-u+a,r-c+h+o,d-l+a,r-c+h+p+o];case 270:return[d-h-p+a,r-c-l-u+o,d-h+a,r-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,r]=t,a=n-i,o=r-s;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-s,o,a];case 180:return[n,e-s,a,o];case 270:return[n,e-r,o,a];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#l?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:s,deleted:n,richText:r},uid:a,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:a,pageIndex:o,rect:this.getPDFRect(),richText:r,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!n,color:e,opacity:s}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;this.parent.setEditingState(!1);this.#Ge=!0;return!0}disableEditMode(){if(!this.isInEditMode())return!1;this.parent.setEditingState(!0);this.#Ge=!1;return!0}isInEditMode(){return this.#Ge}shouldGetKeyboardEvents(){return this.#We}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&s>0&&t<n&&i>0}#ai(){if(this.#Oe||!this.div)return;this.#Oe=new AbortController;const t=this._uiManager.combinedSignal(this.#Oe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ai()}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:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});s.rotation=t.rotation;s.#De=t.accessibilityData;s._isCopy=t.isCopy||!1;const[n,r]=s.pageDimensions,[a,o,l,h]=s.getRectInCurrentCoords(t.rect,r);s.x=a/n;s.y=o/r;s.width=l/n;s.height=h/r;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#Oe?.abort();this.#Oe=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Ve){clearTimeout(this.#Ve);this.#Ve=null}this.#Qe();this.removeEditToolbar();if(this.#qe){for(const t of this.#qe.values())clearTimeout(t);this.#qe=null}this.parent=null;this.#Xe?.destroy();this.#Xe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#ei();this.#Fe.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,r]=this.getPDFRect();return[AnnotationEditor._round(i+(n-i)*t),AnnotationEditor._round(s+(r-s)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#l.commentPopupPositionInLayer}set commentPopupPosition(t){this.#l.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#l.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#l.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#l.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#Le={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#Fe.children;if(!this.#Me){this.#Me=Array.from(e);const t=this.#ui.bind(this),i=this.#pi.bind(this),s=this._uiManager._signal;for(const e of this.#Me){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.#gi.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#Me[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#Me.length/4);if(n!==s){if(n<s)for(let t=0;t<s-n;t++)this.#Fe.append(this.#Fe.firstChild);else if(n>s)for(let t=0;t<n-s;t++)this.#Fe.firstChild.before(this.#Fe.lastChild);let t=0;for(const i of e){const e=this.#Me[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[e])}}this.#mi(0);this.#We=!0;this.#Fe.firstChild.focus({focusVisible:!0});t.preventDefault();t.stopImmediatePropagation()}#ui(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#pi(t){this.#We&&t.relatedTarget?.parentNode!==this.#Fe&&this.#Qe()}#gi(t){this.#Ne=this.#We?t:""}#mi(t){if(this.#Me)for(const e of this.#Me)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#We&&this.#si(this.#Ne,{deltaX:t,deltaY:e,fromKeyboard:!0})}#Qe(){this.#We=!1;this.#mi(-1);this.#ni()}_stopResizingWithKeyboard(){this.#Qe();this.div.focus()}select(){if(this.isSelected&&this._editToolbar)this._editToolbar.show();else{this.isSelected=!0;this.makeResizable();this.div?.classList.add("selectedEditor");if(this._editToolbar){this._editToolbar?.show();this.#o?.toggleAltTextBadge(!1)}else 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(){if(this.isSelected){this.isSelected=!1;this.#Fe?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0);this.hasComment&&this._uiManager.toggleComment(this,!1,!1)}}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){if(this.canChangeContent){this.enableEditMode();this.div.focus()}}dblclick(t){if("BUTTON"!==t.target.nodeName){this.enterInEditMode();this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.id})}}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#ze}set isEditing(t){this.#ze=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else 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.#qe||=new Map;const{action:e}=t;let i=this.#qe.get(e);i&&clearTimeout(i);i=setTimeout(()=>{this._reportTelemetry(t);this.#qe.delete(e);0===this.#qe.size&&(this.#qe=null)},AnnotationEditor._telemetryTimeout);this.#qe.set(e,i);return}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.#ke=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#ke=!0}updateFakeAnnotationElement(t){if(this.#Be||this.deleted)if(this.deleted){this.#Be.remove();this.#Be=null}else(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Be.updateEdited({rect:this.getPDFRect(),popup:this.comment});else this.#Be=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted){t.hide();return 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{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const $=3285377520,j=4294901760,q=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:$;this.h2=t?4294967295&t:$}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);if(n<=255)e[i++]=n;else{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,r=new Uint32Array(e.buffer,0,s);let a=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t<s;t++)if(1&t){a=r[t];a=a*d&j|a*u&q;a=a<<15|a>>>17;a=a*c&j|a*p&q;l^=a;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[t];o=o*d&j|o*u&q;o=o<<15|o>>>17;o=o*c&j|o*p&q;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}a=0;switch(n){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&j|a*u&q;a=a<<15|a>>>17;a=a*c&j|a*p&q;1&s?l^=a:h^=a}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&j|36045*t&q;e=4283543511*e&j|(2950163797*(e<<16|t>>>16)&j)>>>16;t^=e>>>1;t=444984403*t&j|60499*t&q;e=3301882366*e&j|(3120437893*(e<<16|t>>>16)&j)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const X=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#fi=!1;#bi=null;#wi=null;#yi=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#yi.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#yi.get(t)}remove(t){const e=this.#yi.get(t);if(void 0!==e){e instanceof AnnotationEditor&&this.#wi.delete(e.annotationElementId);this.#yi.delete(t);0===this.#yi.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#yi.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}}setValue(t,e){const i=this.#yi.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#yi.set(t,e)}s&&this.#Ai();if(e instanceof AnnotationEditor){(this.#wi||=new Map).set(e.annotationElementId,e);"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}}has(t){return this.#yi.has(t)}get size(){return this.#yi.size}#Ai(){if(!this.#fi){this.#fi=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#fi){this.#fi=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#yi.size)return X;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,r]of this.#yi){const a=r instanceof AnnotationEditor?r.serialize(!1,s):r;if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);n||=!!a.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}:X}get editorStats(){let t=null;const e=new Map;let i=0,s=0;for(const n of this.#yi.values()){if(!(n instanceof AnnotationEditor)){n.popup&&(n.popup.deleted?s+=1:i+=1);continue}n.isCommentDeleted?s+=1:n.hasEditedComment&&(i+=1);const r=n.telemetryFinalData;if(!r)continue;const{type:a}=r;e.has(a)||e.set(a,Object.getPrototypeOf(n).constructor);t||=Object.create(null);const o=t[a]||=new Map;for(const[t,e]of Object.entries(r)){if("type"===t)continue;let i=o.get(t);if(!i){i=new Map;o.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}if(s>0||i>0){t||=Object.create(null);t.comments={deleted:s,edited:i}}if(!t)return null;for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#bi=null}updateEditor(t,e){const i=this.#wi?.get(t);if(i){i.updateFromAnnotationLayer(e);return!0}return!1}getEditor(t){return this.#wi?.get(t)||null}get modifiedIds(){if(this.#bi)return this.#bi;const t=[];if(this.#wi)for(const e of this.#wi.values())e.serialize()&&t.push(e.annotationElementId);return this.#bi={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#yi.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#vi;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#vi={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#vi}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#xi=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){if(!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.#xi.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#xi.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:s,style:n}=t,r=new FontFace(e,s,n);this.addNativeFontFace(r);try{await r.load();this.#xi.add(e);i?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(r)}return}unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",t||util_FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const r=n.getContext("2d");let a=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let d=int32(l,16);for(i=0,s=o.length-3;i<s;i+=4)d=d-h+int32(o,i)|0;i<o.length&&(d=d-h+int32(o+"XXX",i)|0);l=spliceString(l,16,4,function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}(d));const c=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(c);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++a>30){warn("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,()=>{u.remove();e.complete()})}}class FontFaceObject{#Ei;constructor(t,e=null,i,s){this.compiledGlyphs=Object.create(null);this.#Ei=t;this._inspectFont=e;i&&Object.assign(this,i);s&&(this.charProcOperatorList=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,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;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}}`;this._inspectFont?.(this,t);return 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){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}get black(){return this.#Ei.black}get bold(){return this.#Ei.bold}get disableFontFace(){return this.#Ei.disableFontFace??!1}get fontExtraProperties(){return this.#Ei.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#Ei.isInvalidPDFjsFont}get isType3Font(){return this.#Ei.isType3Font}get italic(){return this.#Ei.italic}get missingFile(){return this.#Ei.missingFile}get remeasure(){return this.#Ei.remeasure}get vertical(){return this.#Ei.vertical}get ascent(){return this.#Ei.ascent}get defaultWidth(){return this.#Ei.defaultWidth}get descent(){return this.#Ei.descent}get bbox(){return this.#Ei.bbox}get fontMatrix(){return this.#Ei.fontMatrix}get fallbackName(){return this.#Ei.fallbackName}get loadedName(){return this.#Ei.loadedName}get mimetype(){return this.#Ei.mimetype}get name(){return this.#Ei.name}get data(){return this.#Ei.data}clearData(){this.#Ei.clearData()}get cssFontInfo(){return this.#Ei.cssFontInfo}get systemFontInfo(){return this.#Ei.systemFontInfo}get defaultVMetrics(){return this.#Ei.defaultVMetrics}}function getFactoryUrlProp(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const isRefProxy=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,K=function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[s,n,...r]=i;if(!t(s)&&!Number.isInteger(s))return!1;if(!e(n))return!1;const a=r.length;let o=!0;switch(n.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(const t of r)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,isRefProxy,t=>"object"==typeof t&&"string"==typeof t?.name);class LoopbackPort{#Ci=new Map;#_i=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#_i.then(()=>{for(const[t]of this.#Ci)t.call(this,i)})}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#Ci.set(e,s)}removeEventListener(t,e){const i=this.#Ci.get(e);i?.();this.#Ci.delete(e)}terminate(){for(const[,t]of this.#Ci)t?.();this.#Ci.clear()}}const Y=1,Q=2,J=1,Z=2,tt=3,et=4,it=5,st=6,nt=7,rt=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof PasswordException||t instanceof ResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"ResponseException":return new ResponseException(t.message,t.status,t.missing);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#Si=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.#Ti.bind(this),{signal:this.#Si.signal})}#Ti({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#Di(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===Y)i.resolve(t.data);else{if(t.callback!==Q)throw new Error("Unexpected callback case");i.reject(wrapReason(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;Promise.try(e,t.data).then(function(e){n.postMessage({sourceName:i,targetName:s,callback:Y,callbackId:t.callbackId,data:e})},function(e){n.postMessage({sourceName:i,targetName:s,callback:Q,callbackId:t.callbackId,reason:wrapReason(e)})});return}t.streamId?this.#Mi(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++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:r,targetName:a,stream:st,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:r,targetName:a,stream:J,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#Mi(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:et,streamId:e,chunk:t},a)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:tt,streamId:e});delete r.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:it,streamId:e,reason:wrapReason(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(){n.postMessage({sourceName:i,targetName:s,stream:rt,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:rt,streamId:e,reason:wrapReason(t)})})}#Di(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case rt:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case nt:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case st:if(!a){n.postMessage({sourceName:i,targetName:s,stream:nt,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve();a.desiredSize=t.desiredSize;Promise.try(a.onPull||onFn).then(function(){n.postMessage({sourceName:i,targetName:s,stream:nt,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:nt,streamId:e,reason:wrapReason(t)})});break;case et:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case tt:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#ki(r,e);break;case it:assert(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#ki(r,e);break;case Z:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#ki(r,e);break;case J:if(!a)break;const o=wrapReason(t.reason);Promise.try(a.onCancel||onFn,o).then(function(){n.postMessage({sourceName:i,targetName:s,stream:Z,streamId:e,success:!0})},function(t){n.postMessage({sourceName:i,targetName:s,stream:Z,streamId:e,reason:wrapReason(t)})});a.sinkCapability.reject(o);a.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#ki(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#Si?.abort();this.#Si=null}}class BaseCanvasFactory{#Pi=!1;constructor({enableHWA:t=!1}){this.#Pi=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.#Pi})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#Ii;#Fi;#Ri;#Li;#Bi;#Oi;#v=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#Li=t;this.#Bi=e}get#E(){return this.#Fi||=new Map}get#Ni(){return this.#Oi||=new Map}get#Ui(){if(!this.#Ri){const t=this.#Bi.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#Bi.createElementNS(G,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#Ri=this.#Bi.createElementNS(G,"defs");t.append(i);i.append(this.#Ri);this.#Bi.body.append(t)}return this.#Ri}#Hi(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),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;r[t]=i[t]/255;a[t]=s[t]/255}return[n.join(","),r.join(","),a.join(",")]}#zi(t){if(void 0===this.#Ii){this.#Ii="";const t=this.#Bi.URL;t!==this.#Bi.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#Ii=updateUrlHash(t,""))}return`url(${this.#Ii}#${t})`}addFilter(t){if(!t)return"none";let e=this.#E.get(t);if(e)return e;const[i,s,n]=this.#Hi(t),r=1===t.length?i:`${i}${s}${n}`;e=this.#E.get(r);if(e){this.#E.set(t,e);return e}const a=`g_${this.#Li}_transfer_map_${this.#v++}`,o=this.#zi(a);this.#E.set(t,o);this.#E.set(r,o);const l=this.#Gi(a);this.#Wi(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#Ni.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#Ni.set(s,n)}if(!t||!e)return n.url;const r=this.#Vi(t);t=Util.makeHexColor(...r);const a=this.#Vi(e);e=Util.makeHexColor(...a);this.#Ui.style.color="";if("#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.#Li}_hcm_filter`,d=n.filter=this.#Gi(h);this.#Wi(l,l,l,d);this.#$i(d);const getSteps=(t,e)=>{const i=r[t]/255,s=a[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#Wi(getSteps(0,5),getSteps(1,5),getSteps(2,5),d);n.url=this.#zi(h);return n.url}addAlphaFilter(t){let e=this.#E.get(t);if(e)return e;const[i]=this.#Hi([t]),s=`alpha_${i}`;e=this.#E.get(s);if(e){this.#E.set(t,e);return e}const n=`g_${this.#Li}_alpha_map_${this.#v++}`,r=this.#zi(n);this.#E.set(t,r);this.#E.set(s,r);const a=this.#Gi(n);this.#ji(i,a);return r}addLuminosityFilter(t){let e,i,s=this.#E.get(t||"luminosity");if(s)return s;if(t){[e]=this.#Hi([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#E.get(i);if(s){this.#E.set(t,s);return s}const n=`g_${this.#Li}_luminosity_map_${this.#v++}`,r=this.#zi(n);this.#E.set(t,r);this.#E.set(i,r);const a=this.#Gi(n);this.#qi(a);t&&this.#ji(e,a);return r}addHighlightHCMFilter(t,e,i,s,n){const r=`${e}-${i}-${s}-${n}`;let a=this.#Ni.get(t);if(a?.key===r)return a.url;if(a){a.filter?.remove();a.key=r;a.url="none";a.filter=null}else{a={key:r,url:"none",filter:null};this.#Ni.set(t,a)}if(!e||!i)return a.url;const[o,l]=[e,i].map(this.#Vi.bind(this));let 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,n].map(this.#Vi.bind(this));d<h&&([h,d,c,u]=[d,h,u,c]);this.#Ui.style.color="";const getSteps=(t,e,i)=>{const s=new Array(256),n=(d-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=r+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(",")},p=`g_${this.#Li}_hcm_${t}_filter`,g=a.filter=this.#Gi(p);this.#$i(g);this.#Wi(getSteps(c[0],u[0],5),getSteps(c[1],u[1],5),getSteps(c[2],u[2],5),g);a.url=this.#zi(p);return a.url}destroy(t=!1){if(!t||!this.#Oi?.size){this.#Ri?.parentNode.parentNode.remove();this.#Ri=null;this.#Fi?.clear();this.#Fi=null;this.#Oi?.clear();this.#Oi=null;this.#v=0}}#qi(t){const e=this.#Bi.createElementNS(G,"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)}#$i(t){const e=this.#Bi.createElementNS(G,"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)}#Gi(t){const e=this.#Bi.createElementNS(G,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#Ui.append(e);return e}#Xi(t,e,i){const s=this.#Bi.createElementNS(G,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#Wi(t,e,i,s){const n=this.#Bi.createElementNS(G,"feComponentTransfer");s.append(n);this.#Xi(n,"feFuncR",t);this.#Xi(n,"feFuncG",e);this.#Xi(n,"feFuncB",i)}#ji(t,e){const i=this.#Bi.createElementNS(G,"feComponentTransfer");e.append(i);this.#Xi(i,"feFuncA",t)}#Vi(t){this.#Ui.style.color=t;return getRGB(getComputedStyle(this.#Ui).getPropertyValue("color"))}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}class BaseWasmFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw new Error(`Unable to load wasm data at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMWasmFactory extends BaseWasmFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}t&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeWasmFactory extends BaseWasmFactory{async _fetch(t){return node_utils_fetchData(t)}}const at="__forcedDependency",{floor:ot,ceil:lt}=Math;function expandBBox(t,e,i,s,n,r){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],r)}const ht=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Ki;#Yi;constructor(t,e){this.#Ki=t;this.#Yi=e}get length(){return this.#Ki.length}isEmpty(t){return this.#Ki[t]===ht}minX(t){return this.#Yi[4*t+0]/256}minY(t){return this.#Yi[4*t+1]/256}maxX(t){return(this.#Yi[4*t+2]+1)/256}maxY(t){return(this.#Yi[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>{if(!t)return;let i=t.get(e);if(!i){i={dependencies:new Set,isRenderingOperation:!1};t.set(e,i)}return i};class CanvasDependencyTracker{#Qi={__proto__:null};#Ji={__proto__:null,transform:[],moveText:[],sameLineText:[],[at]:[]};#Zi=new Map;#ts=[];#es=[];#is=[[1,0,0,1,0,0]];#ss=[-1/0,-1/0,1/0,1/0];#ns=new Float64Array([1/0,1/0,-1/0,-1/0]);#rs=-1;#as=new Set;#os=new Map;#ls=new Map;#hs;#ds;#cs;#Ki;#us;constructor(t,e,i=!1){this.#hs=t.width;this.#ds=t.height;this.#ps(e);i&&(this.#us=new Map)}growOperationsCount(t){t>=this.#Ki.length&&this.#ps(t,this.#Ki)}#ps(t,e){const i=new ArrayBuffer(4*t);this.#cs=new Uint8ClampedArray(i);this.#Ki=new Uint32Array(i);if(e&&e.length>0){this.#Ki.set(e);this.#Ki.fill(ht,e.length)}else this.#Ki.fill(ht)}save(t){this.#Qi={__proto__:this.#Qi};this.#Ji={__proto__:this.#Ji,transform:{__proto__:this.#Ji.transform},moveText:{__proto__:this.#Ji.moveText},sameLineText:{__proto__:this.#Ji.sameLineText},[at]:{__proto__:this.#Ji[at]}};this.#ss={__proto__:this.#ss};this.#ts.push(t);return this}restore(t){const e=Object.getPrototypeOf(this.#Qi);if(null===e)return this;this.#Qi=e;this.#Ji=Object.getPrototypeOf(this.#Ji);this.#ss=Object.getPrototypeOf(this.#ss);const i=this.#ts.pop();if(void 0!==i){ensureDebugMetadata(this.#us,t)?.dependencies.add(i);this.#Ki[t]=this.#Ki[i]}return this}recordOpenMarker(t){this.#ts.push(t);return this}getOpenMarker(){return 0===this.#ts.length?null:this.#ts.at(-1)}recordCloseMarker(t){const e=this.#ts.pop();if(void 0!==e){ensureDebugMetadata(this.#us,t)?.dependencies.add(e);this.#Ki[t]=this.#Ki[e]}return this}beginMarkedContent(t){this.#es.push(t);return this}endMarkedContent(t){const e=this.#es.pop();if(void 0!==e){ensureDebugMetadata(this.#us,t)?.dependencies.add(e);this.#Ki[t]=this.#Ki[e]}return this}pushBaseTransform(t){this.#is.push(Util.multiplyByDOMMatrix(this.#is.at(-1),t.getTransform()));return this}popBaseTransform(){this.#is.length>1&&this.#is.pop();return this}recordSimpleData(t,e){this.#Qi[t]=e;return this}recordIncrementalData(t,e){this.#Ji[t].push(e);return this}resetIncrementalData(t,e){this.#Ji[t].length=0;return this}recordNamedData(t,e){this.#Zi.set(t,e);return this}recordSimpleDataFromNamed(t,e,i){this.#Qi[t]=this.#Zi.get(e)??i}recordFutureForcedDependency(t,e){this.recordIncrementalData(at,e);return this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Qi&&this.recordFutureForcedDependency(e,this.#Qi[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#as)this.recordFutureForcedDependency(at,t);return this}resetBBox(t){if(this.#rs!==t){this.#rs=t;this.#ns[0]=1/0;this.#ns[1]=1/0;this.#ns[2]=-1/0;this.#ns[3]=-1/0}return this}recordClipBox(t,e,i,s,n,r){const a=Util.multiplyByDOMMatrix(this.#is.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,n,s,r],a,o);const l=Util.intersect(this.#ss,o);if(l){this.#ss[0]=l[0];this.#ss[1]=l[1];this.#ss[2]=l[2];this.#ss[3]=l[3]}else{this.#ss[0]=this.#ss[1]=1/0;this.#ss[2]=this.#ss[3]=-1/0}return this}recordBBox(t,e,i,s,n,r){const a=this.#ss;if(a[0]===1/0)return this;const o=Util.multiplyByDOMMatrix(this.#is.at(-1),e.getTransform());if(a[0]===-1/0){Util.axialAlignedBoundingBox([i,n,s,r],o,this.#ns);return this}const l=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,n,s,r],o,l);this.#ns[0]=Math.min(this.#ns[0],Math.max(l[0],a[0]));this.#ns[1]=Math.min(this.#ns[1],Math.max(l[1],a[1]));this.#ns[2]=Math.max(this.#ns[2],Math.min(l[2],a[2]));this.#ns[3]=Math.max(this.#ns[3],Math.min(l[3],a[3]));return this}recordCharacterBBox(t,e,i,s=1,n=0,r=0,a){const o=i.bbox;let l,h;if(o){l=o[2]!==o[0]&&o[3]!==o[1]&&this.#ls.get(i);if(!1!==l){h=[0,0,0,0];Util.axialAlignedBoundingBox(o,i.fontMatrix,h);1===s&&0===n&&0===r||Util.scaleMinMax([s,0,0,-s,n,r],h);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}}if(!a)return this.recordFullPageBBox(t);const d=a();if(o&&h&&void 0===l){l=h[0]<=n-d.actualBoundingBoxLeft&&h[2]>=n+d.actualBoundingBoxRight&&h[1]<=r-d.actualBoundingBoxAscent&&h[3]>=r+d.actualBoundingBoxDescent;this.#ls.set(i,l);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}return this.recordBBox(t,e,n-d.actualBoundingBoxLeft,n+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(t){this.#ns[0]=Math.max(0,this.#ss[0]);this.#ns[1]=Math.max(0,this.#ss[1]);this.#ns[2]=Math.min(this.#hs,this.#ss[2]);this.#ns[3]=Math.min(this.#ds,this.#ss[3]);return this}getSimpleIndex(t){return this.#Qi[t]}recordDependencies(t,e){const i=this.#as,s=this.#Qi,n=this.#Ji;for(const t of e)t in this.#Qi?i.add(s[t]):t in n&&n[t].forEach(i.add,i);return this}recordNamedDependency(t,e){this.#Zi.has(e)&&this.#as.add(this.#Zi.get(e));return this}recordOperation(t,e=!1){this.recordDependencies(t,[at]);if(this.#us){const e=ensureDebugMetadata(this.#us,t),{dependencies:i}=e;this.#as.forEach(i.add,i);this.#ts.forEach(i.add,i);this.#es.forEach(i.add,i);i.delete(t);e.isRenderingOperation=!0}if(this.#rs===t){const i=ot(256*this.#ns[0]/this.#hs),s=ot(256*this.#ns[1]/this.#ds),n=lt(256*this.#ns[2]/this.#hs),r=lt(256*this.#ns[3]/this.#ds);expandBBox(this.#cs,t,i,s,n,r);for(const e of this.#as)e!==t&&expandBBox(this.#cs,e,i,s,n,r);for(const e of this.#ts)e!==t&&expandBBox(this.#cs,e,i,s,n,r);for(const e of this.#es)e!==t&&expandBBox(this.#cs,e,i,s,n,r);if(!e){this.#as.clear();this.#rs=-1}}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#as);this.recordOperation(t,e);this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){if(this.#rs===t){this.#rs=-1;this.#ss[0]=Math.max(this.#ss[0],this.#ns[0]);this.#ss[1]=Math.max(this.#ss[1],this.#ns[1]);this.#ss[2]=Math.min(this.#ss[2],this.#ns[2]);this.#ss[3]=Math.min(this.#ss[3],this.#ns[3]);e||this.#as.clear()}return this}_takePendingDependencies(){const t=this.#as;this.#as=new Set;return t}_extractOperation(t){const e=this.#os.get(t);this.#os.delete(t);return e}_pushPendingDependencies(t){for(const e of t)this.#as.add(e)}take(){this.#ls.clear();return new BBoxReader(this.#Ki,this.#cs)}takeDebugMetadata(){return this.#us}}class CanvasNestedDependencyTracker{#gs;#ms;#fs;#bs=0;#ws=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#fs===!!i)return t;this.#gs=t;this.#ms=e;this.#fs=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){this.#ws++;this.#gs.save(this.#ms);return this}restore(t){if(this.#ws>0){this.#gs.restore(this.#ms);this.#ws--}return this}recordOpenMarker(t){this.#bs++;return this}getOpenMarker(){return this.#bs>0?this.#ms:this.#gs.getOpenMarker()}recordCloseMarker(t){this.#bs--;return this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){this.#gs.pushBaseTransform(t);return this}popBaseTransform(){this.#gs.popBaseTransform();return this}recordSimpleData(t,e){this.#gs.recordSimpleData(t,this.#ms);return this}recordIncrementalData(t,e){this.#gs.recordIncrementalData(t,this.#ms);return this}resetIncrementalData(t,e){this.#gs.resetIncrementalData(t,this.#ms);return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){this.#gs.recordSimpleDataFromNamed(t,e,this.#ms);return this}recordFutureForcedDependency(t,e){this.#gs.recordFutureForcedDependency(t,this.#ms);return this}inheritSimpleDataAsFutureForcedDependencies(t){this.#gs.inheritSimpleDataAsFutureForcedDependencies(t);return this}inheritPendingDependenciesAsFutureForcedDependencies(){this.#gs.inheritPendingDependenciesAsFutureForcedDependencies();return this}resetBBox(t){this.#fs||this.#gs.resetBBox(this.#ms);return this}recordClipBox(t,e,i,s,n,r){this.#fs||this.#gs.recordClipBox(this.#ms,e,i,s,n,r);return this}recordBBox(t,e,i,s,n,r){this.#fs||this.#gs.recordBBox(this.#ms,e,i,s,n,r);return this}recordCharacterBBox(t,e,i,s,n,r,a){this.#fs||this.#gs.recordCharacterBBox(this.#ms,e,i,s,n,r,a);return this}recordFullPageBBox(t){this.#fs||this.#gs.recordFullPageBBox(this.#ms);return this}getSimpleIndex(t){return this.#gs.getSimpleIndex(t)}recordDependencies(t,e){this.#gs.recordDependencies(this.#ms,e);return this}recordNamedDependency(t,e){this.#gs.recordNamedDependency(this.#ms,e);return this}recordOperation(t){this.#gs.recordOperation(this.#ms,!0);return this}recordShowTextOperation(t){this.#gs.recordShowTextOperation(this.#ms,!0);return this}bboxToClipBoxDropOperation(t){this.#fs||this.#gs.bboxToClipBoxDropOperation(this.#ms,!0);return this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const dt=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],ct=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],ut=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],pt=["filter","fillColor","fillAlpha"],gt=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],mt=["transform"],ft=["transform","fillColor"],bt="Fill",wt="Stroke",yt="Shading";function applyBoundingBox(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 BaseShadingPattern{isModifyingCurrentTransform(){return!1}getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===wt||s===bt){const r=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",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(-r[0],-r[1]);i=Util.transform(i,[1,0,0,1,r[0],r[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);n.setTransform(d)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,r,a,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=r;r=a;a=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=a;a=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=r;r=a;a=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[s]+e.offsetX)*e.scaleX,f=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,w=(l[n+1]+e.offsetY)*e.scaleY;if(g>=w)return;const y=h[r],A=h[r+1],v=h[r+2],x=h[a],E=h[a+1],C=h[a+2],_=h[o],S=h[o+1],T=h[o+2],D=Math.round(g),M=Math.round(w);let k,P,I,F,R,L,B,O;for(let t=D;t<=M;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);k=p-(p-m)*e;P=y-(y-x)*e;I=A-(A-E)*e;F=v-(v-C)*e}else{let e;e=t>w?1:f===w?0:(f-t)/(f-w);k=m-(m-b)*e;P=x-(x-_)*e;I=E-(E-S)*e;F=C-(C-T)*e}let e;e=t<g?0:t>w?1:(g-t)/(g-w);R=p-(p-b)*e;L=y-(y-_)*e;B=A-(A-S)*e;O=v-(v-T)*e;const i=Math.round(Math.min(k,R)),s=Math.round(Math.max(k,R));let n=c*t+4*i;for(let t=i;t<=s;t++){e=(k-t)/(k-R);e<0?e=0:e>1&&(e=1);d[n++]=P-(P-L)*e|0;d[n++]=I-(I-B)*e|0;d[n++]=F-(F-O)*e|0;d[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let r,a;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(r=0;r<l;r++){let e=r*o;for(let r=0;r<h;r++,e++){drawTriangle(t,i,s[e],s[e+1],s[e+o],n[e],n[e+1],n[e+o]);drawTriangle(t,i,s[e+o+1],s[e+1],s[e+o],n[e+o+1],n[e+1],n[e+o])}}break;case"triangles":for(r=0,a=s.length;r<a;r+=3)drawTriangle(t,i,s[r],s[r+1],s[r+2],n[r],n[r+1],n[r+2]);break;default:throw new Error("illegal figure")}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._coords=t[2];this._colors=t[3];this._figures=t[4];this._bounds=t[5];this._bbox=t[6];this._background=t[7];this.matrix=null}_createMeshCanvas(t,e,i){const s=Math.floor(this._bounds[0]),n=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-s,a=Math.ceil(this._bounds[3])-n,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(a*t[1]*1.1)),3e3),h=r/o,d=a/l,c={coords:this._coords,colors:this._colors,offsetX:-s,offsetY:-n,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,s=t.length;i<s;i+=4){t[i]=e[0];t[i+1]=e[1];t[i+2]=e[2];t[i+3]=255}}for(const t of this._figures)drawFigure(f,t,c);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:s-2*h,offsetY:n-2*d,scaleX:h,scaleY:d}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,s){applyBoundingBox(t,this._bbox);const n=new Float32Array(2);if(s===yt)Util.singularValueDecompose2dScale(getCurrentTransform(t),n);else if(this.matrix){Util.singularValueDecompose2dScale(this.matrix,n);const[t,i]=n;Util.singularValueDecompose2dScale(e.baseTransform,n);n[0]*=t;n[1]*=i}else Util.singularValueDecompose2dScale(e.baseTransform,n);const r=this._createMeshCanvas(n,s===yt?null:this._background,e.cachedCanvases);if(s!==yt){t.setTransform(...e.baseTransform);this.matrix&&t.transform(...this.matrix)}t.translate(r.offsetX,r.offsetY);t.scale(r.scaleX,r.scaleY);return t.createPattern(r.canvas,"no-repeat")}}class DummyShadingPattern extends BaseShadingPattern{getPattern(){return"hotpink"}}const At=1,vt=2;class TilingPattern{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.ctx=e;this.canvasGraphicsFactory=i;this.baseTransform=s}createPatternCanvas(t,e){const{bbox:i,operatorList:s,paintType:n,tilingType:r,color:a,canvasGraphicsFactory:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l);h=Math.abs(h);info("TilingType: "+r);const d=i[0],c=i[1],u=i[2],p=i[3],g=u-d,m=p-c,f=new Float32Array(2);Util.singularValueDecompose2dScale(this.matrix,f);const[b,w]=f;Util.singularValueDecompose2dScale(this.baseTransform,f);const y=b*f[0],A=w*f[1];let v=g,x=m,E=!1,C=!1;const _=Math.ceil(l*y),S=Math.ceil(h*A);_>=Math.ceil(g*y)?v=l:E=!0;S>=Math.ceil(m*A)?x=h:C=!0;const T=this.getSizeAndScale(v,this.ctx.canvas.width,y),D=this.getSizeAndScale(x,this.ctx.canvas.height,A),M=t.cachedCanvases.getCanvas("pattern",T.size,D.size),k=M.context,P=o.createCanvasGraphics(k,e);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,n,a);k.translate(-T.scale*d,-D.scale*c);P.transform(0,T.scale,0,0,D.scale,0,0);k.save();P.dependencyTracker?.save();this.clipBbox(P,d,c,u,p);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(s);P.endDrawing();P.dependencyTracker?.restore();k.restore();if(E||C){const e=M.canvas;E&&(v=l);C&&(x=h);const i=this.getSizeAndScale(v,this.ctx.canvas.width,y),s=this.getSizeAndScale(x,this.ctx.canvas.height,A),n=i.size,r=s.size,a=t.cachedCanvases.getCanvas("pattern-workaround",n,r),o=a.context,u=E?Math.floor(g/l):0,p=C?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,n*t,r*i,n,r,0,0,n,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:d,offsetY:c}}return{canvas:M.canvas,scaleX:T.scale,scaleY:D.scale,offsetX:d,offsetY:c}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const r=s-e,a=n-i;t.ctx.rect(e,i,r,a);Util.axialAlignedBoundingBox([e,i,s,n],getCurrentTransform(t.ctx),t.current.minMax);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case At:const{fillStyle:t,strokeStyle:r}=this.ctx;s.fillStyle=n.fillColor=t;s.strokeStyle=n.strokeColor=r;break;case vt:s.fillStyle=s.strokeStyle=i;n.fillColor=n.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,s,n){let r=i;if(s!==yt){r=Util.transform(r,e.baseTransform);this.matrix&&(r=Util.transform(r,this.matrix))}const a=this.createPatternCanvas(e,n);let o=new DOMMatrix(r);o=o.translate(a.offsetX,a.offsetY);o=o.scale(1/a.scaleX,1/a.scaleY);const l=t.createPattern(a.canvas,"repeat");l.setTransform(o);return l}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],d=s>>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s<n;s++){for(const s=e+d;e<s;e++){const s=e<u?t[e]:255;i[p++]=128&s?h:l;i[p++]=64&s?h:l;i[p++]=32&s?h:l;i[p++]=16&s?h:l;i[p++]=8&s?h:l;i[p++]=4&s?h:l;i[p++]=2&s?h:l;i[p++]=1&s?h:l}if(0===c)continue;const s=e<u?t[e++]:255;for(let t=0;t<c;t++)i[p++]=s&1<<7-t?h:l}return{srcPos:e,destPos:p}}const xt=16,Et=new DOMMatrix,Ct=new Float32Array(2),_t=new Float32Array([1/0,1/0,-1/0,-1/0]);class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,i){let s;if(void 0!==this.cache[t]){s=this.cache[t];this.canvasFactory.reset(s,e,i)}else{s=this.canvasFactory.create(e,i);this.cache[t]=s}return s}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,i,s,n,r,a,o,l,h){const[d,c,u,p,g,m]=getCurrentTransform(t);if(0===c&&0===u){const f=a*d+g,b=Math.round(f),w=o*p+m,y=Math.round(w),A=(a+l)*d+g,v=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(Math.sign(d),0,0,Math.sign(p),b,y);t.drawImage(e,i,s,n,r,0,0,v,E);t.setTransform(d,c,u,p,g,m);return[v,E]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),w=a*c+m,y=Math.round(w),A=(o+h)*u+g,v=Math.abs(Math.round(A)-b)||1,x=(a+l)*c+m,E=Math.abs(Math.round(x)-y)||1;t.setTransform(0,Math.sign(c),Math.sign(u),0,b,y);t.drawImage(e,i,s,n,r,0,0,E,v);t.setTransform(d,c,u,p,g,m);return[E,v]}t.drawImage(e,i,s,n,r,a,o,l,h);return[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}class CanvasExtraState{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=e;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=f;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this);this.clipBox=new Float32Array([0,0,t,e]);this.minMax=_t.slice()}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();t.minMax=this.minMax.slice();return t}getPathBoundingBox(t=bt,e=null){const i=this.minMax.slice();if(t===wt){e||unreachable("Stroke bounding box must include transform.");Util.singularValueDecompose2dScale(e,Ct);const t=Ct[0]*this.lineWidth/2,s=Ct[1]*this.lineWidth/2;i[0]-=t;i[1]-=s;i[2]+=t;i[3]+=s}return i}updateClipFromPath(){const t=Util.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(_t,0)}getClippedPathBoundingBox(t=bt,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}const i=e.height,s=e.width,n=i%xt,r=(i-n)/xt,a=0===n?r:r+1,o=t.createImageData(s,xt);let l,h=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===x.GRAYSCALE_1BPP){const e=d.byteLength,i=new Uint32Array(c.buffer,0,c.byteLength>>2),m=i.length,f=s+7>>3,b=4294967295,w=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;u<a;u++){g=u<r?xt:n;l=0;for(p=0;p<g;p++){const t=e-h;let n=0;const r=t>f?s:8*t-7,a=-8&r;let o=0,c=0;for(;n<a;n+=8){c=d[h++];i[l++]=128&c?b:w;i[l++]=64&c?b:w;i[l++]=32&c?b:w;i[l++]=16&c?b:w;i[l++]=8&c?b:w;i[l++]=4&c?b:w;i[l++]=2&c?b:w;i[l++]=1&c?b:w}for(;n<r;n++){if(0===o){c=d[h++];o=128}i[l++]=c&o?b:w;o>>=1}}for(;l<m;)i[l++]=0;t.putImageData(o,0,u*xt)}}else if(e.kind===x.RGBA_32BPP){p=0;m=s*xt*4;for(u=0;u<r;u++){c.set(d.subarray(h,h+m));h+=m;t.putImageData(o,0,p);p+=xt}if(u<a){m=s*n*4;c.set(d.subarray(h,h+m));t.putImageData(o,0,p)}}else{if(e.kind!==x.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);g=xt;m=s*g;for(u=0;u<a;u++){if(u>=r){g=n;m=s*g}l=0;for(p=m;p--;){c[l++]=d[h++];c[l++]=d[h++];c[l++]=d[h++];c[l++]=255}t.putImageData(o,0,u*xt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%xt,r=(i-n)/xt,a=0===n?r:r+1,o=t.createImageData(s,xt);let l=0;const h=e.data,d=o.data;for(let e=0;e<a;e++){const i=e<r?xt:n;({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:d,width:s,height:i,nonBlackColor:0}));t.putImageData(o,0,e*xt)}}function copyCtxState(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]);if(void 0!==t.setLineDash){e.setLineDash(t.getLineDash());e.lineDashOffset=t.lineDashOffset}}function resetCtxToDefault(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";if(void 0!==t.setLineDash){t.setLineDash([]);t.lineDashOffset=0}const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function getImageSmoothingEnabled(t,e){if(e)return!0;Util.singularValueDecompose2dScale(t,Ct);const i=Math.fround(OutputScale.pixelRatio*PixelsPerInch.PDF_TO_CSS_UNITS);return Ct[0]<=i&&Ct[1]<=i}const St=["butt","round","square"],Tt=["miter","round","bevel"],Dt={},Mt={};class CanvasGraphics{constructor(t,e,i,s,n,{optionalContentConfig:r,markedContentStack:a=null},o,l,h){this.ctx=t;this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.stateStack=[];this.pendingClip=null;this.pendingEOFill=!1;this.res=null;this.xobjs=null;this.commonObjs=e;this.objs=i;this.canvasFactory=s;this.filterFactory=n;this.groupStack=[];this.baseTransform=null;this.baseTransformStack=[];this.groupLevel=0;this.smaskStack=[];this.smaskCounter=0;this.tempSMask=null;this.suspendedCtx=null;this.contentVisible=!0;this.markedContentStack=a||[];this.optionalContentConfig=r;this.cachedCanvases=new CachedCanvases(this.canvasFactory);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}getObject(t,e,i=null){if("string"==typeof e){this.dependencyTracker?.recordNamedDependency(t,e);return e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)}return i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:s=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;this.ctx.fillStyle=s||"#ffffff";this.ctx.fillRect(0,0,n,r);this.ctx.fillStyle=a;if(i){const t=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx;this.transparentCanvas=t.canvas;this.ctx=t.context;this.ctx.save();this.ctx.transform(...getCurrentTransform(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[0]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=getCurrentTransform(this.ctx)}executeOperatorList(t,e,i,s,n){const r=t.argsArray,a=t.fnArray;let o=e||0;const l=r.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,d=h?Date.now()+15:0;let c=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==s&&o===s.nextBreakPoint){s.breakIt(o,i);return o}if(!n||n(o)){g=a[o];m=r[o]??null;if(g!==k.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)){e.get(t,i);return o}}}o++;if(o===l)return o;if(h&&++c>10){if(Date.now()>d){i();return o}c=0}}}#ys(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#ys();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#As()}#As(){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;let n,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,d="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;if(a>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);a/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(d,e,i);r=n.context;r.clearRect(0,0,e,i);r.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:s,height:n}=e,r=this.current.fillColor,a=this.current.patternFill,o=getCurrentTransform(i);let l,h,d,c;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(a?o:[o.slice(0,4),r]);l=this._cachedBitmapsMap.get(i);if(!l){l=new Map;this._cachedBitmapsMap.set(i,l)}const s=l.get(h);if(s&&!a){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);this.dependencyTracker?.recordDependencies(t,ft);return{canvas:s,offsetX:e,offsetY:i}}d=s}if(!d){c=this.cachedCanvases.getCanvas("maskCanvas",s,n);putBinaryImageMask(c.context,e)}let u=Util.transform(o,[1/s,0,0,-1/n,0,0]);u=Util.transform(u,[1,0,0,1,0,-n]);const p=_t.slice();Util.axialAlignedBoundingBox([0,0,s,n],u,p);const[g,m,f,b]=p,w=Math.round(f-g)||1,y=Math.round(b-m)||1,A=this.cachedCanvases.getCanvas("fillCanvas",w,y),v=A.context,x=g,E=m;v.translate(-x,-E);v.transform(...u);if(!d){d=this._scaleImage(c.canvas,getCurrentTransformInverse(v));d=d.img;l&&a&&l.set(h,d)}v.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(v),e.interpolate);drawImageAtIntegerCoords(v,d,0,0,d.width,d.height,0,0,s,n);v.globalCompositeOperation="source-in";const C=Util.transform(getCurrentTransformInverse(v),[1,0,0,1,-x,-E]);v.fillStyle=a?r.getPattern(i,this,C,bt,t):r;v.fillRect(0,0,s,n);if(l&&!a){this.cachedCanvases.delete("fillCanvas");l.set(h,A.canvas)}this.dependencyTracker?.recordDependencies(t,ft);return{canvas:A.canvas,offsetX:Math.round(x),offsetY:Math.round(E)}}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=St[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t);this.ctx.lineJoin=Tt[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;if(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.tempSMask=null;this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t);this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,n=this.cachedCanvases.getCanvas(s,e,i);this.suspendedCtx=this.ctx;const r=this.ctx=n.context;r.setTransform(this.suspendedCtx.getTransform());copyCtxState(this.suspendedCtx,r);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function(){e.save();this.__originalSave()};t.restore=function(){e.restore();this.__originalRestore()};t.translate=function(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function(t,i,s,n,r,a){e.transform(t,i,s,n,r,a);this.__originalTransform(t,i,s,n,r,a)};t.setTransform=function(t,i,s,n,r,a){e.setTransform(t,i,s,n,r,a);this.__originalSetTransform(t,i,s,n,r,a)};t.resetTransform=function(){e.resetTransform();this.__originalResetTransform()};t.rotate=function(t){e.rotate(t);this.__originalRotate(t)};t.clip=function(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,r,a){e.bezierCurveTo(t,i,s,n,r,a);this.__originalBezierCurveTo(t,i,s,n,r,a)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(r,this.suspendedCtx);this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],r=s[1],a=s[2]-n,o=s[3]-r;if(0!==a&&0!==o){this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,r,a,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(r)if(u<0||p<0||u+i>c.width||p+s>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),e=t.context;e.drawImage(c,-u,-p);e.globalCompositeOperation="destination-atop";e.fillStyle=r;e.fillRect(0,0,i,s);e.globalCompositeOperation="source-over";c=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,s);t.clip(e);t.globalCompositeOperation="destination-atop";t.fillStyle=r;t.fillRect(u,p,i,s);t.restore()}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(c,u,p,i,s,o,l,i,s);e.restore()}save(t){this.inSMaskMode&©CtxState(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);if(0!==this.stateStack.length){this.current=this.stateStack.pop();this.ctx.restore();this.inSMaskMode&©CtxState(this.suspendedCtx,this.ctx);this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}else this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,s,n,r,a){this.dependencyTracker?.recordIncrementalData("transform",t);this.ctx.transform(e,i,s,n,r,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,s){let[n]=i;if(s){if(null!==this.dependencyTracker){const i=e===k.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"])}if(!(n instanceof Path2D)){const t=i[0]=new Path2D;for(let e=0,i=n.length;e<i;)switch(n[e++]){case P:t.moveTo(n[e++],n[e++]);break;case I:t.lineTo(n[e++],n[e++]);break;case F:t.bezierCurveTo(n[e++],n[e++],n[e++],n[e++],n[e++],n[e++]);break;case R:t.closePath();break;default:warn(`Unrecognized drawing path operator: ${n[e-1]}`)}n=t}Util.axialAlignedBoundingBox(s,getCurrentTransform(this.ctx),this.current.minMax);this[e](t,n);this._pathStartIdx=t}else{n||=i[0]=new Path2D;this[e](t,n)}}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const s=this.ctx,n=this.current.strokeColor;s.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof n&&n?.getPattern){const i=n.isModifyingCurrentTransform()?s.getTransform():null;s.save();s.strokeStyle=n.getPattern(s,this,getCurrentTransformInverse(s),wt,t);if(i){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(i));e=t}this.rescaleAndStroke(e,!1);s.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,dt);i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(wt,getCurrentTransform(this.ctx)));s.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const s=this.ctx,n=this.current.fillColor;let r=!1;if(this.current.patternFill){const i=n.isModifyingCurrentTransform()?s.getTransform():null;this.dependencyTracker?.save(t);s.save();s.fillStyle=n.getPattern(s,this,getCurrentTransformInverse(s),bt,t);if(i){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(i));e=t}r=!0}const a=this.current.getClippedPathBoundingBox();if(this.contentVisible&&null!==a)if(this.pendingEOFill){s.fill(e,"evenodd");this.pendingEOFill=!1}else s.fill(e);this.dependencyTracker?.recordDependencies(t,ct);if(r){s.restore();this.dependencyTracker?.restore(t)}i&&this.consumePath(t,e,a)}eoFill(t,e){this.pendingEOFill=!0;this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1);this.stroke(t,e,!1);this.consumePath(t,e)}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){this.ctx.fill(e);this.dependencyTracker?.recordDependencies(t,pt).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=Dt}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=Mt}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:r,fontSize:a,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(s).translate(n,r).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,i,s){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",i,t);const n=this.commonObjs.get(i),r=this.current;if(!n)throw new Error(`Can't find font for ${i}`);r.fontMatrix=n.fontMatrix||e;0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||warn("Invalid font matrix for font "+i);if(s<0){s=-s;r.fontDirection=-1}else r.fontDirection=1;this.current.font=n;this.current.fontSize=s;if(n.isType3Font)return;const a=n.loadedName||"sans-serif",o=n.systemFontInfo?.css||`"${a}", ${n.fallbackName}`;let l="normal";n.black?l="900":n.bold&&(l="bold");const h=n.italic?"italic":"normal";let d=s;s<16?d=16:s>100&&(d=100);this.current.fontSizeScale=s/d;this.ctx.font=`${h} ${l} ${d}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?.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)}#vs(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n,r){const a=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,d=o.fontSize/o.fontSizeScale,c=h&A,u=!!(h&v),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;(l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e));if(m&&(l.disableFontFace||p||g)){a.save();a.translate(i,s);a.scale(d,-d);this.dependencyTracker?.recordCharacterBBox(t,a,l);let e;if(c===f||c===w)if(n){e=a.getTransform();a.setTransform(...n);const t=this.#vs(m,e,n);a.fill(t)}else a.fill(m);if(c===b||c===w)if(r){e||=a.getTransform();a.setTransform(...r);const{a:t,b:i,c:s,d:n}=e,o=Util.inverseTransform(r),l=Util.transform([t,i,s,n,0,0],o);Util.singularValueDecompose2dScale(l,Ct);a.lineWidth*=Math.max(Ct[0],Ct[1])/d;a.stroke(this.#vs(m,e,r))}else{a.lineWidth/=d;a.stroke(m)}a.restore()}else{if(c===f||c===w){a.fillText(e,i,s);this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s,()=>a.measureText(e))}if(c===b||c===w){this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s,()=>a.measureText(e)).recordDependencies(t,dt);a.strokeText(e,i,s)}}if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(a),x:i,y:s,fontSize:d,path:m});this.dependencyTracker?.recordCharacterBBox(t,a,l,d,i,s)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t,e){if(this.dependencyTracker){this.dependencyTracker.recordDependencies(t,gt).resetBBox(t);this.current.textRenderingMode&v&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies()}const i=this.current,s=i.font;if(s.isType3Font){this.showType3Text(t,e);this.dependencyTracker?.recordShowTextOperation(t);return}const n=i.fontSize;if(0===n){this.dependencyTracker?.recordOperation(t);return}const r=this.ctx,a=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,d=i.textHScale*h,c=e.length,u=s.vertical,p=u?1:-1,g=s.defaultVMetrics,m=n*i.fontMatrix[0],y=i.textRenderingMode===f&&!s.disableFontFace&&!i.patternFill;r.save();i.textMatrix&&r.transform(...i.textMatrix);r.translate(i.x,i.y+i.textRise);h>0?r.scale(d,-1):r.scale(d,1);let x,E;if(i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,getCurrentTransformInverse(r),bt,t);x=getCurrentTransform(r);r.restore();r.fillStyle=e}if(i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,getCurrentTransformInverse(r),wt,t);E=getCurrentTransform(r);r.restore();r.strokeStyle=e}let C=i.lineWidth;const _=i.textMatrixScale;if(0===_||0===C){const t=i.textRenderingMode&A;t!==b&&t!==w||(C=this.getSinglePixelWidth())}else C/=_;if(1!==a){r.scale(a,a);C/=a}r.lineWidth=C;if(s.isInvalidPDFjsFont){const s=[];let n=0;for(const t of e){s.push(t.unicode);n+=t.width}const a=s.join("");r.fillText(a,0,0);if(null!==this.dependencyTracker){const e=r.measureText(a);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}i.x+=n*m*d;r.restore();this.compose();return}let S,T=0;for(S=0;S<c;++S){const i=e[S];if("number"==typeof i){T+=p*i*n/1e3;continue}let d=!1;const c=(i.isSpace?l:0)+o,f=i.fontChar,b=i.accent;let w,A,v,C=i.width;if(u){const t=i.vmetric||g,e=-(i.vmetric?t[1]:.5*C)*m,s=t[2]*m;C=t?-t[0]:C;w=e/a;A=(T+s)/a}else{w=T/a;A=0}if(s.remeasure&&C>0){v=r.measureText(f);const t=1e3*v.width/n*a;if(C<t&&this.isFontSubpixelAAEnabled){const e=C/t;d=!0;r.save();r.scale(e,1);w/=e}else C!==t&&(w+=(C-t)/2e3*n/a)}if(this.contentVisible&&(i.isInFont||s.missingFile))if(y&&!b){r.fillText(f,w,A);this.dependencyTracker?.recordCharacterBBox(t,r,v?{bbox:null}:s,n/a,w,A,()=>v??r.measureText(f))}else{this.paintChar(t,f,w,A,x,E);if(b){const e=w+n*b.offset.x/a,i=A-n*b.offset.y/a;this.paintChar(t,b.fontChar,e,i,x,E)}}T+=u?C*m-c*h:C*m+c*h;d&&r.restore()}u?i.y-=T:i.x+=T*d;r.restore();this.compose();this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,i){const s=this.ctx,n=this.current,r=n.font,a=n.fontSize,o=n.fontDirection,l=r.vertical?1:-1,h=n.charSpacing,d=n.wordSpacing,c=n.textHScale*o,u=n.fontMatrix||e,p=i.length;let g,m,f,b;if(n.textRenderingMode===y||0===a)return;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;s.save();n.textMatrix&&s.transform(...n.textMatrix);s.translate(n.x,n.y+n.textRise);s.scale(c,o);const w=this.dependencyTracker;this.dependencyTracker=w?new CanvasNestedDependencyTracker(w,t):null;for(g=0;g<p;++g){m=i[g];if("number"==typeof m){b=l*m*a/1e3;this.ctx.translate(b,0);n.x+=b*c;continue}const t=(m.isSpace?d:0)+h,e=r.charProcOperatorList[m.operatorListId];if(e){if(this.contentVisible){this.save();s.scale(a,a);s.transform(...u);this.executeOperatorList(e);this.restore()}}else warn(`Type3 character "${m.operatorListId}" is not available.`);const o=[m.width,0];Util.applyTransform(o,u);f=o[0]*a+t;s.translate(f,0);n.x+=f*c}s.restore();w&&(this.dependencyTracker=w)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,s,n,r,a){const o=new Path2D;o.rect(s,n,r-s,a-n);this.ctx.clip(o);this.dependencyTracker?.recordBBox(t,this.ctx,s,r,n,a).recordClipBox(t,this.ctx,s,r,n,a);this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||getCurrentTransform(this.ctx),s={createCanvasGraphics:(t,e)=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new CanvasNestedDependencyTracker(this.dependencyTracker,e,!0):null)};i=new TilingPattern(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);this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0}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}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e,i=null){let s;if(this.cachedPatterns.has(e))s=this.cachedPatterns.get(e);else{s=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e));this.cachedPatterns.set(e,s)}i&&(s.matrix=i);return s}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const s=this._getPattern(t,e);i.fillStyle=s.getPattern(i,this,getCurrentTransformInverse(i),yt,t);const n=getCurrentTransformInverse(i);if(n){const{width:t,height:e}=i.canvas,s=_t.slice();Util.axialAlignedBoundingBox([0,0,t,e],n,s);const[r,a,o,l]=s;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,mt).recordDependencies(t,ct).recordOperation(t);this.compose(this.current.getClippedPathBoundingBox());this.restore(t)}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("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=getCurrentTransform(this.ctx);if(i){Util.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,s,n,r]=i,a=new Path2D;a.rect(e,s,n-e,r-s);this.ctx.clip(a);this.dependencyTracker?.recordClipBox(t,this.ctx,e,n,s,r);this.endPath(t)}}}paintFormXObjectEnd(t){if(this.contentVisible){this.restore(t);this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const i=this.ctx;e.isolated||info("TODO: Support non-isolated groups.");e.knockout&&warn("Knockout groups not supported.");const s=getCurrentTransform(i);e.matrix&&i.transform(...e.matrix);if(!e.bbox)throw new Error("Bounding box is required.");let n=_t.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(i),n);const r=[0,0,i.canvas.width,i.canvas.height];n=Util.intersect(n,r)||[0,0,0,0];const a=Math.floor(n[0]),o=Math.floor(n[1]),l=Math.max(Math.ceil(n[2])-a,1),h=Math.max(Math.ceil(n[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let d="groupAt"+this.groupLevel;e.smask&&(d+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(d,l,h),u=c.context;u.translate(-a,-o);u.transform(...s);let p=new Path2D;const[g,m,f,b]=e.bbox;p.rect(g,m,f-g,b-m);if(e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix));p=t}u.clip(p);e.smask&&this.smaskStack.push({canvas:c.canvas,context:u,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null});if(!e.smask||this.dependencyTracker){i.setTransform(1,0,0,1,0,0);i.translate(a,o);i.save()}copyCtxState(i,u);this.ctx=u;this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i);this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(i);this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,s=this.groupStack.pop();this.ctx=s;this.ctx.imageSmoothingEnabled=!1;this.dependencyTracker?.popBaseTransform();if(e.smask){this.tempSMask=this.smaskStack.pop();this.restore(t);this.dependencyTracker&&this.ctx.restore()}else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t);this.ctx.save();this.ctx.setTransform(...e);const s=_t.slice();Util.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,s);this.ctx.drawImage(i.canvas,0,0);this.ctx.restore();this.compose(s)}}beginAnnotation(t,e,i,s,n,r){this.#ys();resetCtxToDefault(this.ctx);this.ctx.save();this.save(t);this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(i){const n=i[2]-i[0],a=i[3]-i[1];if(r&&this.annotationCanvasMap){(s=s.slice())[4]-=i[0];s[5]-=i[1];(i=i.slice())[0]=i[1]=0;i[2]=n;i[3]=a;Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),Ct);const{viewportScale:t}=this,r=Math.ceil(n*this.outputScaleX*t),o=Math.ceil(a*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(r,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(Ct[0],0,0,-Ct[1],0,a*Ct[1]);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],n,a);this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(t,...s);this.transform(t,...n)}endAnnotation(t){if(this.annotationCanvas){this.ctx.restore();this.#As();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const s=this.ctx,n=this._createMaskCanvas(t,e),r=n.canvas;s.save();s.setTransform(1,0,0,1,0,0);s.drawImage(r,n.offsetX,n.offsetY);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,n.offsetX,n.offsetX+r.width,n.offsetY,n.offsetY+r.height).recordOperation(t);s.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i,s=0,n=0,r,a){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=getCurrentTransform(o);o.transform(i,s,n,r,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]);this.dependencyTracker?.resetBBox(t);for(let e=0,d=a.length;e<d;e+=2){const d=Util.transform(l,[i,s,n,r,a[e],a[e+1]]);o.drawImage(h.canvas,d[4],d[5]);this.dependencyTracker?.recordBBox(t,this.ctx,d[4],d[4]+h.canvas.width,d[5],d[5]+h.canvas.height)}o.restore();this.compose();this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx,s=this.current.fillColor,n=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,ft);for(const r of e){const{data:e,width:a,height:o,transform:l}=r,h=this.cachedCanvases.getCanvas("maskCanvas",a,o),d=h.context;d.save();putBinaryImageMask(d,this.getObject(t,e,r));d.globalCompositeOperation="source-in";d.fillStyle=n?s.getPattern(d,this,getCurrentTransformInverse(i),bt,t):s;d.fillRect(0,0,a,o);d.restore();i.save();i.transform(...l);i.scale(1,-1);drawImageAtIntegerCoords(i,h.canvas,0,0,a,o,0,-1,1,1);this.dependencyTracker?.recordBBox(t,i,0,a,0,o);i.restore()}this.compose();this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):warn("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,s,n){if(!this.contentVisible)return;const r=this.getObject(t,e);if(!r){warn("Dependent image isn't ready yet");return}const a=r.width,o=r.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:a,h:o});this.paintInlineImageXObjectGroup(t,r,l)}applyTransferMapsToCanvas(t){if("none"!==this.current.transferMaps){t.filter=this.current.transferMaps;t.drawImage(t.canvas,0,0);t.filter="none"}return t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:s}=t,n=this.cachedCanvases.getCanvas("inlineImage",i,s),r=n.context;r.filter=this.current.transferMaps;r.drawImage(e,0,0);r.filter="none";return n.canvas}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,s=e.height,n=this.ctx;this.save(t);const{filter:r}=n;"none"!==r&&""!==r&&(n.filter="none");n.scale(1/i,-1/s);let a;if(e.bitmap)a=this.applyTransferMapsToBitmap(e);else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)a=e;else{const t=this.cachedCanvases.getCanvas("inlineImage",i,s).context;putBinaryImageData(t,e);a=this.applyTransferMapsToCanvas(t)}const o=this._scaleImage(a,getCurrentTransformInverse(n));n.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(n),e.interpolate);this.dependencyTracker?.resetBBox(t).recordBBox(t,n,0,i,-s,0).recordDependencies(t,ut).recordOperation(t);drawImageAtIntegerCoords(n,o.img,0,0,o.paintWidth,o.paintHeight,0,-s,i,s);this.compose();this.restore(t)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const s=this.ctx;let n;if(e.bitmap)n=e.bitmap;else{const t=e.width,i=e.height,s=this.cachedCanvases.getCanvas("inlineImage",t,i).context;putBinaryImageData(s,e);n=this.applyTransferMapsToCanvas(s)}this.dependencyTracker?.resetBBox(t);for(const e of i){s.save();s.transform(...e.transform);s.scale(1,-1);drawImageAtIntegerCoords(s,n,e.x,e.y,e.w,e.h,0,-1,1,1);this.dependencyTracker?.recordBBox(t,s,0,1,-1,0);s.restore()}this.dependencyTracker?.recordOperation(t);this.compose()}paintSolidColorImageMask(t){if(this.contentVisible){this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,ct).recordOperation(t);this.ctx.fillRect(0,0,1,1);this.compose()}}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;if(this.pendingClip){s||(this.pendingClip===Mt?n.clip(e,"evenodd"):n.clip(e));this.pendingClip=null;this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)}else this.dependencyTracker?.recordOperation(t);this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=getCurrentTransform(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 r,a;if(0===i&&0===s){const i=Math.abs(e),s=Math.abs(n);if(i===s)if(0===t)r=a=1/i;else{const e=i*t;r=a=e<1?1/e:1}else if(0===t){r=1/i;a=1/s}else{const e=i*t,n=s*t;r=e<1?1/e:1;a=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){r=h/o;a=l/o}else{const e=t*o;r=h>e?h/e:1;a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r;this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:s}}=this,[n,r]=this.getScaleForStroking();if(n===r){i.lineWidth=(s||1)*n;i.stroke(t);return}const a=i.getLineDash();e&&i.save();i.scale(n,r);Et.a=1/n;Et.d=1/r;const o=new Path2D;o.addPath(t,Et);if(a.length>0){const t=Math.max(n,r);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(const t in k)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[k[t]]=CanvasGraphics.prototype[t]);class CssFontInfo{#xs;#Es;#Cs;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let s=0;for(const n of CssFontInfo.strings){const r=e.encode(t[n]);i[n]=r;s+=4+r.length}const n=new ArrayBuffer(s),r=new Uint8Array(n),a=new DataView(n);let o=0;for(const t of CssFontInfo.strings){const e=i[t],s=e.length;a.setUint32(o,s);r.set(e,o+4);o+=4+s}assert(o===n.byteLength,"CssFontInfo.write: Buffer overflow");return n}constructor(t){this.#xs=t;this.#Es=new DataView(this.#xs);this.#Cs=new TextDecoder}#_s(t){assert(t<CssFontInfo.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#Es.getUint32(e)+4;const i=this.#Es.getUint32(e);return this.#Cs.decode(new Uint8Array(this.#xs,e+4,i))}get fontFamily(){return this.#_s(0)}get fontWeight(){return this.#_s(1)}get italicAngle(){return this.#_s(2)}}class SystemFontInfo{#xs;#Es;#Cs;static strings=["css","loadedName","baseFontName","src"];static write(t){const e=new TextEncoder,i={};let s=0;for(const n of SystemFontInfo.strings){const r=e.encode(t[n]);i[n]=r;s+=4+r.length}s+=4;let n,r,a=1+s;if(t.style){n=e.encode(t.style.style);r=e.encode(t.style.weight);a+=4+n.length+4+r.length}const o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let d=0;h.setUint8(d++,t.guessFallback?1:0);h.setUint32(d,0);d+=4;s=0;for(const t of SystemFontInfo.strings){const e=i[t],n=e.length;s+=4+n;h.setUint32(d,n);l.set(e,d+4);d+=4+n}h.setUint32(d-s-4,s);if(t.style){h.setUint32(d,n.length);l.set(n,d+4);d+=4+n.length;h.setUint32(d,r.length);l.set(r,d+4);d+=4+r.length}assert(d<=o.byteLength,"SubstitionInfo.write: Buffer overflow");return o.transferToFixedLength(d)}constructor(t){this.#xs=t;this.#Es=new DataView(this.#xs);this.#Cs=new TextDecoder}get guessFallback(){return 0!==this.#Es.getUint8(0)}#_s(t){assert(t<SystemFontInfo.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#Es.getUint32(e)+4;const i=this.#Es.getUint32(e);return this.#Cs.decode(new Uint8Array(this.#xs,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.#Es.getUint32(t);const e=this.#Es.getUint32(t),i=this.#Cs.decode(new Uint8Array(this.#xs,t+4,e));t+=4+e;const s=this.#Es.getUint32(t);return{style:i,weight:this.#Cs.decode(new Uint8Array(this.#xs,t+4,s))}}}class FontInfo{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#Ss=Math.ceil(2*this.bools.length/8);static#Ts=this.#Ss+8*this.numbers.length;static#Ds=this.#Ts+1+8;static#Ms=this.#Ds+1+48;static#ks=this.#Ms+1+6;#xs;#Cs;#Es;constructor({data:t,extra:e}){this.#xs=t;this.#Cs=new TextDecoder;this.#Es=new DataView(this.#xs);e&&Object.assign(this,e)}#Ps(t){assert(t<FontInfo.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,s=this.#Es.getUint8(e)>>i&3;return 0===s?void 0:2===s}get black(){return this.#Ps(0)}get bold(){return this.#Ps(1)}get disableFontFace(){return this.#Ps(2)}get fontExtraProperties(){return this.#Ps(3)}get isInvalidPDFjsFont(){return this.#Ps(4)}get isType3Font(){return this.#Ps(5)}get italic(){return this.#Ps(6)}get missingFile(){return this.#Ps(7)}get remeasure(){return this.#Ps(8)}get vertical(){return this.#Ps(9)}#Is(t){assert(t<FontInfo.numbers.length,"Invalid number index");return this.#Es.getFloat64(FontInfo.#Ss+8*t)}get ascent(){return this.#Is(0)}get defaultWidth(){return this.#Is(1)}get descent(){return this.#Is(2)}get bbox(){let t=FontInfo.#Ts;if(0===this.#Es.getUint8(t))return;t+=1;const e=[];for(let i=0;i<4;i++){e.push(this.#Es.getInt16(t,!0));t+=2}return e}get fontMatrix(){let t=FontInfo.#Ds;if(0===this.#Es.getUint8(t))return;t+=1;const e=[];for(let i=0;i<6;i++){e.push(this.#Es.getFloat64(t,!0));t+=8}return e}get defaultVMetrics(){let t=FontInfo.#Ms;if(0===this.#Es.getUint8(t))return;t+=1;const e=[];for(let i=0;i<3;i++){e.push(this.#Es.getInt16(t,!0));t+=2}return e}#_s(t){assert(t<FontInfo.strings.length,"Invalid string index");let e=FontInfo.#ks+4;for(let i=0;i<t;i++)e+=this.#Es.getUint32(e)+4;const i=this.#Es.getUint32(e),s=new Uint8Array(i);s.set(new Uint8Array(this.#xs,e+4,i));return this.#Cs.decode(s)}get fallbackName(){return this.#_s(0)}get loadedName(){return this.#_s(1)}get mimetype(){return this.#_s(2)}get name(){return this.#_s(3)}get data(){let t=FontInfo.#ks;t+=4+this.#Es.getUint32(t);t+=4+this.#Es.getUint32(t);t+=4+this.#Es.getUint32(t);const e=this.#Es.getUint32(t);if(0!==e)return new Uint8Array(this.#xs,t+4,e)}clearData(){let t=FontInfo.#ks;t+=4+this.#Es.getUint32(t);t+=4+this.#Es.getUint32(t);t+=4+this.#Es.getUint32(t);const e=this.#Es.getUint32(t);new Uint8Array(this.#xs,t+4,e).fill(0);this.#Es.setUint32(t,0)}get cssFontInfo(){let t=FontInfo.#ks;t+=4+this.#Es.getUint32(t);t+=4+this.#Es.getUint32(t);const e=this.#Es.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#xs,t+4,e));return new CssFontInfo(i.buffer)}get systemFontInfo(){let t=FontInfo.#ks;t+=4+this.#Es.getUint32(t);const e=this.#Es.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#xs,t+4,e));return new SystemFontInfo(i.buffer)}static write(t){const e=t.systemFontInfo?SystemFontInfo.write(t.systemFontInfo):null,i=t.cssFontInfo?CssFontInfo.write(t.cssFontInfo):null,s=new TextEncoder,n={};let r=0;for(const e of FontInfo.strings){n[e]=s.encode(t[e]);r+=4+n[e].length}const a=FontInfo.#ks+4+r+4+(e?e.byteLength:0)+4+(i?i.byteLength:0)+4+(t.data?t.data.length:0),o=new ArrayBuffer(a),l=new Uint8Array(o),h=new DataView(o);let d=0;const c=FontInfo.bools.length;let u=0,p=0;for(let e=0;e<c;e++){const i=t[FontInfo.bools[e]];u|=(void 0===i?0:i?2:1)<<p;p+=2;if(8===p||e===c-1){h.setUint8(d++,u);u=0;p=0}}assert(d===FontInfo.#Ss,"FontInfo.write: Boolean properties offset mismatch");for(const e of FontInfo.numbers){h.setFloat64(d,t[e]);d+=8}assert(d===FontInfo.#Ts,"FontInfo.write: Number properties offset mismatch");if(t.bbox){h.setUint8(d++,4);for(const e of t.bbox){h.setInt16(d,e,!0);d+=2}}else{h.setUint8(d++,0);d+=8}assert(d===FontInfo.#Ds,"FontInfo.write: BBox properties offset mismatch");if(t.fontMatrix){h.setUint8(d++,6);for(const e of t.fontMatrix){h.setFloat64(d,e,!0);d+=8}}else{h.setUint8(d++,0);d+=48}assert(d===FontInfo.#Ms,"FontInfo.write: FontMatrix properties offset mismatch");if(t.defaultVMetrics){h.setUint8(d++,1);for(const e of t.defaultVMetrics){h.setInt16(d,e,!0);d+=2}}else{h.setUint8(d++,0);d+=6}assert(d===FontInfo.#ks,"FontInfo.write: DefaultVMetrics properties offset mismatch");h.setUint32(FontInfo.#ks,0);d+=4;for(const t of FontInfo.strings){const e=n[t],i=e.length;h.setUint32(d,i);l.set(e,d+4);d+=4+i}h.setUint32(FontInfo.#ks,d-FontInfo.#ks-4);if(e){const t=e.byteLength;h.setUint32(d,t);assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo");l.set(new Uint8Array(e),d+4);d+=4+t}else{h.setUint32(d,0);d+=4}if(i){const t=i.byteLength;h.setUint32(d,t);assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo");l.set(new Uint8Array(i),d+4);d+=4+t}else{h.setUint32(d,0);d+=4}if(void 0===t.data){h.setUint32(d,0);d+=4}else{h.setUint32(d,t.data.length);l.set(t.data,d+4);d+=4+t.data.length}assert(d<=o.byteLength,"FontInfo.write: Buffer overflow");return o.transferToFixedLength(d)}}class GlobalWorkerOptions{static#Fs=null;static#Rs="";static get workerPort(){return this.#Fs}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Fs=t}static get workerSrc(){return this.#Rs}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Rs=t}}class Metadata{#Ls;#Bs;constructor({parsedData:t,rawData:e}){this.#Ls=t;this.#Bs=e}getRaw(){return this.#Bs}get(t){return this.#Ls.get(t)??null}[Symbol.iterator](){return this.#Ls.entries()}}const kt=Symbol("INTERNAL");class OptionalContentGroup{#Os=!1;#Ns=!1;#Us=!1;#Hs=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:a}){this.#Os=!!(t&n);this.#Ns=!!(t&r);this.name=e;this.intent=i;this.usage=s;this.rbGroups=a}get visible(){if(this.#Us)return this.#Hs;if(!this.#Hs)return!1;const{print:t,view:e}=this.usage;return this.#Os?"OFF"!==e?.viewState:!this.#Ns||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==kt&&unreachable("Internal method `_setVisible` called.");this.#Us=i;this.#Hs=e}}class OptionalContentConfig{#zs=null;#Gs=new Map;#Ws=null;#Vs=null;constructor(t,e=n){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#Vs=t.order;for(const i of t.groups)this.#Gs.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#Gs.values())t._setVisible(kt,!1);for(const e of t.on)this.#Gs.get(e)._setVisible(kt,!0);for(const e of t.off)this.#Gs.get(e)._setVisible(kt,!1);this.#Ws=this.getHash()}}#$s(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.#$s(e);else{if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return!0}n=this.#Gs.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.#Gs.size)return!0;if(!t){info("Optional content group not defined.");return!0}if("OCG"===t.type){if(!this.#Gs.has(t.id)){warn(`Optional content group not found: ${t.id}`);return!0}return this.#Gs.get(t.id).visible}if("OCMD"===t.type){if(t.expression)return this.#$s(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#Gs.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#Gs.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#Gs.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#Gs.get(e).visible)return!1}return!0}warn(`Unknown optional content policy ${t.policy}.`);return!0}warn(`Unknown group type ${t.type}.`);return!0}setVisibility(t,e=!0,i=!0){const s=this.#Gs.get(t);if(s){if(i&&e&&s.rbGroups.length)for(const e of s.rbGroups)for(const i of e)i!==t&&this.#Gs.get(i)?._setVisible(kt,!1,!0);s._setVisible(kt,!!e,!0);this.#zs=null}else warn(`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.#Gs.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.#zs=null}get hasInitialVisibility(){return null===this.#Ws||this.getHash()===this.#Ws}getOrder(){return this.#Gs.size?this.#Vs?this.#Vs.slice():[...this.#Gs.keys()]:null}getGroup(t){return this.#Gs.get(t)||null}getHash(){if(null!==this.#zs)return this.#zs;const t=new MurmurHash3_64;for(const[e,i]of this.#Gs)t.update(`${e}:${i.visible}`);return this.#zs=t.hexdigest()}[Symbol.iterator](){return this.#Gs.entries()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:r,contentDispositionFilename:a}=t;this._queuedChunks=[];this._progressiveDone=r;this._contentDispositionFilename=a;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener((t,e)=>{this._onReceiveData({begin:t,chunk:e})});t.addProgressListener((t,e)=>{this._onProgress({loaded:t,total:e})});t.addProgressiveReadListener(t=>{this._onReceiveData({chunk:t})});t.addProgressiveDoneListener(()=>{this._onProgressiveDone()});t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some(function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(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 getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return n;n.suggestedLength=r;if(r<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t<e.length&&t in e;++t){let[i,s]=e[t];s=rfc2616unquote(s);if(i){s=unescape(s);0===t&&(s=rfc5987decode(s))}n.push(s)}return n.join("")}(t);if(i)return fixupEncoding(rfc2047decode(i));i=toParamRegExp("filename","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=rfc2047decode(t);return fixupEncoding(t)}function toParamRegExp(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function textdecode(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const s=new TextDecoder(t,{fatal:!0}),n=stringToBytes(i);i=s.decode(n);e=!1}catch{}}return i}function fixupEncoding(t){if(e&&/[\x80-\xff]/.test(t)){t=textdecode("utf-8",t);e&&(t=textdecode("iso-8859-1",t))}return t}function rfc2616unquote(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');if(-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 rfc5987decode(t){const e=t.indexOf("'");return-1===e?t:textdecode(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function rfc2047decode(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(t,e,i,s){if("q"===i||"Q"===i)return textdecode(e,s=(s=s.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{s=atob(s)}catch{}return textdecode(e,s)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(isPdfFile(t))return t}return null}function createResponseError(t,e){return new ResponseException(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,404===t||0===t&&e.startsWith("file:"))}function validateResponseStatus(t){return 200===t||206===t}function createFetchOptions(t,e,i){return{method:"GET",headers:t,signal:i.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;warn(`getArrayBuffer - unexpected data format: ${t}`);return new Uint8Array(t).buffer}class PDFFetchStream{_responseOrigin=null;constructor(t){this.source=t;this.isHttp=/^https?:/i.test(t.url);this.headers=createHeaders(this.isHttp,t.httpHeaders);this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once.");this._fullRequestReader=new PDFFetchStreamReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFFetchStreamRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFFetchStreamReader{constructor(t){this._stream=t;this._reader=null;this._loaded=0;this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1;this._contentLength=e.length;this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._abortController=new AbortController;this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;const i=new Headers(t.headers),s=e.url;fetch(s,createFetchOptions(i,this._withCredentials,this._abortController)).then(e=>{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:r}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=r||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const r=s.url;fetch(r,createFetchOptions(n,this._withCredentials,this._abortController)).then(e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseError(e.status,r);this._readCapability.resolve();this._reader=e.body.getReader()}).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const r=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:r});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else r?i.onDone({begin:0,chunk:r}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=r||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Pt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Pt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then(t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()},t=>{"ENOENT"===t.code&&(t=createResponseError(0,this._url.href));this._storedError=t;this._headersCapability.reject(t)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",()=>{this._readCapability.resolve()});t.on("end",()=>{t.destroy();this._done=!0;this._readCapability.resolve()});t.on("error",t=>{this._error(t)});!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",()=>{this._readCapability.resolve()});t.on("end",()=>{t.destroy();this._done=!0;this._readCapability.resolve()});t.on("error",t=>{this._error(t)});this._storedError&&this._readableStream.destroy(this._storedError)}}const It=Symbol("INITIAL_DATA");class PDFObjects{#js=Object.create(null);#qs(t){return this.#js[t]||={...Promise.withResolvers(),data:It}}get(t,e=null){if(e){const i=this.#qs(t);i.promise.then(()=>e(i.data));return null}const i=this.#js[t];if(!i||i.data===It)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#js[t];return!!e&&e.data!==It}delete(t){const e=this.#js[t];if(!e||e.data===It)return!1;delete this.#js[t];return!0}resolve(t,e=null){const i=this.#qs(t);i.data=e;i.resolve()}clear(){for(const t in this.#js){const{data:e}=this.#js[t];e?.bitmap?.close()}this.#js=Object.create(null)}*[Symbol.iterator](){for(const t in this.#js){const{data:e}=this.#js[t];e!==It&&(yield[t,e])}}}class TextLayer{#Xs=Promise.withResolvers();#vt=null;#Ks=!1;#Ys=!!globalThis.FontInspector?.enabled;#Qs=null;#Js=null;#Zs=0;#tn=0;#en=null;#in=null;#sn=0;#nn=0;#rn=Object.create(null);#an=[];#on=null;#ln=[];#hn=new WeakMap;#dn=null;static#cn=new Map;static#un=new Map;static#pn=new WeakMap;static#gn=null;static#mn=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#on=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#on=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#vt=this.#in=e;this.#nn=i.scale*OutputScale.pixelRatio;this.#sn=i.rotation;this.#Js={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:r,pageY:a}=i.rawDims;this.#dn=[1,0,0,-1,-r,a+n];this.#tn=s;this.#Zs=n;TextLayer.#fn();setLayerDimensions(e,i);this.#Xs.promise.finally(()=>{TextLayer.#mn.delete(this);this.#Js=null;this.#rn=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#en.read().then(({value:t,done:e})=>{if(e)this.#Xs.resolve();else{this.#Qs??=t.lang;Object.assign(this.#rn,t.styles);this.#bn(t.items);pump()}},this.#Xs.reject)};this.#en=this.#on.getReader();TextLayer.#mn.add(this);pump();return this.#Xs.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,s=t.rotation;if(s!==this.#sn){e?.();this.#sn=s;setLayerDimensions(this.#in,{rotation:s})}if(i!==this.#nn){e?.();this.#nn=i;const t={div:null,properties:null,ctx:TextLayer.#wn(this.#Qs)};for(const e of this.#ln){t.properties=this.#hn.get(e);t.div=e;this.#yn(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#en?.cancel(t).catch(()=>{});this.#en=null;this.#Xs.reject(t)}get textDivs(){return this.#ln}get textContentItemsStr(){return this.#an}#bn(t){if(this.#Ks)return;this.#Js.ctx??=TextLayer.#wn(this.#Qs);const e=this.#ln,i=this.#an;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ks=!0;return}if(void 0!==s.str){i.push(s.str);this.#An(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#vt;this.#vt=document.createElement("span");this.#vt.classList.add("markedContent");s.id&&this.#vt.setAttribute("id",`${s.id}`);t.append(this.#vt)}else"endMarkedContent"===s.type&&(this.#vt=this.#vt.parentNode)}}#An(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ln.push(e);const s=Util.transform(this.#dn,t.transform);let n=Math.atan2(s[1],s[0]);const r=this.#rn[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#Ys&&r.fontSubstitution||r.fontFamily;a=TextLayer.fontFamilyMap.get(a)||a;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#vn(a,r,this.#Qs);let h,d;if(0===n){h=s[4];d=s[5]-l}else{h=s[4]+l*Math.sin(n);d=s[5]-l*Math.cos(n)}const c="calc(var(--total-scale-factor) *",u=e.style;if(this.#vt===this.#in){u.left=`${(100*h/this.#tn).toFixed(2)}%`;u.top=`${(100*d/this.#Zs).toFixed(2)}%`}else{u.left=`${c}${h.toFixed(2)}px)`;u.top=`${c}${d.toFixed(2)}px)`}u.fontSize=`${c}${(TextLayer.#gn*o).toFixed(2)}px)`;u.fontFamily=a;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ys&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=r.vertical?t.height:t.width);this.#hn.set(e,i);this.#Js.div=e;this.#Js.properties=i;this.#yn(this.#Js);i.hasText&&this.#vt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#vt.append(t)}}#yn(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let r="";TextLayer.#gn>1&&(r=`scale(${1/TextLayer.#gn})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:a,fontSize:o}=i;TextLayer.#xn(s,o*this.#nn,t);const{width:l}=s.measureText(e.textContent);l>0&&(r=`scaleX(${a*this.#nn/l}) ${r}`)}0!==i.angle&&(r=`rotate(${i.angle}deg) ${r}`);r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#mn.size>0)){this.#cn.clear();for(const{canvas:t}of this.#un.values())t.remove();this.#un.clear()}}static#wn(t=null){let e=this.#un.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#un.set(t,e);this.#pn.set(e,{size:0,family:""})}return e}static#xn(t,e,i){const s=this.#pn.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#fn(){if(null!==this.#gn)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.#gn=t.getBoundingClientRect().height;t.remove()}static#vn(t,e,i){const s=this.#cn.get(t);if(s)return s;const n=this.#wn(i);n.canvas.width=n.canvas.height=30;this.#xn(n,30,t);const r=n.measureText(""),a=r.fontBoundingBoxAscent,o=Math.abs(r.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;if(a)l=a/(a+o);else{util_FeatureTest.platform.isFirefox&&warn("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.#cn.set(t,l);return l}}function getDocument(e={}){"string"==typeof e||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});const i=new PDFDocumentLoadingTask,{docId:s}=i,n=e.url?function getUrlProp(e){if(e instanceof URL)return e.href;if("string"==typeof e){if(t)return e;const i=URL.parse(e,window.location);if(i)return i.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(e.url):null,r=e.data?function getDataProp(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 stringToBytes(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,a=e.httpHeaders||null,o=!0===e.withCredentials,l=e.password??null,h=e.range instanceof PDFDataRangeTransport?e.range:null,d=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536;let c=e.worker instanceof PDFWorker?e.worker:null;const u=e.verbosity,p="string"!=typeof e.docBaseUrl||isDataScheme(e.docBaseUrl)?null:e.docBaseUrl,g=getFactoryUrlProp(e.cMapUrl),m=!1!==e.cMapPacked,f=e.CMapReaderFactory||(t?NodeCMapReaderFactory:DOMCMapReaderFactory),b=getFactoryUrlProp(e.iccUrl),w=getFactoryUrlProp(e.standardFontDataUrl),y=e.StandardFontDataFactory||(t?NodeStandardFontDataFactory:DOMStandardFontDataFactory),A=getFactoryUrlProp(e.wasmUrl),v=e.WasmFactory||(t?NodeWasmFactory:DOMWasmFactory),x=!0!==e.stopAtErrors,E=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,C=!1!==e.isEvalSupported,_="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,S="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,D="boolean"==typeof e.disableFontFace?e.disableFontFace:t,M=!0===e.fontExtraProperties,k=!0===e.enableXfa,P=e.ownerDocument||globalThis.document,I=!0===e.disableRange,F=!0===e.disableStream,R=!0===e.disableAutoFetch,L=!0===e.pdfBug,B=e.CanvasFactory||(t?NodeCanvasFactory:DOMCanvasFactory),O=e.FilterFactory||(t?NodeFilterFactory:DOMFilterFactory),N=!0===e.enableHWA,U=!1!==e.useWasm,H=h?h.length:e.length??NaN,z="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!D,G="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(f===DOMCMapReaderFactory&&y===DOMStandardFontDataFactory&&v===DOMWasmFactory&&g&&w&&A&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(w,document.baseURI)&&isValidFetchUrl(A,document.baseURI));setVerbosityLevel(u);const W={canvasFactory:new B({ownerDocument:P,enableHWA:N}),filterFactory:new O({docId:s,ownerDocument:P}),cMapReaderFactory:G?null:new f({baseUrl:g,isCompressed:m}),standardFontDataFactory:G?null:new y({baseUrl:w}),wasmFactory:G?null:new v({baseUrl:A})};if(!c){c=PDFWorker.create({verbosity:u,port:GlobalWorkerOptions.workerPort});i._worker=c}const V={docId:s,apiVersion:"5.4.296",data:r,password:l,disableAutoFetch:R,rangeChunkSize:d,length:H,docBaseUrl:p,enableXfa:k,evaluatorOptions:{maxImageSize:E,disableFontFace:D,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:_,isImageDecoderSupported:S,canvasMaxAreaInBytes:T,fontExtraProperties:M,useSystemFonts:z,useWasm:U,useWorkerFetch:G,cMapUrl:g,iccUrl:b,standardFontDataUrl:w,wasmUrl:A}},$={ownerDocument:P,pdfBug:L,styleElement:null,loadingParams:{disableAutoFetch:R,enableXfa:k}};c.promise.then(function(){if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=c.messageHandler.sendWithPromise("GetDocRequest",V,r?[r.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:I,disableStream:F});else if(!r){if(!n)throw new Error("getDocument - no `url` parameter provided.");const e=isValidFetchUrl(n)?PDFFetchStream:t?PDFNodeStream:PDFNetworkStream;l=new e({url:n,length:H,httpHeaders:a,withCredentials:o,rangeChunkSize:d,disableRange:I,disableStream:F})}return e.then(t=>{if(i.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(s,t,c.port),n=new WorkerTransport(e,i,l,$,W,N);i._transport=n;e.send("Ready",null)})}).catch(i._capability.reject);return i}class PDFDocumentLoadingTask{static#Li=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#Li++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}async getData(){return this._transport.getData()}}class PDFDataRangeTransport{#Xs=Promise.withResolvers();#En=[];#Cn=[];#_n=[];#Sn=[];constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s}addRangeListener(t){this.#Sn.push(t)}addProgressListener(t){this.#_n.push(t)}addProgressiveReadListener(t){this.#Cn.push(t)}addProgressiveDoneListener(t){this.#En.push(t)}onDataRange(t,e){for(const i of this.#Sn)i(t,e)}onDataProgress(t,e){this.#Xs.promise.then(()=>{for(const i of this.#_n)i(t,e)})}onDataProgressiveRead(t){this.#Xs.promise.then(()=>{for(const e of this.#Cn)e(t)})}onDataProgressiveDone(){this.#Xs.promise.then(()=>{for(const t of this.#En)t()})}transportReady(){this.#Xs.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}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 shadow(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()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#Tn=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=!1;this.recordedBBoxes=null}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({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 shadow(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=c.ENABLE,transform:a=null,background:o=null,optionalContentConfigPromise:l=null,annotationCanvasMap:h=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:p=!1,recordOperations:g=!1,operationsFilter:m=null}){this._stats?.time("Overall");const f=this._transport.getRenderingIntent(s,n,u,p),{renderingIntent:b,cacheKey:w}=f;this.#Tn=!1;l||=this._transport.getOptionalContentConfig(b);let y=this._intentStates.get(w);if(!y){y=Object.create(null);this._intentStates.set(w,y)}if(y.streamReaderCancelTimeout){clearTimeout(y.streamReaderCancelTimeout);y.streamReaderCancelTimeout=null}const A=!!(b&r);if(!y.displayReadyCapability){y.displayReadyCapability=Promise.withResolvers();y.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(f)}const v=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),x=!this.recordedBBoxes&&(g||v),complete=t=>{y.renderTasks.delete(E);if(x){const t=E.gfx?.dependencyTracker.take();if(t){E.stepper&&E.stepper.setOperatorBBoxes(t,E.gfx.dependencyTracker.takeDebugMetadata());g&&(this.recordedBBoxes=t)}}A&&(this.#Tn=!0);this.#Dn();if(t){E.capability.reject(t);this._abortOperatorList({intentState:y,reason:t instanceof Error?t:new Error(t)})}else E.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},E=new InternalRenderTask({callback:complete,params:{canvas:e,canvasContext:t,dependencyTracker:x?new CanvasDependencyTracker(e,y.operatorList.length,v):null,viewport:i,transform:a,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:y.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!A,pdfBug:this._pdfBug,pageColors:d,enableHWA:this._transport.enableHWA,operationsFilter:m});(y.renderTasks||=new Set).add(E);const C=E.task;Promise.all([y.displayReadyCapability.promise,l]).then(([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&b))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(complete);return C}getOperatorList({intent:t="display",annotationMode:e=c.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let r,a=this._intentStates.get(n.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(n.cacheKey,a)}if(!a.opListReadCapability){r=Object.create(null);r.operatorListChanged=function operatorListChanged(){if(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)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>XfaText.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then(function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#Tn=!1;return Promise.all(t)}cleanup(t=!1){this.#Tn=!0;const e=this.#Dn();t&&e&&(this._stats&&=new StatTimer);return e}#Dn(){if(!this.#Tn||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#Tn=!1;return!0}_startRenderPage(t,e){const i=this._intentStates.get(e);if(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.#Dn()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:s}){const{map:n,transfer:r}=i,a=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:s},r).getReader(),o=this._intentStates.get(e);o.streamReader=a;const pump=()=>{a.read().then(({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}},t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#Dn()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}t.streamReader.cancel(new AbortException(e.message)).catch(()=>{});t.streamReader=null;if(!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 PDFWorker{#Xs=Promise.withResolvers();#Mn=null;#Fs=null;#kn=null;static#Pn=0;static#In=!1;static#Fn=new WeakMap;static{if(t){this.#In=!0;GlobalWorkerOptions.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"}))};this.fromPort=t=>{!function deprecated(t){console.log("Deprecated API usage: "+t)}("`PDFWorker.fromPort` - please use `PDFWorker.create` instead.");if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;if(e){if(PDFWorker.#Fn.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#Fn.set(e,this);this.#Rn(e)}else this.#Ln()}get promise(){return this.#Xs.promise}#Bn(){this.#Xs.resolve();this.#Mn.send("configure",{verbosity:this.verbosity})}get port(){return this.#Fs}get messageHandler(){return this.#Mn}#Rn(t){this.#Fs=t;this.#Mn=new MessageHandler("main","worker",t);this.#Mn.on("ready",()=>{});this.#Bn()}#Ln(){if(PDFWorker.#In||PDFWorker.#On){this.#Nn();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this.#Xs.reject(new Error("Worker was destroyed")):this.#Nn()},s=new AbortController;e.addEventListener("error",()=>{this.#kn||terminateEarly()},{signal:s.signal});i.on("test",t=>{s.abort();if(!this.destroyed&&t){this.#Mn=i;this.#Fs=e;this.#kn=e;this.#Bn()}else terminateEarly()});i.on("ready",t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this.#Nn()}});const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this.#Nn()}#Nn(){if(!PDFWorker.#In){warn("Setting up fake worker.");PDFWorker.#In=!0}PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this.#Xs.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this.#Fs=e;const i="fake"+PDFWorker.#Pn++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this.#Mn=new MessageHandler(i,i+"_worker",e);this.#Bn()}).catch(t=>{this.#Xs.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0;this.#kn?.terminate();this.#kn=null;PDFWorker.#Fn.delete(this.#Fs);this.#Fs=null;this.#Mn?.destroy();this.#Mn=null}static create(t){const e=this.#Fn.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 PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#On(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#On)return this.#On;return(await import(
- /*webpackIgnore: true*/
- /*@vite-ignore*/
- this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Un=new Map;#Hn=new Map;#zn=new Map;#Gn=new Map;#Wn=null;constructor(t,e,i,s,n,r){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.wasmFactory=n.wasmFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.enableHWA=r;this.setupMessageHandler()}#Vn(t,e=null){const i=this.#Un.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Un.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=c.ENABLE,i=null,u=!1,p=!1){let g=n,m=X;switch(t){case"any":g=s;break;case"display":break;case"print":g=r;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&r&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case c.DISABLE:g+=l;break;case c.ENABLE:break;case c.ENABLE_FORMS:g+=a;break;case c.ENABLE_STORAGE:g+=o;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}u&&(g+=h);p&&(g+=d);const{ids:b,hash:w}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,w].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Wn?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Hn.values())t.push(e._destroy());this.#Hn.clear();this.#zn.clear();this.#Gn.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then(()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Un.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()},this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}});t.on("GetRangeReader",(t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i)e.close();else{assert(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})}}else e.close()});t.on("GetDoc",({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))});t.on("DocException",t=>{e._capability.reject(wrapReason(t))});t.on("PasswordRequest",t=>{this.#Wn=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Wn.reject(t):this.#Wn.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Wn.reject(t)}return this.#Wn.promise});t.on("DataLoaded",t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#Hn.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;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const n=new FontInfo(s),r=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,a=new FontFaceObject(n,r,s.extra,s.charProcOperatorList);this.fontLoader.bind(a).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!a.fontExtraProperties&&a.data&&a.clearData();this.commonObjs.resolve(e,a)});break;case"CopyLocalImage":const{imageRef:o}=s;assert(o,"The imageRef must be defined.");for(const t of this.#Hn.values())for(const[,i]of t.objs)if(i?.ref===o){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);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.#Hn.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||e.onProgress?.({loaded:t.loaded,total:t.total})});t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#zn.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#Gn.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Hn.set(e,s);return s});this.#zn.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Vn("GetFieldObjects")}hasJSActions(){return this.#Vn("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.#Vn("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Vn("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Un.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));this.#Un.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Hn.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Un.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Gn.get(e)??null}}class RenderTask{#$n=null;onContinue=null;onError=null;constructor(t){this.#$n=t}get promise(){return this.#$n.capability.promise}cancel(t=0){this.#$n.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#$n.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#$n;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#jn=null;static#qn=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:r,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=n;this.operatorListIdx=null;this.operatorList=r;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&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvas;this._canvasContext=e.canvas?null:e.canvasContext;this._enableHWA=u;this._dependencyTracker=e.dependencyTracker;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(InternalRenderTask.#qn.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.");InternalRenderTask.#qn.add(this._canvas)}if(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:r}=this.params,a=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,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();if(this.#jn){window.cancelAnimationFrame(this.#jn);this.#jn=null}InternalRenderTask.#qn.delete(this._canvas);t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e);this.callback(t);this.task.onError?.(t)}operatorListChanged(){if(this.graphicsReady){this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#jn=window.requestAnimationFrame(()=>{this.#jn=null;this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#qn.delete(this._canvas);this.callback()}}}}}const Ft="5.4.296",Rt="f56dc8601";class ColorPicker{#Xn=null;#Kn=null;#Yn;#Qn=null;#Jn=!1;#Zn=!1;#r=null;#tr;#er=null;#b=null;static#ir=null;static get _keyboardManager(){return shadow(this,"_keyboardManager",new KeyboardManager([[["Escape","mac+Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home","mac+Home"],ColorPicker.prototype._moveToBeginning],[["End","mac+End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#Zn=!1;this.#r=t}else this.#Zn=!0;this.#b=t?._uiManager||e;this.#tr=this.#b._eventBus;this.#Yn=t?.color?.toUpperCase()||this.#b?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#ir||=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.#Xn=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.#b._signal;t.addEventListener("click",this.#sr.bind(this),{signal:e});t.addEventListener("keydown",this.#nr.bind(this),{signal:e});const i=this.#Kn=document.createElement("span");i.className="swatch";i.ariaHidden="true";i.style.backgroundColor=this.#Yn;t.append(i);return t}renderMainDropdown(){const t=this.#Qn=this.#rr();t.ariaOrientation="horizontal";t.ariaLabelledBy="highlightColorPickerLabel";return t}#rr(){const t=document.createElement("div"),e=this.#b._signal;t.addEventListener("contextmenu",noContextMenu,{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.#b.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",ColorPicker.#ir[i]);const r=document.createElement("span");n.append(r);r.className="swatch";r.style.backgroundColor=s;n.ariaSelected=s===this.#Yn;n.addEventListener("click",this.#ar.bind(this,s),{signal:e});t.append(n)}t.addEventListener("keydown",this.#nr.bind(this),{signal:e});return t}#ar(t,e){e.stopPropagation();this.#tr.dispatch("switchannotationeditorparams",{source:this,type:g.HIGHLIGHT_COLOR,value:t});this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Xn){this.#sr(t);return}const e=t.target.getAttribute("data-color");e&&this.#ar(e,t)}_moveToNext(t){this.#or?t.target!==this.#Xn?t.target.nextSibling?.focus():this.#Qn.firstChild?.focus():this.#sr(t)}_moveToPrevious(t){if(t.target!==this.#Qn?.firstChild&&t.target!==this.#Xn){this.#or||this.#sr(t);t.target.previousSibling?.focus()}else this.#or&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#or?this.#Qn.firstChild?.focus():this.#sr(t)}_moveToEnd(t){this.#or?this.#Qn.lastChild?.focus():this.#sr(t)}#nr(t){ColorPicker._keyboardManager.exec(this,t)}#sr(t){if(this.#or){this.hideDropdown();return}this.#Jn=0===t.detail;if(!this.#er){this.#er=new AbortController;window.addEventListener("pointerdown",this.#u.bind(this),{signal:this.#b.combinedSignal(this.#er)})}this.#Xn.ariaExpanded="true";if(this.#Qn){this.#Qn.classList.remove("hidden");return}const e=this.#Qn=this.#rr();this.#Xn.append(e)}#u(t){this.#Qn?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Qn?.classList.add("hidden");this.#Xn.ariaExpanded="false";this.#er?.abort();this.#er=null}get#or(){return this.#Qn&&!this.#Qn.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#Zn)if(this.#or){this.hideDropdown();this.#Xn.focus({preventScroll:!0,focusVisible:this.#Jn})}else this.#r?.unselect()}updateColor(t){this.#Kn&&(this.#Kn.style.backgroundColor=t);if(!this.#Qn)return;const e=this.#b.highlightColors.values();for(const i of this.#Qn.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Xn?.remove();this.#Xn=null;this.#Kn=null;this.#Qn?.remove();this.#Qn=null}}class BasicColorPicker{#lr=null;#r=null;#b=null;static#ir=null;constructor(t){this.#r=t;this.#b=t._uiManager;BasicColorPicker.#ir||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#lr)return this.#lr;const{editorType:t,colorType:e,colorValue:i}=this.#r,s=this.#lr=document.createElement("input");s.type="color";s.value=i||"#000000";s.className="basicColorPicker";s.tabIndex=0;s.setAttribute("data-l10n-id",BasicColorPicker.#ir[t]);s.addEventListener("input",()=>{this.#b.updateParams(e,s.value)},{signal:this.#b._signal});return s}update(t){this.#lr&&(this.#lr.value=t)}destroy(){this.#lr?.remove();this.#lr=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{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=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(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(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).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[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(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,r=1-i;return["CMYK",s,n,r,Math.min(s,n,r)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(G,t)}}const Lt=new WeakSet,Bt=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case E.LINK:return new LinkAnnotationElement(t);case E.TEXT:return new TextAnnotationElement(t);case E.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case E.POPUP:return new PopupAnnotationElement(t);case E.FREETEXT:return new FreeTextAnnotationElement(t);case E.LINE:return new LineAnnotationElement(t);case E.SQUARE:return new SquareAnnotationElement(t);case E.CIRCLE:return new CircleAnnotationElement(t);case E.POLYLINE:return new PolylineAnnotationElement(t);case E.CARET:return new CaretAnnotationElement(t);case E.INK:return new InkAnnotationElement(t);case E.POLYGON:return new PolygonAnnotationElement(t);case E.HIGHLIGHT:return new HighlightAnnotationElement(t);case E.UNDERLINE:return new UnderlineAnnotationElement(t);case E.SQUIGGLY:return new SquigglyAnnotationElement(t);case E.STRIKEOUT:return new StrikeOutAnnotationElement(t);case E.STAMP:return new StampAnnotationElement(t);case E.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#hr=null;#dr=!1;#cr=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;e&&(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 AnnotationElement._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,r=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)if(e[t+1]>r){r=e[t+1];n=e[t+2]}else e[t+1]===r&&(n=Math.max(n,e[t+2]));return[n,r]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)if(t[e+1]>r){r=t[e+1];n=t[e]}else t[e+1]===r&&(n=Math.max(n,t[e]));if(n!==1/0)return[n,r]}return s?[s[2],s[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:r}}}=this.parent;t[1]=e[3]-t[1]+e[1];t[0]=100*(t[0]-n)/i;t[1]=100*(t[1]-r)/s;return t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${u}${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(`${u}${e.id}`,{id:e.id,annotationType:e.annotationType,pageIndex:this.parent.page._pageIndex,popup:i,popupRef:e.popupRef,modificationDate:new Date});t||this.removePopup()}removePopup(){(this.#cr?.popup||this.popup)?.remove();this.#cr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#hr||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#ur(e);let s=this.#cr?.popup||this.popup;if(!s&&i?.text){this._createPopup(i);s=this.#cr.popup}if(s){s.updateEdited(t);if(i?.deleted){s.remove();this.#cr=null;this.popup=null}}}resetEdited(){if(this.#hr){this.#ur(this.#hr.rect);this.#cr?.popup.resetEdited();this.#hr=null}}#ur(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t);e.left=100*(t[0]-a)/n+"%";e.top=100*(r-t[3]+o)/r+"%";if(0===s){e.width=100*(t[2]-t[0])/n+"%";e.height=100*(t[3]-t[1])/r+"%"}else 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 WidgetAnnotationElement||this instanceof LinkAnnotationElement||(n.tabIndex=0);const{style:r}=n;r.zIndex=this.parent.zIndex;this.parent.zIndex+=2;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:a,height:o}=this;if(!t&&e.borderStyle.width>0){r.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))`;r.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${a}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case C:r.borderStyle="solid";break;case _:r.borderStyle="dashed";break;case S:warn("Unimplemented border style: beveled");break;case T:warn("Unimplemented border style: inset");break;case D:r.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#dr=!0;r.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else r.borderWidth=0}const l=Util.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;r.left=100*(l[0]-c)/h+"%";r.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){r.width=100*a/h+"%";r.height=100*o/d+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims;let{width:n,height:r}=this;t%180!=0&&([n,r]=[r,n]);e.style.width=100*n/i+"%";e.style.height=100*r/s+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],r=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](r);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](r)})};return shadow(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:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},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 r=i[s];if(r){r({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[r,a,o,l]=t.subarray(2,6);if(s===r&&n===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#dr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);d.role="none";const c=h.createElement("defs");d.append(c);const 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){const s=t[i],r=t[i+1],d=t[i+2],c=t[i+3],p=h.createElement("rect"),g=(d-e)/o,m=(n-r)/l,f=(s-d)/o,b=(r-c)/l;p.setAttribute("x",g);p.setAttribute("y",m);p.setAttribute("width",f);p.setAttribute("height",b);u.append(p);a?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}if(this.#dr){a.push("</g></svg>')");r.backgroundImage=a.join("")}this.container.append(d);this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,s;if(t){i={str:t.text};s=t.date}else{i=e.contentsObj;s=e.modificationDate}const n=this.#cr=new PopupAnnotationElement({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]});this.parent._commentManager||this.parent.div.append(n.render())}get hasPopupElement(){return!!(this.#cr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#cr}render(){unreachable("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:r}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${n}"]`);!a||Lt.has(a)?i.push({id:n,exportValue:s,domElement:a}):warn(`_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&&(Lt.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})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class EditorAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.editor=t.editor}render(){this.container.className="editorAnnotation";return this.container}createOrUpdatePopup(){const{editor:t}=this;if(t.hasComment){this._createPopup(t.comment);this.extraPopupElement.popup.renderCommentButton()}}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.container.remove();this.container=null;this.removePopup()}}class LinkAnnotationElement extends AnnotationElement{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;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action,t.overlaidText);s=!0}else if(t.attachment){this.#pr(i,t.attachment,t.overlaidText,t.attachmentDest);s=!0}else if(t.setOCGState){this.#gr(i,t.setOCGState,t.overlaidText);s=!0}else if(t.dest){this._bindLink(i,t.dest,t.overlaidText);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#mr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#mr();i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};i&&(t.title=i);this.#mr()}#pr(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);return!1};this.#mr()}#gr(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};i&&(t.title=i);this.#mr()}_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}});return!1})}e.overlaidText&&(t.title=e.overlaidText);t.onclick||(t.onclick=()=>!1);this.#mr()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#mr();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,r=[];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&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Lt.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.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,r]of i)if("Action"===r||this.data.actions?.[r]){"Focus"!==r&&"Blur"!==r||(e||={focused:!1});this._setEventListener(t,e,n,r,s);"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||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":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||9,r=t.style;let a;const roundToOneDecimal=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/(i*n))||1);a=Math.min(n,roundToOneDecimal(e/i))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(n,roundToOneDecimal(t/i))}r.fontSize=`calc(${a}px * var(--total-scale-factor))`;r.color=Util.makeHexColor(s[0],s[1],s[2]);null!==this.data.textAlignment&&(r.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{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 r of this._getElementsByName(t.name,t.id)){r.domElement&&(r.domElement[e]=i);n.setValue(r.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 r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=s.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=a??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type=this.data.password?"password":"text";i.setAttribute("value",a??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);Lt.add(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:d}=this.data,c=!!h&&this.enableScripting;l&&(i.title=l);this._setRequired(i,this.data.required);r&&(i.maxLength=r);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 blurListener=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(c){e.type=h;d&&(e.step=d)}if(o.userValue){const t=o.userValue;if(c)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-Bt).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??"";c||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};c&&(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){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let r=o.userValue;if(r&&!(r.length<=s)){r=r.slice(0,s);n.value=o.userValue=r;t.setValue(e,{value:r});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)});i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(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=blurListener;blurListener=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(c){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:r,selectionEnd:a}=s;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(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)}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;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)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{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;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");Lt.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:r}=s.target;for(const s of this._getElementsByName(n,i)){const i=r&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:r})});n.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue});if(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);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{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})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");Lt.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});if(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)}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{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");Lt.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;if(!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});for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(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 getValue=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 a=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",i=>{const n={value(i){r?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,r=i.detail.remove;n[r].selected=!1;s.remove(r);if(n.length>0){-1===Array.prototype.findIndex.call(n,t=>t.selected)&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});a=getValue(!1)},insert(i){const{index:n,displayValue:r,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=r;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!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");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!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:getValue(!0)});a=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)});s.addEventListener("input",i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,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)}else s.addEventListener("input",function(i){t.setValue(e,{value:getValue(!0)})});this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:s}=t,n=!!s._commentManager;super(t,{isRenderable:!n&&AnnotationElement._hasPopupData(e)});this.elements=i;if(n&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#fr();for(const e of i)e.popup=t}else this.popup=null}#fr(){return new PopupElement({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.#fr(),i=[];for(const t of this.elements){t.popup=e;t.container.ariaHasPopup="dialog";i.push(t.data.id);t.addHighlightArea()}this.container.setAttribute("aria-controls",i.map(t=>`${z}${t}`).join(","));return this.container}}class PopupElement{#U=null;#br=this.#nr.bind(this);#wr=this.#yr.bind(this);#Ar=this.#vr.bind(this);#xr=this.#Er.bind(this);#Cr=null;#vt=null;#_r=null;#Sr=null;#Tr=null;#Dr=null;#Mr=null;#kr=!1;#Pr=null;#Ir=null;#D=null;#Fr=null;#Rr=null;#pe=null;#Lr=null;#he=null;#Br=null;#hr=null;#Or=!1;#Nr=null;#Ur=null;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#vt=t;this.#Br=s;this.#_r=r;this.#he=a;this.#Dr=o;this.#Cr=e;this.#Lr=l;this.#Mr=h;this.#Tr=i;this.#U=c;this.#Nr=i[0];this.#Sr=PDFDateString.toDateObject(n);this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup());if(c)this.renderCommentButton();else{this.#Hr();this.#vt.hidden=!0;d&&this.#Er()}}#Hr(){if(this.#Ir)return;this.#Ir=new AbortController;const{signal:t}=this.#Ir;for(const e of this.trigger){e.addEventListener("click",this.#xr,{signal:t});e.addEventListener("pointerenter",this.#Ar,{signal:t});e.addEventListener("pointerleave",this.#wr,{signal:t});e.classList.add("popupTriggerArea")}for(const e of this.#Tr)e.container?.addEventListener("keydown",this.#br,{signal:t})}#zr(){const t=this.#Tr.find(t=>t.hasCommentButton);t&&(this.#Rr=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Fr)return;this.#Rr||this.#zr();if(!this.#Rr)return;const{signal:t}=this.#Ir=new AbortController,e=!!this.#Nr.extraPopupElement,togglePopup=()=>{this.#U.toggleCommentPopup(this,!0,void 0,!e)},showPopup=()=>{this.#U.toggleCommentPopup(this,!1,!0,!e)},hidePopup=()=>{this.#U.toggleCommentPopup(this,!1,!1)};if(e){this.#Fr=this.#Nr.container;for(const e of this.trigger){e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.addEventListener("keydown",this.#br,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});e.classList.add("popupTriggerArea")}}else{const e=this.#Fr=document.createElement("button");e.className="annotationCommentButton";const i=this.#Nr.container;e.style.zIndex=i.style.zIndex+1;e.tabIndex=0;e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.setAttribute("data-l10n-id","pdfjs-show-comment-button");this.#Gr();this.#Wr();e.addEventListener("keydown",this.#br,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});i.after(e)}}#Wr(){if(this.#Nr.extraPopupElement&&!this.#Nr.editor)return;this.renderCommentButton();const[t,e]=this.#Rr,{style:i}=this.#Fr;i.left=`calc(${t}%)`;i.top=`calc(${e}% - var(--comment-button-dim))`}#Gr(){if(!this.#Nr.extraPopupElement){this.renderCommentButton();this.#Fr.style.backgroundColor=this.commentButtonColor||""}}get commentButtonColor(){const{color:t,opacity:e}=this.#Nr.commentData;return t?this.#Dr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Fr?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}=this.#Nr.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:s,modificationDate:n}}get elementBeforePopup(){return this.#Fr}get comment(){this.#Ur||=this.#Nr.commentText;return this.#Ur}set comment(t){t!==this.comment&&(this.#Nr.commentText=this.#Ur=t)}get parentBoundingClientRect(){return this.#Nr.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#Fr){this.#Fr.classList.toggle("selected",t);this.#Fr.ariaExpanded=e}}setSelectedCommentButton(t){this.#Fr.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#pe)return this.#pe;const{x:t,y:e,height:i}=this.#Fr.getBoundingClientRect(),{x:s,y:n,width:r,height:a}=this.#Nr.layer.getBoundingClientRect();return[(t-s)/r,(e+i-n)/a]}set commentPopupPosition(t){this.#pe=t}hasDefaultPopupPosition(){return null===this.#pe}get commentButtonPosition(){return this.#Rr}get commentButtonWidth(){return this.#Fr.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#pe||this.commentButtonPosition.map(t=>t/100),s=this.parentBoundingClientRect,{x:n,y:r,width:a,height:o}=s;this.#U.showDialog(null,this,n+e*a,r+i*o,{...t,parentDimensions:s})}render(){if(this.#Pr)return;const t=this.#Pr=document.createElement("div");t.className="popup";if(this.#Cr){const e=t.style.outlineColor=Util.makeHexColor(...this.#Cr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";if(this.#Br?.str){const t=document.createElement("span");t.className="title";e.append(t);({dir:t.dir,str:t.textContent}=this.#Br)}t.append(e);if(this.#Sr){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.#Sr.valueOf()}));t.dateTime=this.#Sr.toISOString();e.append(t)}renderRichText({html:this.#Vr||this.#_r.str,dir:this.#_r?.dir,className:"popupContent"},t);this.#vt.append(t)}get#Vr(){const t=this.#he,e=this.#_r;return!t?.str||e?.str&&e.str!==t.str?null:this.#he.html||null}get#$r(){return this.#Vr?.attributes?.style?.fontSize||0}get#jr(){return this.#Vr?.attributes?.style?.color||null}#qr(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#jr,fontSize:this.#$r?`calc(${this.#$r}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}#nr(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#kr)&&this.#Er()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#U){if(i){this.remove();this.#Ur=null}else if(e)if(e.deleted)this.remove();else{this.#Gr();this.#Ur=e.text}if(t){this.#Rr=null;this.#zr();this.#Wr()}}else if(i||e?.deleted)this.remove();else{this.#Hr();this.#hr||={contentsObj:this.#_r,richText:this.#he};t&&(this.#D=null);if(e&&e.text){this.#he=this.#qr(e.text);this.#Sr=PDFDateString.toDateObject(e.date);this.#_r=null}this.#Pr?.remove();this.#Pr=null}}resetEdited(){if(this.#hr){({contentsObj:this.#_r,richText:this.#he}=this.#hr);this.#hr=null;this.#Pr?.remove();this.#Pr=null;this.#D=null}}remove(){this.#Ir?.abort();this.#Ir=null;this.#Pr?.remove();this.#Pr=null;this.#Or=!1;this.#kr=!1;this.#Fr?.remove();this.#Fr=null;if(this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Xr(){if(null!==this.#D)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:s,pageY:n}}}=this.#Dr;let r=!!this.#Mr,a=r?this.#Mr:this.#Lr;for(const t of this.#Tr)if(!a||null!==Util.intersect(t.data.rect,a)){a=t.data.rect;r=!0;break}const o=Util.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),l=r?a[2]-a[0]+5:0,h=o[0]+l,d=o[1];this.#D=[100*(h-s)/e,100*(d-n)/i];const{style:c}=this.#vt;c.left=`${this.#D[0]}%`;c.top=`${this.#D[1]}%`}#Er(){if(this.#U)this.#U.toggleCommentPopup(this,!1);else{this.#kr=!this.#kr;if(this.#kr){this.#vr();this.#vt.addEventListener("click",this.#xr);this.#vt.addEventListener("keydown",this.#br)}else{this.#yr();this.#vt.removeEventListener("click",this.#xr);this.#vt.removeEventListener("keydown",this.#br)}}}#vr(){this.#Pr||this.render();if(this.isVisible)this.#kr&&this.#vt.classList.add("focused");else{this.#Xr();this.#vt.hidden=!1;this.#vt.style.zIndex=parseInt(this.#vt.style.zIndex)+1e3}}#yr(){this.#vt.classList.remove("focused");if(!this.#kr&&this.isVisible){this.#vt.hidden=!0;this.#vt.style.zIndex=parseInt(this.#vt.style.zIndex)-1e3}}forceHide(){this.#Or=this.isVisible;this.#Or&&(this.#vt.hidden=!0)}maybeShow(){if(!this.#U){this.#Hr();if(this.#Or){this.#Pr||this.#vr();this.#Or=!1;this.#vt.hidden=!1}}}get isVisible(){return!this.#U&&!1===this.#vt.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=p.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=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)}!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#Kr=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.#Kr=this.svgFactory.createElement("svg:line");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._createPopup();return this.container}getElementsToTriggerPopup(){return this.#Kr}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Yr=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,r=this.#Yr=this.svgFactory.createElement("svg:rect");r.setAttribute("x",n/2);r.setAttribute("y",n/2);r.setAttribute("width",e-n);r.setAttribute("height",i-n);r.setAttribute("stroke-width",n||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");s.append(r);this.container.append(s);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#Yr}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#Qr=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,r=this.#Qr=this.svgFactory.createElement("svg:ellipse");r.setAttribute("cx",e/2);r.setAttribute("cy",i/2);r.setAttribute("rx",e/2-n/2);r.setAttribute("ry",i/2-n/2);r.setAttribute("stroke-width",n||1);r.setAttribute("stroke","transparent");r.setAttribute("fill","transparent");s.append(r);this.container.append(s);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#Qr}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#Jr=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:r}=this;if(!e)return this.container;const a=this.svgFactory.create(n,r,!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.#Jr=this.svgFactory.createElement(this.svgElementName);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._createPopup();return this.container}getElementsToTriggerPopup(){return this.#Jr}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t);this.containerClassName="polygonAnnotation";this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("caretAnnotation");!this.data.popupRef&&this.hasPopupData&&this._createPopup();return this.container}}class InkAnnotationElement extends AnnotationElement{#Zr=null;#ta=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="inkAnnotation";this.svgElementName="svg:polyline";this.annotationEditorType="InkHighlight"===this.data.it?p.HIGHLIGHT:p.INK}#ea(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:r,width:a,height:o}=this.#ea(e,t),l=this.svgFactory.create(a,o,!0),h=this.#Zr=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",r);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#ta.push(e);e.setAttribute("points",i[t].join(","));h.append(e)}!n&&this.hasPopupData&&this._createPopup();this.container.append(l);this._editOnDoubleClick();return this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:s}=t,n=this.#Zr;e>=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#ta.length;t<e;t++)this.#ta[t].setAttribute("points",i[t].join(","));if(s){const{transform:t,width:e,height:i}=this.#ea(this.data.rotation,s);n.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`);n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#ta}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0});this.annotationEditorType=p.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;!e&&this.hasPopupData&&this._createPopup();this.container.classList.add("highlightAnnotation");this._editOnDoubleClick();if(t){const e=document.createElement("mark");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;!e&&this.hasPopupData&&this._createPopup();this.container.classList.add("underlineAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;!e&&this.hasPopupData&&this._createPopup();this.container.classList.add("squigglyAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;!e&&this.hasPopupData&&this._createPopup();this.container.classList.add("strikeoutAnnotation");if(t){const e=document.createElement("s");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.annotationEditorType=p.STAMP}render(){this.container.classList.add("stampAnnotation");this.container.setAttribute("role","img");!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#ia=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;if(e.hasAppearance||0===e.fillAlpha)i=document.createElement("div");else{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.#sa.bind(this));this.#ia=i;const{isMac:s}=util_FeatureTest.platform;t.addEventListener("keydown",t=>{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#sa()});!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#ia}addHighlightArea(){this.container.classList.add("highlightArea")}#sa(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#na=null;#ra=null;#B=null;#aa=new Map;#oa=null;#la=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:r,structTreeLayer:a,commentManager:o,linkService:l,annotationStorage:h}){this.div=t;this.#na=e;this.#ra=i;this.#oa=a||null;this.#la=l||null;this.#B=h||new AnnotationStorage;this.page=n;this.viewport=r;this.zIndex=0;this._annotationEditorUIManager=s;this._commentManager=o||null}hasEditableAnnotations(){return this.#aa.size>0}async#ha(t,e,i){const s=t.firstChild||t,n=s.id=`${z}${e}`,r=await(this.#oa?.getAriaAttributes(n));if(r)for(const[t,e]of r)s.setAttribute(t,e);if(i)i.at(-1).container.after(t);else{this.div.append(t);this.#na?.moveElementInDOM(this.div,t,s,!1)}}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:this.#la,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#B,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===E.POPUP;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const r=i.render();t.hidden&&(r.style.visibility="hidden");await this.#ha(r,t.id,n.elements);i.extraPopupElement?.popup?.renderCommentButton();if(i._isEditable){this.#aa.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#da()}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#la,svgFactory:new DOMSVGFactory,parent:this};for(const i of t){i.borderStyle||=AnnotationLayer._defaultBorderStyle;e.data=i;const t=AnnotationElementFactory.create(e);if(!t.isRenderable)continue;const s=t.render();await this.#ha(s,i.id,null)}}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#da();e.hidden=!1}#da(){if(!this.#ra)return;const t=this.div;for(const[e,i]of this.#ra){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 r=this.#aa.get(e);if(r)if(r._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,s.id,i);r._hasNoCanvas=!1}else r.canvas=i}this.#ra.clear()}getEditableAnnotations(){return Array.from(this.#aa.values())}getEditableAnnotation(t){return this.#aa.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:s}=t,n=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:s},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#la,annotationStorage:this.#B}),r=n.render();e.append(r);this.#na?.moveElementInDOM(e,r,r,!1);n.createOrUpdatePopup();return n}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:C,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ot=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#ca="";#ua=`${this.id}-editor`;#pa=null;#$r;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["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:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=p.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#$r=t.fontSize||FreeTextEditor._defaultFontSize;this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert")}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case g.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case g.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case g.FREETEXT_SIZE:this.#ga(e);break;case g.FREETEXT_COLOR:this.#Gr(e)}}static get defaultPropertiesToUpdate(){return[[g.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[g.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[g.FREETEXT_SIZE,this.#$r],[g.FREETEXT_COLOR,this.color]]}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return g.FREETEXT_COLOR}#ga(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#$r)*this.parentScale);this.#$r=t;this.#ma()},e=this.#$r;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color;this._colorPicker?.update(this.color);super.onUpdatedColor()}#Gr(t){const setColor=t=>{this.color=t;this.onUpdatedColor()},e=this.color;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#$r)*t]}rebuild(){if(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.#pa=new AbortController;const t=this._uiManager.combinedSignal(this.#pa);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});return!0}disableEditMode(){if(!super.disableEditMode())return!1;this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#ua);this._isDraggable=!0;this.#pa?.abort();this.#pa=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing");return!0}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!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;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#fa(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#ba(i));e=i}return t.join("\n")}#ma(){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)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#ca,e=this.#ca=this.#fa().trimEnd();if(t===e)return;const setText=t=>{this.#ca=t;if(t){this.#wa();this._uiManager.rebuild(this);this.#ma()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#ma()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._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;if(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.#ua);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;i.fontSize=`calc(${this.#$r}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);if(this._isCopy||this.annotationElementId){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(n[0]-h)/o;u=e+this.height-(n[1]-d)/l;break;case 90:c=t+(n[0]-h)/o;u=e-(n[1]-d)/l;[r,a]=[a,-r];break;case 180:c=t-this.width+(n[0]-h)/o;u=e-(n[1]-d)/l;[r,a]=[-r,-a];break;case 270:c=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-d-this.width*o)/l;[r,a]=[-a,r]}this.setAt(c*i,u*s,r,a)}else this._moveAfterPaste(t,e);this.#wa();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#ba(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ot,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#ya(e.getData("text")||"").replaceAll(Ot,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const r=n.getRangeAt(0);if(!s.includes("\n")){r.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;h.push(a.nodeValue.slice(o).replaceAll(Ot,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#ba(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(Ot,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#ba(i))}}this.#ca=`${l.join("\n")}${s}${h.join("\n")}`;this.#wa();const d=new Range;let c=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(c<=e){d.setStart(t,c);d.setEnd(t,c);break}c-=e}n.removeAllRanges();n.addRange(d)}#wa(){this.editorDiv.replaceChildren();if(this.#ca)for(const t of this.#ca.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Aa(){return this.#ca.replaceAll(" "," ")}static#ya(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=FreeTextEditor._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:r,id:a,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:g,parent:{page:{pageNumber:m}}}=t;if(!u||0===u.length)return null;s=t={annotationType:p.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:g,pageIndex:m-1,rect:n.slice(0),rotation:r,annotationElementId:a,id:a,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}const n=await super.deserialize(t,e,i);n.#$r=t.fontSize;n.color=Util.makeHexColor(...t.color);n.#ca=FreeTextEditor.#ya(t.value);n._initialData=s;t.comment&&n.setCommentData(t);return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#$r,value:this.#Aa()});this.addComment(i);if(t){i.isCopy=!0;return i}if(this.annotationElementId&&!this.#va(i))return null;i.id=this.annotationElementId;return i}#va(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.#$r}px * var(--total-scale-factor))`;i.color=this.color;e.replaceChildren();for(const t of this.#ca.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#ca}});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2){r[a]=e+t[a]*s;r[a+1]=i+t[a+1]*n}return r}static _rescaleAndSwap(t,e,i,s,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a<o;a+=2){r[a]=e+t[a+1]*s;r[a+1]=i+t[a]*n}return r}static _translate(t,e,i,s){s||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;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 _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,s,n,r){return[(t+5*i)/6,(e+5*s)/6,(5*i+n)/6,(5*s+r)/6,(i+n)/2,(s+r)/2]}}class FreeDrawOutliner{#xa;#Ea=[];#Ca;#_a;#Sa=[];#Ta=new Float32Array(18);#Da;#Ma;#ka;#Pa;#Ia;#Fa;#Ra=[];static#La=8;static#Ba=2;static#Oa=FreeDrawOutliner.#La+FreeDrawOutliner.#Ba;constructor({x:t,y:e},i,s,n,r,a=0){this.#xa=i;this.#Fa=n*s;this.#_a=r;this.#Ta.set([NaN,NaN,NaN,NaN,t,e],6);this.#Ca=a;this.#Pa=FreeDrawOutliner.#La*s;this.#ka=FreeDrawOutliner.#Oa*s;this.#Ia=s;this.#Ra.push(t,e)}isEmpty(){return isNaN(this.#Ta[8])}#Na(){const t=this.#Ta.subarray(4,6),e=this.#Ta.subarray(16,18),[i,s,n,r]=this.#xa;return[(this.#Da+(t[0]-e[0])/2-i)/n,(this.#Ma+(t[1]-e[1])/2-s)/r,(this.#Da+(e[0]-t[0])/2-i)/n,(this.#Ma+(e[1]-t[1])/2-s)/r]}add({x:t,y:e}){this.#Da=t;this.#Ma=e;const[i,s,n,r]=this.#xa;let[a,o,l,h]=this.#Ta.subarray(8,12);const d=t-l,c=e-h,u=Math.hypot(d,c);if(u<this.#ka)return!1;const p=u-this.#Pa,g=p/u,m=g*d,f=g*c;let b=a,w=o;a=l;o=h;l+=m;h+=f;this.#Ra?.push(t,e);const y=m/p,A=-f/p*this.#Fa,v=y*this.#Fa;this.#Ta.set(this.#Ta.subarray(2,8),0);this.#Ta.set([l+A,h+v],4);this.#Ta.set(this.#Ta.subarray(14,18),12);this.#Ta.set([l-A,h-v],16);if(isNaN(this.#Ta[6])){if(0===this.#Sa.length){this.#Ta.set([a+A,o+v],2);this.#Sa.push(NaN,NaN,NaN,NaN,(a+A-i)/n,(o+v-s)/r);this.#Ta.set([a-A,o-v],14);this.#Ea.push(NaN,NaN,NaN,NaN,(a-A-i)/n,(o-v-s)/r)}this.#Ta.set([b,w,a,o,l,h],6);return!this.isEmpty()}this.#Ta.set([b,w,a,o,l,h],6);if(Math.abs(Math.atan2(w-o,b-a)-Math.atan2(f,m))<Math.PI/2){[a,o,l,h]=this.#Ta.subarray(2,6);this.#Sa.push(NaN,NaN,NaN,NaN,((a+l)/2-i)/n,((o+h)/2-s)/r);[a,o,b,w]=this.#Ta.subarray(14,18);this.#Ea.push(NaN,NaN,NaN,NaN,((b+a)/2-i)/n,((w+o)/2-s)/r);return!0}[b,w,a,o,l,h]=this.#Ta.subarray(0,6);this.#Sa.push(((b+5*a)/6-i)/n,((w+5*o)/6-s)/r,((5*a+l)/6-i)/n,((5*o+h)/6-s)/r,((a+l)/2-i)/n,((o+h)/2-s)/r);[l,h,a,o,b,w]=this.#Ta.subarray(12,18);this.#Ea.push(((b+5*a)/6-i)/n,((w+5*o)/6-s)/r,((5*a+l)/6-i)/n,((5*o+h)/6-s)/r,((a+l)/2-i)/n,((o+h)/2-s)/r);return!0}toSVGPath(){if(this.isEmpty())return"";const t=this.#Sa,e=this.#Ea;if(isNaN(this.#Ta[6])&&!this.isEmpty())return this.#Ua();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.#Ha(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]}`);this.#za(i);return i.join(" ")}#Ua(){const[t,e,i,s]=this.#xa,[n,r,a,o]=this.#Na();return`M${(this.#Ta[2]-t)/i} ${(this.#Ta[3]-e)/s} L${(this.#Ta[4]-t)/i} ${(this.#Ta[5]-e)/s} L${n} ${r} L${a} ${o} L${(this.#Ta[16]-t)/i} ${(this.#Ta[17]-e)/s} L${(this.#Ta[14]-t)/i} ${(this.#Ta[15]-e)/s} Z`}#za(t){const e=this.#Ea;t.push(`L${e[4]} ${e[5]} Z`)}#Ha(t){const[e,i,s,n]=this.#xa,r=this.#Ta.subarray(4,6),a=this.#Ta.subarray(16,18),[o,l,h,d]=this.#Na();t.push(`L${(r[0]-e)/s} ${(r[1]-i)/n} L${o} ${l} L${h} ${d} L${(a[0]-e)/s} ${(a[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,r){return new FreeDrawOutline(t,e,i,s,n,r)}getOutlines(){const t=this.#Sa,e=this.#Ea,i=this.#Ta,[s,n,r,a]=this.#xa,o=new Float32Array((this.#Ra?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2){o[t]=(this.#Ra[t]-s)/r;o[t+1]=(this.#Ra[t+1]-n)/a}o[o.length-2]=(this.#Da-s)/r;o[o.length-1]=(this.#Ma-n)/a;if(isNaN(i[6])&&!this.isEmpty())return this.#Ga(o);const l=new Float32Array(this.#Sa.length+24+this.#Ea.length);let h=t.length;for(let e=0;e<h;e+=2)if(isNaN(t[e]))l[e]=l[e+1]=NaN;else{l[e]=t[e];l[e+1]=t[e+1]}h=this.#Wa(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#Va(l,h);return this.newFreeDrawOutline(l,o,this.#xa,this.#Ia,this.#Ca,this.#_a)}#Ga(t){const e=this.#Ta,[i,s,n,r]=this.#xa,[a,o,l,h]=this.#Na(),d=new Float32Array(36);d.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/r,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/r,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/r],0);return this.newFreeDrawOutline(d,t,this.#xa,this.#Ia,this.#Ca,this.#_a)}#Va(t,e){const i=this.#Ea;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#Wa(t,e){const i=this.#Ta.subarray(4,6),s=this.#Ta.subarray(16,18),[n,r,a,o]=this.#xa,[l,h,d,c]=this.#Na();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o],e);return e+24}}class FreeDrawOutline extends Outline{#xa;#$a=new Float32Array(4);#Ca;#_a;#Ra;#Ia;#ja;constructor(t,e,i,s,n,r){super();this.#ja=t;this.#Ra=e;this.#xa=i;this.#Ia=s;this.#Ca=n;this.#_a=r;this.firstPoint=[NaN,NaN];this.lastPoint=[NaN,NaN];this.#qa(r);const[a,o,l,h]=this.#$a;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(){const t=[`M${this.#ja[4]} ${this.#ja[5]}`];for(let e=6,i=this.#ja.length;e<i;e+=6)isNaN(this.#ja[e])?t.push(`L${this.#ja[e+4]} ${this.#ja[e+5]}`):t.push(`C${this.#ja[e]} ${this.#ja[e+1]} ${this.#ja[e+2]} ${this.#ja[e+3]} ${this.#ja[e+4]} ${this.#ja[e+5]}`);t.push("Z");return t.join(" ")}serialize([t,e,i,s],n){const r=i-t,a=s-e;let o,l;switch(n){case 0:o=Outline._rescale(this.#ja,t,s,r,-a);l=Outline._rescale(this.#Ra,t,s,r,-a);break;case 90:o=Outline._rescaleAndSwap(this.#ja,t,e,r,a);l=Outline._rescaleAndSwap(this.#Ra,t,e,r,a);break;case 180:o=Outline._rescale(this.#ja,i,e,-r,a);l=Outline._rescale(this.#Ra,i,e,-r,a);break;case 270:o=Outline._rescaleAndSwap(this.#ja,i,s,-r,-a);l=Outline._rescaleAndSwap(this.#Ra,i,s,-r,-a)}return{outline:Array.from(o),points:[Array.from(l)]}}#qa(t){const e=this.#ja;let i=e[4],s=e[5];const n=[i,s,i,s];let r=i,a=s,o=i,l=s;const h=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,c=e.length;t<c;t+=6){const c=e[t+4],u=e[t+5];if(isNaN(e[t])){Util.pointBoundingBox(c,u,n);if(a>u){r=c;a=u}else a===u&&(r=h(r,c));if(l<u){o=c;l=u}else l===u&&(o=h(o,c))}else{d[0]=d[1]=1/0;d[2]=d[3]=-1/0;Util.bezierBoundingBox(i,s,...e.slice(t,t+6),d);Util.rectBoundingBox(d[0],d[1],d[2],d[3],n);if(a>d[1]){r=d[0];a=d[1]}else a===d[1]&&(r=h(r,d[0]));if(l<d[3]){o=d[2];l=d[3]}else l===d[3]&&(o=h(o,d[2]))}i=c;s=u}const c=this.#$a;c[0]=n[0]-this.#Ca;c[1]=n[1]-this.#Ca;c[2]=n[2]-n[0]+2*this.#Ca;c[3]=n[3]-n[1]+2*this.#Ca;this.firstPoint=[r,a];this.lastPoint=[o,l]}get box(){return this.#$a}newOutliner(t,e,i,s,n,r=0){return new FreeDrawOutliner(t,e,i,s,n,r)}getNewOutline(t,e){const[i,s,n,r]=this.#$a,[a,o,l,h]=this.#xa,d=n*l,c=r*h,u=i*l+a,p=s*h+o,g=this.newOutliner({x:this.#Ra[0]*d+u,y:this.#Ra[1]*c+p},this.#xa,this.#Ia,t,this.#_a,e??this.#Ca);for(let t=2;t<this.#Ra.length;t+=2)g.add({x:this.#Ra[t]*d+u,y:this.#Ra[t+1]*c+p});return g.getOutlines()}}class HighlightOutliner{#xa;#Xa;#Ka;#Ya=[];#Qa=[];constructor(t,e=0,i=0,s=!0){const n=[1/0,1/0,-1/0,-1/0],r=10**-4;for(const{x:i,y:s,width:a,height:o}of t){const t=Math.floor((i-e)/r)*r,l=Math.ceil((i+a+e)/r)*r,h=Math.floor((s-e)/r)*r,d=Math.ceil((s+o+e)/r)*r,c=[t,h,d,!0],u=[l,h,d,!1];this.#Ya.push(c,u);Util.rectBoundingBox(t,h,l,d,n)}const a=n[2]-n[0]+2*i,o=n[3]-n[1]+2*i,l=n[0]-i,h=n[1]-i;let d=s?-1/0:1/0,c=1/0;const u=this.#Ya.at(s?-1:-2),p=[u[0],u[2]];for(const t of this.#Ya){const[e,i,n,r]=t;if(!r&&s)if(i<c){c=i;d=e}else i===c&&(d=Math.max(d,e));else if(r&&!s)if(i<c){c=i;d=e}else i===c&&(d=Math.min(d,e));t[0]=(e-l)/a;t[1]=(i-h)/o;t[2]=(n-h)/o}this.#xa=new Float32Array([l,h,a,o]);this.#Xa=[d,c];this.#Ka=p}getOutlines(){this.#Ya.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Ya)if(e[3]){t.push(...this.#Ja(e));this.#Za(e)}else{this.#to(e);t.push(...this.#Ja(e))}return this.#eo(t)}#eo(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,r,a,o,l]=t;i.delete(t);let h=e,d=r;n=[e,a];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,r,a,o,l]=t;if(h!==e){n.push(h,d,e,d===r?r:a);h=e}d=d===r?a:r}n.push(h,d)}return new HighlightOutline(s,this.#xa,this.#Xa,this.#Ka)}#io(t){const e=this.#Qa;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,r=e[n][0];if(r===t)return n;r<t?i=n+1:s=n-1}return s+1}#Za([,t,e]){const i=this.#io(t);this.#Qa.splice(i,0,[t,e])}#to([,t,e]){const i=this.#io(t);for(let s=i;s<this.#Qa.length;s++){const[i,n]=this.#Qa[s];if(i!==t)break;if(i===t&&n===e){this.#Qa.splice(s,1);return}}for(let s=i-1;s>=0;s--){const[i,n]=this.#Qa[s];if(i!==t)break;if(i===t&&n===e){this.#Qa.splice(s,1);return}}}#Ja(t){const[e,i,s]=t,n=[[e,i,s]],r=this.#io(s);for(let t=0;t<r;t++){const[i,s]=this.#Qa[t];for(let t=0,r=n.length;t<r;t++){const[,a,o]=n[t];if(!(s<=a||o<=i))if(a>=i)if(o>s)n[t][1]=s;else{if(1===r)return[];n.splice(t,1);t--;r--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#xa;#so;constructor(t,e,i,s){super();this.#so=t;this.#xa=e;this.firstPoint=i;this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#so){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];if(r===i){t.push(`V${a}`);s=a}else if(a===s){t.push(`H${r}`);i=r}}t.push("Z")}return t.join(" ")}serialize([t,e,i,s],n){const r=[],a=i-t,o=s-e;for(const e of this.#so){const i=new Array(e.length);for(let n=0;n<e.length;n+=2){i[n]=t+e[n]*a;i[n+1]=s-e[n+1]*o}r.push(i)}return r}get box(){return this.#xa}get classNamesForOutlining(){return["highlightOutline"]}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,i,s,n,r){return new FreeHighlightOutline(t,e,i,s,n,r)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,i,s,n,r=0){return new FreeHighlightOutliner(t,e,i,s,n,r)}}class HighlightEditor extends AnnotationEditor{#no=null;#ro=0;#ao;#oo=null;#n=null;#lo=null;#ho=null;#do=0;#co=null;#uo=null;#v=null;#po=!1;#Xa=null;#Ka=null;#go=null;#de="";#Fa;#mo="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=p.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=HighlightEditor.prototype;return shadow(this,"_keyboardManager",new KeyboardManager([[["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||HighlightEditor._defaultColor;this.#Fa=t.thickness||HighlightEditor._defaultThickness;this.opacity=t.opacity||HighlightEditor._defaultOpacity;this.#ao=t.boxes||null;this.#mo=t.methodOfCreation||"";this.#de=t.text||"";this._isDraggable=!1;this.defaultL10nId="pdfjs-editor-highlight-editor";if(t.highlightId>-1){this.#po=!0;this.#fo(t);this.#bo()}else if(this.#ao){this.#no=t.anchorNode;this.#ro=t.anchorOffset;this.#ho=t.focusNode;this.#do=t.focusOffset;this.#wo();this.#bo();this.rotate(this.rotation)}this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#po?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#Fa,methodOfCreation:this.#mo}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#wo(){const t=new HighlightOutliner(this.#ao,.001);this.#uo=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#uo.box;const e=new HighlightOutliner(this.#ao,.0025,.001,"ltr"===this._uiManager.direction);this.#lo=e.getOutlines();const{firstPoint:i}=this.#uo;this.#Xa=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:s}=this.#lo;this.#Ka=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#fo({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#uo=t;this.#lo=t.getNewOutline(this.#Fa/2+1.5,.0025);if(e>=0){this.#v=e;this.#oo=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#go=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#v,{bbox:HighlightEditor.#yo(this.#uo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#go,{bbox:HighlightEditor.#yo(this.#lo.box,e),path:{d:this.#lo.toSVGPath()}})}const[s,n,r,a]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=r;this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=r*e/t;this.height=a*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=r;this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=r*e/t;this.height=a*t/e;break}}const{firstPoint:o}=t;this.#Xa=[(o[0]-s)/r,(o[1]-n)/a];const{lastPoint:l}=this.#lo;this.#Ka=[(l[0]-s)/r,(l[1]-n)/a]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case g.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Ka}get commentButtonPosition(){return this.#Xa}updateParams(t,e){switch(t){case g.HIGHLIGHT_COLOR:this.#Gr(e);break;case g.HIGHLIGHT_THICKNESS:this.#Ao(e)}}static get defaultPropertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[g.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[g.HIGHLIGHT_THICKNESS,this.#Fa||HighlightEditor._defaultThickness],[g.HIGHLIGHT_FREE,this.#po]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#v,{root:{fill:this.color,"fill-opacity":this.opacity}});this.#n?.updateColor(this.color);super.onUpdatedColor()}#Gr(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.opacity=e;this.onUpdatedColor()},e=this.color,i=this.opacity;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Ao(t){const e=this.#Fa,setThickness=t=>{this.#Fa=t;this.#vo(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:g.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#n=new ColorPicker({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.#xo())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#xo())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#Eo();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#bo();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#Eo();else if(t){this.#bo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#vo(t){if(this.#po){this.#fo({highlightOutlines:this.#uo.getNewOutline(t/2)});this.fixAndSetPosition();this.setDims(this.width,this.height)}}#Eo(){if(null!==this.#v&&this.parent){this.parent.drawLayer.remove(this.#v);this.#v=null;this.parent.drawLayer.remove(this.#go);this.#go=null}}#bo(t=this.parent){if(null===this.#v){({id:this.#v,clipPathId:this.#oo}=t.drawLayer.draw({bbox:this.#uo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#po},path:{d:this.#uo.toSVGPath()}},!1,!0));this.#go=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#po},bbox:this.#lo.box,path:{d:this.#lo.toSVGPath()}},this.#po);this.#co&&(this.#co.style.clipPath=this.#oo)}}static#yo([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;if(this.#po){t=(t-this.rotation+360)%360;i=HighlightEditor.#yo(this.#uo.box,t)}else i=HighlightEditor.#yo([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#v,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#go,{bbox:HighlightEditor.#yo(this.#lo.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#de){t.setAttribute("aria-label",this.#de);t.setAttribute("role","mark")}this.#po?t.classList.add("free"):this.div.addEventListener("keydown",this.#Co.bind(this),{signal:this._uiManager._signal});const e=this.#co=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#oo;this.setDims(this.width,this.height);bindEvents(this,this.#co,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1}})}#Co(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#_o(!0);break;case 1:case 3:this.#_o(!1)}}#_o(t){if(!this.#no)return;const e=window.getSelection();t?e.setPosition(this.#no,this.#ro):e.setPosition(this.#ho,this.#do)}select(){super.select();this.#go&&this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#go){this.parent?.drawLayer.updateProperties(this.#go,{rootClass:{selected:!1}});this.#po||this.#_o(!1)}}get _mustFixPosition(){return!this.#po}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#v,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#go,{rootClass:{hidden:!t}})}}#xo(){return this.#po?this.rotation:0}#So(){if(this.#po)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#ao,r=new Float32Array(8*n.length);let a=0;for(const{x:o,y:l,width:h,height:d}of n){const n=o*t+i,c=(1-l)*e+s;r[a]=r[a+4]=n;r[a+1]=r[a+3]=c;r[a+2]=r[a+6]=n+h*t;r[a+5]=r[a+7]=c-d*e;a+=8}return r}#To(t){return this.#uo.serialize(t,this.#xo())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#Do(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:d});window.addEventListener("pointerup",pointerUpCallback,{signal:d});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d});window.addEventListener("contextmenu",noContextMenu,{signal:d});i.addEventListener("pointermove",this.#Mo.bind(this,t),{signal:d});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[r,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#Mo(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#Do(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 HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:r,color:a,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;s=t={annotationType:p.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:g}}}=t;s=t={annotationType:p.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}const{color:n,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.opacity=o||1;a&&(l.#Fa=t.thickness);l._initialData=s;t.comment&&l.setCommentData(t);const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(r){const t=l.#ao=[];for(let e=0;e<r.length;e+=8)t.push({x:(r[e]-c)/h,y:1-(r[e+1]-u)/d,width:(r[e+2]-r[e])/h,height:(r[e+1]-r[e+5])/d});l.#wo();l.#bo();l.rotate(l.rotation)}else if(a){l.#po=!0;const t=a[0],i={x:t[0]-c,y:d-(t[1]-u)},s=new FreeHighlightOutliner(i,[0,0,h,d],1,l.#Fa/2,!0,.001);for(let e=0,n=t.length;e<n;e+=2){i.x=t[e]-c;i.y=d-(t[e+1]-u);s.add(i)}const{id:n,clipPathId:r}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:s.toSVGPath()}},!0,!0);l.#fo({highlightOutlines:s.getOutlines(),highlightId:n,clipPathId:r});l.#bo();l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#Fa,quadPoints:this.#So(),outlines:this.#To(i.rect)});this.addComment(i);if(this.annotationElementId&&!this.#va(i))return null;i.id=this.annotationElementId;return i}#va(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#ko=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.#ko[t]=e}toSVGProperties(){const t=this.#ko;this.#ko=Object.create(null);return{root:t}}reset(){this.#ko=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#Po=null;#Io;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Fo=null;static#Ro=null;static#Lo=null;static#Bo=NaN;static#Oo=null;static#No=null;static#Uo=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#Io=t.mustBeCommitted||!1;this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color);super.onUpdatedColor()}_addOutlines(t){if(t.drawOutlines){this.#Ho(t);this.#bo()}}#Ho({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Po=t;this._drawingOptions||=i;this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`);if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#zo(t,this.parent);this.#Go(t.box)}#zo(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._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){unreachable("Not implemented")}static get typesMap(){unreachable("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);if(this._currentParent){DrawingEditor.#Fo.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],setter=i=>{s.updateProperty(e,i);const n=this.#Po.updateProperty(e,i);n&&this.#Go(n);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties());t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Po.getPathResizingSVGProperties(this.#Wo()),{bbox:this.#Vo()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Po.getPathResizedSVGProperties(this.#Wo()),{bbox:this.#Vo()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Vo()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Po.getPathTranslatedSVGProperties(this.#Wo(),this.parentDimensions),{bbox:this.#Vo()}))}_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;if(this.#Io){this.#Io=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#Eo();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#bo();this.#Go(this.#Po.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#Eo()}else if(t){this._uiManager.addShouldRescale(this);this.#bo(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#Eo(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#bo(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#zo(this.#Po,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#$o([t,e,i,s]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/n),s*(n/r)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(r/n),s*(n/r)];default:return[t,e,i,s]}}#Wo(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(n/r),s*(r/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/r),s*(r/n)];default:return[t,e,i,s]}}#Go(t){[this.x,this.y,this.width,this.height]=this.#$o(t);if(this.div){this.fixAndSetPosition();this.setDims()}this._onResized()}#Vo(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*n+r)/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,DrawingEditor._mergeSVGProperties({bbox:this.#Vo()},this.#Po.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Go(this.#Po.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}const i=super.render();i.classList.add("draw");const s=document.createElement("div");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);return i}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=s;if(DrawingEditor.#Oo&&DrawingEditor.#Oo!==l)return;const{viewport:{rotation:h}}=t,{width:d,height:c}=n.getBoundingClientRect(),u=DrawingEditor.#Ro=new AbortController,p=t.combinedSignal(u);DrawingEditor.#Bo||=o;DrawingEditor.#Oo??=l;window.addEventListener("pointerup",t=>{DrawingEditor.#Bo===t.pointerId?this._endDraw(t):DrawingEditor.#No?.delete(t.pointerId)},{signal:p});window.addEventListener("pointercancel",t=>{DrawingEditor.#Bo===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#No?.delete(t.pointerId)},{signal:p});window.addEventListener("pointerdown",t=>{if(DrawingEditor.#Oo===t.pointerType){(DrawingEditor.#No||=new Set).add(t.pointerId);if(DrawingEditor.#Fo.isCancellable()){DrawingEditor.#Fo.removeLastElement();DrawingEditor.#Fo.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}},{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",t=>{t.timeStamp===DrawingEditor.#Uo&&stopEvent(t)},{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#Fo)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Fo.startNew(r,a,d,c,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#Fo=this.createDrawerInstance(r,a,d,c,h);DrawingEditor.#Lo=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Lo.toSVGProperties(),DrawingEditor.#Fo.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#Uo=-1;if(!DrawingEditor.#Fo)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#Bo===s)if(DrawingEditor.#No?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Fo.add(e,i));DrawingEditor.#Uo=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#Fo=null;DrawingEditor.#Lo=null;DrawingEditor.#Oo=null;DrawingEditor.#Uo=NaN}if(DrawingEditor.#Ro){DrawingEditor.#Ro.abort();DrawingEditor.#Ro=null;DrawingEditor.#Bo=NaN;DrawingEditor.#No=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Fo.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#Fo,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:g.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(g.DRAW_STEP);if(!DrawingEditor.#Fo.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#Fo.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Lo,mustBeCommitted:!t});this._cleanup(!0);return r}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,r){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#Ho({drawOutlines:o});l.#bo();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#Po.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getPDFRect()});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Ta=new Float64Array(6);#Kr;#jo;#sn;#Fa;#Ra;#qo="";#Xo=0;#so=new InkDrawOutline;#Ko;#Yo;constructor(t,e,i,s,n,r){this.#Ko=i;this.#Yo=s;this.#sn=n;this.#Fa=r;[t,e]=this.#Qo(t,e);const a=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#Ra=[t,e];this.#jo=[{line:a,points:this.#Ra}];this.#Ta.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#Fa=e)}#Qo(t,e){return Outline._normalizePoint(t,e,this.#Ko,this.#Yo,this.#sn)}isEmpty(){return!this.#jo||0===this.#jo.length}isCancellable(){return this.#Ra.length<=10}add(t,e){[t,e]=this.#Qo(t,e);const[i,s,n,r]=this.#Ta.subarray(2,6),a=t-n,o=e-r;if(Math.hypot(this.#Ko*a,this.#Yo*o)<=2)return null;this.#Ra.push(t,e);if(isNaN(i)){this.#Ta.set([n,r,t,e],2);this.#Kr.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Ta[0])&&this.#Kr.splice(6,6);this.#Ta.set([i,s,n,r,t,e],0);this.#Kr.push(...Outline.createBezierPoints(i,s,n,r,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#Ra.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Ko=i;this.#Yo=s;this.#sn=n;[t,e]=this.#Qo(t,e);const r=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#Ra=[t,e];const a=this.#jo.at(-1);if(a){a.line=new Float32Array(a.line);a.points=new Float32Array(a.points)}this.#jo.push({line:r,points:this.#Ra});this.#Ta.set(r,0);this.#Xo=0;this.toSVGPath();return null}getLastElement(){return this.#jo.at(-1)}setLastElement(t){if(!this.#jo)return this.#so.setLastElement(t);this.#jo.push(t);this.#Kr=t.line;this.#Ra=t.points;this.#Xo=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#jo)return this.#so.removeLastElement();this.#jo.pop();this.#qo="";for(let t=0,e=this.#jo.length;t<e;t++){const{line:e,points:i}=this.#jo[t];this.#Kr=e;this.#Ra=i;this.#Xo=0;this.toSVGPath()}return{path:{d:this.#qo}}}toSVGPath(){const t=Outline.svgRound(this.#Kr[4]),e=Outline.svgRound(this.#Kr[5]);if(2===this.#Ra.length){this.#qo=`${this.#qo} M ${t} ${e} Z`;return this.#qo}if(this.#Ra.length<=6){const i=this.#qo.lastIndexOf("M");this.#qo=`${this.#qo.slice(0,i)} M ${t} ${e}`;this.#Xo=6}if(4===this.#Ra.length){const t=Outline.svgRound(this.#Kr[10]),e=Outline.svgRound(this.#Kr[11]);this.#qo=`${this.#qo} L ${t} ${e}`;this.#Xo=12;return this.#qo}const i=[];if(0===this.#Xo){i.push(`M ${t} ${e}`);this.#Xo=6}for(let t=this.#Xo,e=this.#Kr.length;t<e;t+=6){const[e,s,n,r,a,o]=this.#Kr.slice(t,t+6).map(Outline.svgRound);i.push(`C${e} ${s} ${n} ${r} ${a} ${o}`)}this.#qo+=i.join(" ");this.#Xo=this.#Kr.length;return this.#qo}getOutlines(t,e,i,s){const n=this.#jo.at(-1);n.line=new Float32Array(n.line);n.points=new Float32Array(n.points);this.#so.build(this.#jo,t,e,i,this.#sn,this.#Fa,s);this.#Ta=null;this.#Kr=null;this.#jo=null;this.#qo=null;return this.#so}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#$a;#Jo=0;#Ca;#jo;#Ko;#Yo;#Zo;#sn;#Fa;build(t,e,i,s,n,r,a){this.#Ko=e;this.#Yo=i;this.#Zo=s;this.#sn=n;this.#Fa=r;this.#Ca=a??0;this.#jo=t;this.#tl()}get thickness(){return this.#Fa}setLastElement(t){this.#jo.push(t);return{path:{d:this.toSVGPath()}}}removeLastElement(){this.#jo.pop();return{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#jo){t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`);if(6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else for(let i=6,s=e.length;i<s;i+=6){const[s,n,r,a,o,l]=e.subarray(i,i+6).map(Outline.svgRound);t.push(`C${s} ${n} ${r} ${a} ${o} ${l}`)}else t.push("Z")}return t.join("")}serialize([t,e,i,s],n){const r=[],a=[],[o,l,h,d]=this.#el();let c,u,p,g,m,f,b,w,y;switch(this.#sn){case 0:y=Outline._rescale;c=t;u=e+s;p=i;g=-s;m=t+o*i;f=e+(1-l-d)*s;b=t+(o+h)*i;w=e+(1-l)*s;break;case 90:y=Outline._rescaleAndSwap;c=t;u=e;p=i;g=s;m=t+l*i;f=e+o*s;b=t+(l+d)*i;w=e+(o+h)*s;break;case 180:y=Outline._rescale;c=t+i;u=e;p=-i;g=s;m=t+(1-o-h)*i;f=e+l*s;b=t+(1-o)*i;w=e+(l+d)*s;break;case 270:y=Outline._rescaleAndSwap;c=t+i;u=e+s;p=-i;g=-s;m=t+(1-l-d)*i;f=e+(1-o-h)*s;b=t+(1-l)*i;w=e+(1-o)*s}for(const{line:t,points:e}of this.#jo){r.push(y(t,c,u,p,g,n?new Array(t.length):null));a.push(y(e,c,u,p,g,n?new Array(e.length):null))}return{lines:r,points:a,rect:[m,f,b,w]}}static deserialize(t,e,i,s,n,{paths:{lines:r,points:a},rotation:o,thickness:l}){const h=[];let d,c,u,p,g;switch(o){case 0:g=Outline._rescale;d=-t/i;c=e/s+1;u=1/i;p=-1/s;break;case 90:g=Outline._rescaleAndSwap;d=-e/s;c=-t/i;u=1/s;p=1/i;break;case 180:g=Outline._rescale;d=t/i+1;c=-e/s;u=-1/i;p=1/s;break;case 270:g=Outline._rescaleAndSwap;d=e/s+1;c=t/i+1;u=-1/s;p=-1/i}if(!r){r=[];for(const t of a){const e=t.length;if(2===e){r.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){r.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));r.push(i);let[s,n,a,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,s,n],0);for(let r=4;r<e;r+=2){const e=t[r],l=t[r+1];i.set(Outline.createBezierPoints(s,n,a,o,e,l),3*(r-2));[s,n,a,o]=[a,o,e,l]}}}for(let t=0,e=r.length;t<e;t++)h.push({line:g(r[t].map(t=>t??NaN),d,c,u,p),points:g(a[t].map(t=>t??NaN),d,c,u,p)});const m=new this.prototype.constructor;m.build(h,i,s,1,o,l,n);return m}#il(t=this.#Fa){const e=this.#Ca+t/2*this.#Zo;return this.#sn%180==0?[e/this.#Ko,e/this.#Yo]:[e/this.#Yo,e/this.#Ko]}#el(){const[t,e,i,s]=this.#$a,[n,r]=this.#il(0);return[t+n,e+r,i-2*n,s-2*r]}#tl(){const t=this.#$a=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#jo){if(e.length<=12){for(let i=4,s=e.length;i<s;i+=6)Util.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],s=e[5];for(let n=6,r=e.length;n<r;n+=6){const[r,a,o,l,h,d]=e.subarray(n,n+6);Util.bezierBoundingBox(i,s,r,a,o,l,h,d,t);i=h;s=d}}const[e,i]=this.#il();t[0]=MathClamp(t[0]-e,0,1);t[1]=MathClamp(t[1]-i,0,1);t[2]=MathClamp(t[2]+e,0,1);t[3]=MathClamp(t[3]+i,0,1);t[2]-=t[0];t[3]-=t[1]}get box(){return this.#$a}updateProperty(t,e){return"stroke-width"===t?this.#Ao(e):null}#Ao(t){const[e,i]=this.#il();this.#Fa=t;const[s,n]=this.#il(),[r,a]=[s-e,n-i],o=this.#$a;o[0]-=r;o[1]-=a;o[2]+=2*r;o[3]+=2*a;return o}updateParentDimensions([t,e],i){const[s,n]=this.#il();this.#Ko=t;this.#Yo=e;this.#Zo=i;const[r,a]=this.#il(),o=r-s,l=a-n,h=this.#$a;h[0]-=o;h[1]-=l;h[2]+=2*o;h[3]+=2*l;return h}updateRotation(t){this.#Jo=t;return{path:{transform:this.rotationTransform}}}get viewBox(){return this.#$a.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#$a;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#$a;let i=0,s=0,n=0,r=0,a=0,o=0;switch(this.#Jo){case 90:s=e/t;n=-t/e;a=t;break;case 180:i=-1;r=-1;a=t;o=e;break;case 270:s=-e/t;n=t/e;o=e;break;default:return""}return`matrix(${i} ${s} ${n} ${r} ${Outline.svgRound(a)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,s]){const[n,r]=this.#il(),[a,o,l,h]=this.#$a;if(Math.abs(l-n)<=Outline.PRECISION||Math.abs(h-r)<=Outline.PRECISION){const n=t+i/2-(a+l/2),r=e+s/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${r})`}}}const d=(i-2*n)/(l-2*n),c=(s-2*r)/(h-2*r),u=l/i,p=h/s;return{path:{"transform-origin":`${Outline.svgRound(a)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(n)} ${Outline.svgRound(r)}) scale(${d} ${c}) translate(${Outline.svgRound(-n)} ${Outline.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,i,s]){const[n,r]=this.#il(),a=this.#$a,[o,l,h,d]=a;a[0]=t;a[1]=e;a[2]=i;a[3]=s;if(Math.abs(h-n)<=Outline.PRECISION||Math.abs(d-r)<=Outline.PRECISION){const n=t+i/2-(o+h/2),r=e+s/2-(l+d/2);for(const{line:t,points:e}of this.#jo){Outline._translate(t,n,r,t);Outline._translate(e,n,r,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const c=(i-2*n)/(h-2*n),u=(s-2*r)/(d-2*r),p=-c*(o+n)+t+n,g=-u*(l+r)+e+r;if(1!==c||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#jo){Outline._rescale(t,p,g,c,u,t);Outline._rescale(e,p,g,c,u,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[s,n]=i,r=this.#$a,a=t-r[0],o=e-r[1];if(this.#Ko===s&&this.#Yo===n)for(const{line:t,points:e}of this.#jo){Outline._translate(t,a,o,t);Outline._translate(e,a,o,e)}else{const t=this.#Ko/s,e=this.#Yo/n;this.#Ko=s;this.#Yo=n;for(const{line:i,points:s}of this.#jo){Outline._rescale(i,a,o,t,e,i);Outline._rescale(s,a,o,t,e,s)}r[2]*=t;r[3]*=e}r[0]=t;r[1]=e;return{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#$a;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{constructor(t){super();this._viewParameters=t;super.updateProperties({fill:"none",stroke:AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){if("stroke-width"===t){e??=this["stroke-width"];e*=this._viewParameters.realScale}super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this._viewParameters);t.updateAll(this);return t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=p.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"});this._willKeepAspectRatio=!0;this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!0}static get typesMap(){return shadow(this,"typesMap",new Map([[g.INK_THICKNESS,"stroke-width"],[g.INK_COLOR,"stroke"],[g.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,s,n){return new InkDrawOutliner(t,e,i,s,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,s,n,r){return InkDrawOutline.deserialize(t,e,i,s,n,r)}static async deserialize(t,e,i){let s=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:r,color:a,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:g},parent:{page:{pageNumber:m}}}=t;s=t={annotationType:p.INK,color:Array.from(a),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:m-1,rect:i.slice(0),rotation:n,annotationElementId:r,id:r,deleted:!1,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:g}}const n=await super.deserialize(t,e,i);n._initialData=s;t.comment&&n.setCommentData(t);return n}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return g.INK_COLOR}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;if(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=InkEditor.getDefaultDrawingOptions({stroke:Util.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":r}}=this,a=Object.assign(super.serialize(t),{color:AnnotationEditor._colorManager.convert(s),opacity:n,thickness:r,paths:{lines:e,points:i}});this.addComment(a);if(t){a.isCopy=!0;return a}if(this.annotationElementId&&!this.#va(a))return null;a.id=this.annotationElementId;return a}#va(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){t.hide();return null}const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment});return null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();t.endsWith("Z")||(t+="Z");return t}}class SignatureExtractor{static#sl={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#nl(t,e,i,s){s-=e;return 0===(i-=t)?s>0?0:4:1===i?s+6:2-s}static#rl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#al(t,e,i,s,n,r,a){const o=this.#nl(i,s,n,r);for(let n=0;n<8;n++){const r=(-n+o-a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(s+this.#rl[2*r+1])])return r}return-1}static#ol(t,e,i,s,n,r,a){const o=this.#nl(i,s,n,r);for(let n=0;n<8;n++){const r=(n+o+a+16)%8;if(0!==t[(i+this.#rl[2*r])*e+(s+this.#rl[2*r+1])])return r}return-1}static#ll(t,e,i,s){const n=t.length,r=new Int32Array(n);for(let e=0;e<n;e++)r[e]=t[e]<=s?1:0;for(let t=1;t<i-1;t++)r[t*e]=r[t*e+e-1]=0;for(let t=0;t<e;t++)r[t]=r[e*i-1-t]=0;let a,o=1;const l=[];for(let t=1;t<i-1;t++){a=1;for(let i=1;i<e-1;i++){const s=t*e+i,n=r[s];if(0===n)continue;let h=t,d=i;if(1===n&&0===r[s-1]){o+=1;d-=1}else{if(!(n>=1&&0===r[s+1])){1!==n&&(a=Math.abs(n));continue}o+=1;d+=1;n>1&&(a=n)}const c=[i,t],u=d===i+1,p={isHole:u,points:c,id:o,parent:0};l.push(p);let g;for(const t of l)if(t.id===a){g=t;break}g?g.isHole?p.parent=u?g.parent:a:p.parent=u?a:g.parent:p.parent=u?a:0;const m=this.#al(r,e,t,i,h,d,0);if(-1===m){r[s]=-o;1!==r[s]&&(a=Math.abs(r[s]));continue}let f=this.#rl[2*m],b=this.#rl[2*m+1];const w=t+f,y=i+b;h=w;d=y;let A=t,v=i;for(;;){const n=this.#ol(r,e,A,v,h,d,1);f=this.#rl[2*n];b=this.#rl[2*n+1];const l=A+f,u=v+b;c.push(u,l);const p=A*e+v;0===r[p+1]?r[p]=-o:1===r[p]&&(r[p]=o);if(l===t&&u===i&&A===w&&v===y){1!==r[s]&&(a=Math.abs(r[s]));break}h=A;d=v;A=l;v=u}}}return l}static#hl(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],r=t[e+1],a=t[i-4]-n,o=t[i-3]-r,l=Math.hypot(a,o),h=a/l,d=o/l,c=h*r-d*n,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)),w=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*w),Math.atan(Math.abs(f-m)*w));let A=0,v=e;for(let s=e+2;s<i-2;s+=2){const e=Math.abs(c-h*t[s+1]+d*t[s]);if(e>A){v=s;A=e}}if(A>(l*y)**2){this.#hl(t,e,v+2,s);this.#hl(t,v,i,s)}else s.push(n,r)}static#dl(t){const e=[],i=t.length;this.#hl(t,0,i,e);e.push(t[i-2],t[i-1]);return e.length<=4?null:e}static#cl(t,e,i,s,n,r){const a=new Float32Array(r**2),o=-2*s**2,l=r>>1;for(let t=0;t<r;t++){const e=(t-l)**2;for(let i=0;i<r;i++)a[t*r+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),d=-2*n**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/d);const c=t.length,u=new Uint8Array(c),p=new Uint32Array(256);for(let s=0;s<i;s++)for(let n=0;n<e;n++){const o=s*e+n,d=t[o];let c=0,g=0;for(let o=0;o<r;o++){const u=s+o-l;if(!(u<0||u>=i))for(let i=0;i<r;i++){const s=n+i-l;if(s<0||s>=e)continue;const p=t[u*e+s],m=a[o*r+i]*h[Math.abs(p-d)];c+=p*m;g+=m}}p[u[o]=Math.round(c/g)]++}return[u,p]}static#ul(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#pl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let s=-1/0,n=1/0;for(let e=0,r=i.length;e<r;e++){const r=i[e]=t[e<<2];s=Math.max(s,r);n=Math.min(n,r)}const r=255/(s-n);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-n)*r;return i}static#gl(t){let e,i=-1/0,s=-1/0;const n=t.findIndex(t=>0!==t);let r=n,a=n;for(e=n;e<256;e++){const n=t[e];if(n>i){if(e-r>s){s=e-r;a=e-1}i=n;r=e}}for(e=a-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#ml(t){const e=t,{width:i,height:s}=t,{maxDim:n}=this.#sl;let r=i,a=s;if(i>n||s>n){let o=i,l=s,h=Math.log2(Math.max(i,s)/n);const d=Math.floor(h);h=h===d?d-1:d;for(let i=0;i<h;i++){r=Math.ceil(o/2);a=Math.ceil(l/2);const i=new OffscreenCanvas(r,a);i.getContext("2d").drawImage(t,0,0,o,l,0,0,r,a);o=r;l=a;t!==e&&t.close();t=i.transferToImageBitmap()}const c=Math.min(n/r,n/a);r=Math.round(r*c);a=Math.round(a*c)}const o=new OffscreenCanvas(r,a).getContext("2d",{willReadFrequently:!0});o.fillStyle="white";o.fillRect(0,0,r,a);o.filter="grayscale(1)";o.drawImage(t,0,0,t.width,t.height,0,0,r,a);const l=o.getImageData(0,0,r,a).data;return[this.#pl(l),r,a]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:s},n,r,a,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const d=h.font=`${i} ${s} 200px ${e}`,{actualBoundingBoxLeft:c,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),w=1.5,y=Math.ceil(Math.max(Math.abs(c)+Math.abs(u)||0,b)*w),A=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*w);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);const v=this.#pl(h.getImageData(0,0,y,A).data),x=this.#ul(v),E=this.#gl(x),C=this.#ll(v,y,A,E);return this.processDrawnLines({lines:{curves:C,width:y,height:A},pageWidth:n,pageHeight:r,rotation:a,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,s,n){const[r,a,o]=this.#ml(t),[l,h]=this.#cl(r,a,o,Math.hypot(a,o)*this.#sl.sigmaSFactor,this.#sl.sigmaR,this.#sl.kernelSize),d=this.#gl(h),c=this.#ll(l,a,o,d);return this.processDrawnLines({lines:{curves:c,width:a,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:r,areContours:a}){s%180!=0&&([e,i]=[i,e]);const{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(const{points:t}of o){const e=r?this.#dl(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));c.push({line:n,points:s});if(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[a,o,l,h]=e;a*=p;o*=g;l*=p;h*=g;s.set([a,o,l,h],0);n.set([NaN,NaN,NaN,NaN,a,o],0);for(let t=4;t<i;t+=2){const i=s[t]=e[t]*p,r=s[t+1]=e[t+1]*g;n.set(Outline.createBezierPoints(a,o,l,h,i,r),3*(t-2));[a,o,l,h]=[l,h,i,r]}}if(0===c.length)return null;const f=a?new ContourDrawOutline:new InkDrawOutline;f.build(c,e,i,1,s,a?0:d,n);return{outline:f,newCurves:m,areContours:a,thickness:d,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:s,height:n}){let r,a=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];a=Math.min(a,i);o=Math.max(o,i)}}r=a>=-128&&o<=127?Int8Array:a>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,d=8+3*h,c=new Uint32Array(d);let u=0;c[u++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*r.BYTES_PER_ELEMENT;c[u++]=0;c[u++]=s;c[u++]=n;c[u++]=e?0:1;c[u++]=Math.max(0,Math.floor(i??0));c[u++]=h;c[u++]=r.BYTES_PER_ELEMENT;for(const e of t){c[u++]=e.length-2;c[u++]=e[0];c[u++]=e[1]}const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready;g.write(c);const m=r.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();const f=await new Response(p.readable).arrayBuffer();return toBase64Util(new Uint8Array(f))}static async decompressSignature(t){try{const e=function fromBase64Util(t){return Uint8Array.fromBase64?Uint8Array.fromBase64(t):stringToBytes(atob(t))}(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 r=null,a=0;for await(const t of i){r||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]);r.set(t,a);a+=t.length}const o=new Uint32Array(r.buffer,0,r.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],d=o[3],c=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(r.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(r.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(r.buffer,f)}a=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[a++]}return{areContours:c,thickness:u,outlines:m,width:h,height:d}}catch(t){warn(`decompressSignature: ${t}`);return null}}}class SignatureOptions extends DrawingOptions{constructor(){super();super.updateProperties({fill:AnnotationEditor._defaultLineColor,"stroke-width":0})}clone(){const t=new SignatureOptions;t.updateAll(this);return t}}class DrawnSignatureOptions extends InkDrawingOptions{constructor(t){super(t);super.updateProperties({stroke:AnnotationEditor._defaultLineColor,"stroke-width":1})}clone(){const t=new DrawnSignatureOptions(this._viewParameters);t.updateAll(this);return t}}class SignatureEditor extends DrawingEditor{#fl=!1;#bl=null;#wl=null;#yl=null;static _type="signature";static _editorType=p.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});this._willKeepAspectRatio=!0;this.#wl=t.signatureData||null;this.#bl=null;this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new SignatureOptions;this._defaultDrawnSignatureOptions=new DrawnSignatureOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!1}static get typesMap(){return shadow(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#bl}}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();if(null===this._drawId)if(this.#wl){const{lines:t,mustSmooth:e,areContours:i,description:s,uuid:n,heightInPage:r}=this.#wl,{rawDims:{pageWidth:a,pageHeight:o},rotation:l}=this.parent.viewport,h=SignatureExtractor.processDrawnLines({lines:t,pageWidth:a,pageHeight:o,rotation:l,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,r,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.#bl||""}));if(i){this._isCopy=!0;this._moveAfterPaste(t,e)}return this.div}setUuid(t){this.#yl=t;this.addEditToolbar()}getUuid(){return this.#yl}get description(){return this.#bl}set description(t){this.#bl=t;if(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.#wl,r=Math.max(s,n);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:s,height:n},pageWidth:r,pageHeight:r,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:r}=this,{outline:a}=this.#wl=t;this.#fl=a instanceof ContourDrawOutline;this.description=i;let o;if(this.#fl)o=SignatureEditor.getDefaultDrawingOptions();else{o=SignatureEditor._defaultDrawnSignatureOptions.clone();o.updateProperties({"stroke-width":a.thickness})}this._addOutlines({drawOutlines:a,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h;this.width*=h/this.height;if(this.width>=1){h*=.9/this.width;this.width=.9}this.height=h;this.setDims();this.x=n;this.y=r;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 SignatureExtractor.process(t,e,i,s,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:s},rotation:n}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,s,n,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:s}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:s,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){if(t)this._drawingOptions=SignatureEditor.getDefaultDrawingOptions();else{this._drawingOptions=SignatureEditor._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.#fl,color:[0,0,0],thickness:this.#fl?0:s});this.addComment(n);if(t){n.paths={lines:e,points:i};n.uuid=this.#yl;n.isCopy=!0}else n.lines=e;this.#bl&&(n.accessibilityData={type:"Figure",alt:this.#bl});return n}static deserializeDraw(t,e,i,s,n,r){return r.areContours?ContourDrawOutline.deserialize(t,e,i,s,n,r):InkDrawOutline.deserialize(t,e,i,s,n,r)}static async deserialize(t,e,i){const s=await super.deserialize(t,e,i);s.#fl=t.areContours;s.description=t.accessibilityData?.alt||"";s.#yl=t.uuid;return s}}class StampEditor extends AnnotationEditor{#Al=null;#vl=null;#xl=null;#El=null;#Cl=null;#_l="";#Sl=null;#Tl=!1;#Dl=null;#Ml=!1;#kl=!1;static _type="stamp";static _editorType=p.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#El=t.bitmapUrl;this.#Cl=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return W.includes(t)}static paste(t,e){e.pasteEditor({mode:p.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}}#Pl(t,e=!1){if(t){this.#Al=t.bitmap;if(!e){this.#vl=t.id;this.#Ml=t.isSvg}t.file&&(this.#_l=t.file.name);this.#Il()}else this.remove()}#Fl(){this.#xl=null;this._uiManager.enableWaiting(!1);if(this.#Sl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Al)this.addEditToolbar().then(()=>{this._editToolbar.hide();this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Al){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:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:s,width:n,height:r,channels:s.length/(n*r)}});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.");const o=a.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#Rl(){if(this.#vl){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#vl).then(t=>this.#Pl(t,!0)).finally(()=>this.#Fl());return}if(this.#El){const t=this.#El;this.#El=null;this._uiManager.enableWaiting(!0);this.#xl=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#Pl(t)).finally(()=>this.#Fl());return}if(this.#Cl){const t=this.#Cl;this.#Cl=null;this._uiManager.enableWaiting(!0);this.#xl=this._uiManager.imageManager.getFromFile(t).then(t=>this.#Pl(t)).finally(()=>this.#Fl());return}const t=document.createElement("input");t.type="file";t.accept=W.join(",");const e=this._uiManager._signal;this.#xl=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.#Pl(e)}else this.remove();i()},{signal:e});t.addEventListener("cancel",()=>{this.remove();i()},{signal:e})}).finally(()=>this.#Fl());t.click()}remove(){if(this.#vl){this.#Al=null;this._uiManager.imageManager.deleteId(this.#vl);this.#Sl?.remove();this.#Sl=null;if(this.#Dl){clearTimeout(this.#Dl);this.#Dl=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#vl&&null===this.#Sl&&this.#Rl();this.isAttachedToDOM||this.parent.add(this)}}else this.#vl&&this.#Rl()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#xl||this.#Al||this.#El||this.#Cl||this.#vl||this.#Tl)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.createAltText();this.#Tl||(this.#Al?this.#Il():this.#Rl());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:i,bitmap:s}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(i&&this._uiManager.imageManager.isValidId(i)){this.#vl=i;s&&(this.#Al=s);this.#Tl=!1;this.#Il()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Dl&&clearTimeout(this.#Dl);this.#Dl=setTimeout(()=>{this.#Dl=null;this.#Ll()},200)}#Il(){const{div:t}=this;let{width:e,height:i}=this.#Al;const[s,n]=this.pageDimensions,r=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>r*s||i>r*n){const t=Math.min(r*s/e,r*n/i);e*=t;i*=t}this._uiManager.enableWaiting(!1);const a=this.#Sl=document.createElement("canvas");a.setAttribute("role","img");this.addContainer(a);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.#Ll();if(!this.#kl){this.parent.addUndoableEditor(this);this.#kl=!0}this._reportTelemetry({action:"inserted_image"});this.#_l&&this.div.setAttribute("aria-description",this.#_l);this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#Al,r=new OutputScale;let a=this.#Al,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*r.sx),i=h.height=Math.ceil(l*r.sy);this.#Ml||(a=this.#Bl(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(ColorScheme.isDarkMode){c="#8f8f9d";u="#42414d"}const p=15,g=p*r.sx,m=p*r.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(r.symmetric&&a.width<t&&a.height<t){e=a.width;i=a.height}else{a=this.#Al;if(s>t||n>t){const r=Math.min(t/s,t/n);e=Math.floor(s*r);i=Math.floor(n*r);this.#Ml||(a=this.#Bl(e,i))}}const 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}}#Bl(t,e){const{width:i,height:s}=this.#Al;let n=i,r=s,a=this.#Al;for(;n>2*t||r>2*e;){const i=n,s=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(n,r);o.getContext("2d").drawImage(a,0,0,i,s,0,0,n,r);a=o.transferToImageBitmap()}return a}#Ll(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,r=Math.ceil(i*t*n.sx),a=Math.ceil(s*e*n.sy),o=this.#Sl;if(!o||o.width===r&&o.height===a)return;o.width=r;o.height=a;const l=this.#Ml?this.#Al:this.#Bl(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}#Ol(t){if(t){if(this.#Ml){const t=this._uiManager.imageManager.getSvgUrl(this.#vl);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Al);t.getContext("2d").drawImage(this.#Al,0,0);return t.toDataURL()}if(this.#Ml){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#Al,0,0,this.#Al.width,this.#Al.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#Al)}static async deserialize(t,e,i){let s=null,n=!1;if(t instanceof StampAnnotationElement){const{data:{rect:r,rotation:a,id:o,structParent:l,popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:g},container:m,parent:{page:{pageNumber:f}},canvas:b}=t;let w,y;if(b){delete t.canvas;({id:w,bitmap:y}=i.imageManager.getFromCanvas(m.id,b));b.remove()}else{n=!0;t._hasNoCanvas=!0}const A=(await e._structTree.getAriaAttributes(`${z}${o}`))?.get("aria-label")||"";s=t={annotationType:p.STAMP,bitmapId:w,bitmap:y,pageIndex:f-1,rect:r.slice(0),rotation:a,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:A},isSvg:!1,structParent:l,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:g}}const r=await super.deserialize(t,e,i),{rect:a,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;if(n){i.addMissingCanvas(t.id,r);r.#Tl=!0}else if(h&&i.imageManager.isValidId(h)){r.#vl=h;o&&(r.#Al=o)}else r.#El=l;r.#Ml=d;const[u,g]=r.pageDimensions;r.width=(a[2]-a[0])/u;r.height=(a[3]-a[1])/g;c&&(r.altTextData=c);r._initialData=s;t.comment&&r.setCommentData(t);r.#kl=!!s;return r}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.#vl,isSvg:this.#Ml});this.addComment(i);if(t){i.bitmapUrl=this.#Ol(!0);i.accessibilityData=this.serializeAltText(!0);i.isCopy=!0;return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#va(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1;i.id=this.annotationElementId;delete i.bitmapId;return i}if(null===e)return i;e.stamps||=new Map;const r=this.#Ml?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#vl)){if(this.#Ml){const t=e.stamps.get(this.#vl);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#Ol(!1)}}}else{e.stamps.set(this.#vl,{area:r,serialized:i});i.bitmap=this.#Ol(!1)}return i}#va(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){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}}class AnnotationEditorLayer{#na;#Nl=!1;#Ul=null;#Hl=null;#zl=null;#Gl=new Map;#Wl=!1;#Vl=!1;#$l=!1;#jl=null;#ql=null;#Xl=null;#Kl=null;#Yl=null;#Ql=-1;#b;static _initialized=!1;static#$=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#$.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d);this.#b=t;this.pageIndex=e;this.div=i;this.#na=n;this.#Ul=r;this.viewport=l;this.#Xl=o;this.drawLayer=a;this._structTree=s;this.#b.addLayer(this)}get isEmpty(){return 0===this.#Gl.size}get isInvisible(){return this.isEmpty&&this.#b.getMode()===p.NONE}updateToolbar(t){this.#b.updateToolbar(t)}updateMode(t=this.#b.getMode()){this.#Jl();switch(t){case p.NONE:this.div.classList.toggle("nonEditing",!0);this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case p.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case p.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;e.toggle("nonEditing",!1);if(t===p.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#$.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Xl?.div}setEditingState(t){this.#b.setEditingState(t)}addCommands(t){this.#b.addCommands(t)}cleanUndoStack(t){this.#b.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Ul?.div.classList.toggle("disabled",!t)}get#Zl(){return 0!==this.#Gl.size?this.#Gl.values():this.#b.getEditors(this.pageIndex)}async enable(){this.#$l=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);this.div.classList.toggle("nonEditing",!1);this.#Yl?.abort();this.#Yl=null;const t=new Set;for(const e of this.#Zl){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#b.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}const e=this.#Ul;if(e)for(const i of e.getEditableAnnotations()){i.hide();if(this.#b.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#$l=!1;this.#b._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){this.#Vl=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);this.div.classList.toggle("nonEditing",!0);if(this.#Xl&&!this.#Yl){this.#Yl=new AbortController;const t=this.#b.combinedSignal(this.#Yl);this.#Xl.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:s}=t;if(s-this.#Ql>500){this.#Ql=s;return}this.#Ql=-1;const{classList:n}=this.div;n.toggle("getElements",!0);const r=document.elementsFromPoint(e,i);n.toggle("getElements",!1);if(!this.div.contains(r[0]))return;let a;const o=new RegExp(`^${u}[0-9]+$`);for(const t of r)if(o.test(t.id)){a=t.id;break}if(!a)return;const l=this.#Gl.get(a);if(null===l?.annotationElementId){t.stopPropagation();t.preventDefault();l.dblclick(t)}},{signal:t,capture:!0})}const t=this.#Ul;if(t){const e=new Map,i=new Map;for(const s of this.#Zl){s.disableEditing();if(s.annotationElementId)if(null===s.serialize()){i.set(s.annotationElementId,s);this.getEditableAnnotation(s.annotationElementId)?.show();s.remove()}else e.set(s.annotationElementId,s);else s.updateFakeAnnotationElement(t)}const s=t.getEditableAnnotations();for(const t of s){const{id:s}=t.data;if(this.#b.isDeletedAnnotationElement(s)){t.updateEdited({deleted:!0});continue}let n=i.get(s);if(n){n.resetAnnotationElement(t);n.show(!1);t.show()}else{n=e.get(s);if(n){this.#b.addChangedExistingAnnotation(n);n.renderAnnotationElement(t)&&n.show(!1)}t.show()}}}this.#Jl();this.isEmpty&&(this.div.hidden=!0);const{classList:e}=this.div;for(const t of AnnotationEditorLayer.#$.values())e.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#Vl=!1}getEditableAnnotation(t){return this.#Ul?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#b.getActive()!==t&&this.#b.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#Xl?.div&&!this.#Kl){this.#Kl=new AbortController;const t=this.#b.combinedSignal(this.#Kl);this.#Xl.div.addEventListener("pointerdown",this.#th.bind(this),{signal:t});this.#Xl.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#Xl?.div&&this.#Kl){this.#Kl.abort();this.#Kl=null;this.#Xl.div.classList.remove("highlighting")}}#th(t){this.#b.unselectAll();const{target:e}=t;if(e===this.#Xl.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#Xl.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#b.showAllEditors("highlight",!0,!0);this.#Xl.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#b.direction,{target:this.#Xl.div,x:t.x,y:t.y});this.#Xl.div.addEventListener("pointerup",()=>{this.#Xl.div.classList.remove("free");this.toggleDrawing(!0)},{once:!0,signal:this.#b._signal});t.preventDefault()}}enableClick(){if(this.#Hl)return;this.#Hl=new AbortController;const t=this.#b.combinedSignal(this.#Hl);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.#Hl?.abort();this.#Hl=null}attach(t){this.#Gl.set(t.id,t);const{annotationElementId:e}=t;e&&this.#b.isDeletedAnnotationElement(e)&&this.#b.removeDeletedAnnotationElement(t)}detach(t){this.#Gl.delete(t.id);this.#na?.removePointerInTextLayer(t.contentDiv);!this.#Vl&&t.annotationElementId&&this.#b.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#b.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#b.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#b.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#$l);this.#b.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#zl){t._focusEventsAllowed=!1;this.#zl=setTimeout(()=>{this.#zl=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#b._signal});e.focus()}},0)}t._structTreeParentId=this.#na?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#Gl.values())if(e.uid===t)return e;return null}getNextId(){return this.#b.getId()}get#eh(){return AnnotationEditorLayer.#$.get(this.#b.getMode())}combinedSignal(t){return this.#b.combinedSignal(t)}#ih(t){const e=this.#eh;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#eh?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t);await this.#b.updateMode(t.mode);const{offsetX:i,offsetY:s}=this.#sh(),n=this.getNextId(),r=this.#ih({parent:this,id:n,x:i,y:s,uiManager:this.#b,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(AnnotationEditorLayer.#$.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#b))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#ih({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#b,isCentered:e,...i});n&&this.add(n);return n}get boundingClientRect(){return this.div.getBoundingClientRect()}#sh(){const{x:t,y:e,width:i,height:s}=this.boundingClientRect,n=Math.max(0,t),r=Math.max(0,e),a=(n+Math.min(window.innerWidth,t+i))/2-t,o=(r+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.#sh(),!0,t)}setSelected(t){this.#b.setSelected(t)}toggleSelected(t){this.#b.toggleSelected(t)}unselect(t){this.#b.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Wl)return;this.#Wl=!1;if(this.#eh?.isDrawer&&this.#eh.supportMultipleDrawings)return;if(!this.#Nl){this.#Nl=!0;return}const i=this.#b.getMode();i!==p.STAMP&&i!==p.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#b.unselectAll()}pointerdown(t){this.#b.getMode()===p.HIGHLIGHT&&this.enableTextSelection();if(this.#Wl){this.#Wl=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Wl=!0;if(this.#eh?.isDrawer){this.startDrawingSession(t);return}const i=this.#b.getActive();this.#Nl=!i||i.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:!0});if(this.#jl){this.#eh.startDrawing(this,this.#b,!1,t);return}this.#b.setCurrentDrawingSession(this);this.#jl=new AbortController;const e=this.#b.combinedSignal(this.#jl);this.div.addEventListener("blur",({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#ql=null;this.commitOrRemove()}},{signal:e});this.#eh.startDrawing(this,this.#b,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#ql=t);return}this.#ql&&setTimeout(()=>{this.#ql?.focus();this.#ql=null},0)}endDrawingSession(t=!1){if(!this.#jl)return null;this.#b.setCurrentDrawingSession(null);this.#jl.abort();this.#jl=null;this.#ql=null;return this.#eh.endDrawing(t)}findNewParent(t,e,i){const s=this.#b.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#jl){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#jl&&this.#eh.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#b.getActive()?.parent===this){this.#b.commitOrRemove();this.#b.setActiveEditor(null)}if(this.#zl){clearTimeout(this.#zl);this.#zl=null}for(const t of this.#Gl.values()){this.#na?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#Gl.clear();this.#b.removeLayer(this)}#Jl(){for(const t of this.#Gl.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#b.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#b.commitOrRemove();this.#Jl();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#Gl.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#b.viewParameters.realScale}}class DrawLayer{#Dr=null;#nh=new Map;#rh=new Map;static#v=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#Dr){if(this.#Dr!==t){if(this.#nh.size>0)for(const e of this.#nh.values()){e.remove();t.append(e)}this.#Dr=t}}else this.#Dr=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#ah(t,[e,i,s,n]){const{style:r}=t;r.top=100*i+"%";r.left=100*e+"%";r.width=100*s+"%";r.height=100*n+"%"}#oh(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#Dr.append(t);t.setAttribute("aria-hidden",!0);return t}#lh(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#hh(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=DrawLayer.#v++,n=this.#oh(),r=DrawLayer._svgFactory.createElement("defs");n.append(r);const a=DrawLayer._svgFactory.createElement("path");r.append(a);const o=`path_p${this.pageIndex}_${s}`;a.setAttribute("id",o);a.setAttribute("vector-effect","non-scaling-stroke");e&&this.#rh.set(s,a);const l=i?this.#lh(r,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#nh.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#v++,s=this.#oh(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const r=DrawLayer._svgFactory.createElement("path");n.append(r);const a=`path_p${this.pageIndex}_${i}`;r.setAttribute("id",a);r.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${a}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${a}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#nh.set(i,s);return i}finalizeDraw(t,e){this.#rh.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:r}=e,a="number"==typeof t?this.#nh.get(t):t;if(a){i&&this.#hh(a,i);s&&DrawLayer.#ah(a,s);if(n){const{classList:t}=a;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(r){const t=a.firstChild.firstChild;this.#hh(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#nh.get(t);if(i){e.#Dr.append(i);this.#nh.delete(t);e.#nh.set(t,i)}}remove(t){this.#rh.delete(t);if(null!==this.#Dr){this.#nh.get(t).remove();this.#nh.delete(t)}}destroy(){this.#Dr=null;for(const t of this.#nh.values())t.remove();this.#nh.clear();this.#rh.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner};globalThis.pdfjsLib={AbortException,AnnotationEditorLayer,AnnotationEditorParamsType:g,AnnotationEditorType:p,AnnotationEditorUIManager,AnnotationLayer,AnnotationMode:c,AnnotationType:E,applyOpacity,build:Rt,ColorPicker,createValidAbsoluteUrl,CSSConstants,DOMSVGFactory,DrawLayer,FeatureTest:util_FeatureTest,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,GlobalWorkerOptions,ImageKind:x,InvalidPDFException,isDataScheme,isPdfFile,isValidExplicitDest:K,MathClamp,noContextMenu,normalizeUnicode,OPS:k,OutputScale,PasswordResponses:L,PDFDataRangeTransport,PDFDateString,PDFWorker,PermissionFlag:m,PixelsPerInch,RenderingCancelledException,renderRichText,ResponseException,setLayerDimensions,shadow,SignatureExtractor,stopEvent,SupportedImageMimeTypes:W,TextLayer,TouchManager,updateUrlHash,Util,VerbosityLevel:M,version:Ft,XfaLayer};export{AbortException,AnnotationEditorLayer,g as AnnotationEditorParamsType,p as AnnotationEditorType,AnnotationEditorUIManager,AnnotationLayer,c as AnnotationMode,E as AnnotationType,CSSConstants,ColorPicker,DOMSVGFactory,DrawLayer,util_FeatureTest as FeatureTest,GlobalWorkerOptions,x as ImageKind,InvalidPDFException,MathClamp,k as OPS,OutputScale,PDFDataRangeTransport,PDFDateString,PDFWorker,L as PasswordResponses,m as PermissionFlag,PixelsPerInch,RenderingCancelledException,ResponseException,SignatureExtractor,W as SupportedImageMimeTypes,TextLayer,TouchManager,Util,M as VerbosityLevel,XfaLayer,applyOpacity,Rt as build,createValidAbsoluteUrl,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,isDataScheme,isPdfFile,K as isValidExplicitDest,noContextMenu,normalizeUnicode,renderRichText,setLayerDimensions,shadow,stopEvent,updateUrlHash,Ft as version};
|