@component-hook/pdf-canvas 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -502,7 +502,7 @@ void main() {
502
502
  gl_FragColor = color;
503
503
  }
504
504
  `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),l=(n+r+o)/3,c=2*Math.abs(h-l)/255*s;e[i]+=h!==n?(h-n)*c:0,e[i+1]+=h!==r?(h-r)*c:0,e[i+2]+=h!==o?(h-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}x(An,"type","Vibrance"),x(An,"defaults",{vibrance:0}),x(An,"uniformLocations",["uVibrance"]),F.setClass(An);var li={};li.d=(a,t)=>{for(var e in t)li.o(t,e)&&!li.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},li.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var V=globalThis.pdfjsLib={};li.d(V,{AbortException:()=>$e,AnnotationEditorLayer:()=>He,AnnotationEditorParamsType:()=>q,AnnotationEditorType:()=>U,AnnotationEditorUIManager:()=>qe,AnnotationLayer:()=>mg,AnnotationMode:()=>Ue,ColorPicker:()=>ne,DOMSVGFactory:()=>yo,DrawLayer:()=>zt,FeatureTest:()=>Bt,GlobalWorkerOptions:()=>vi,ImageKind:()=>Tn,InvalidPDFException:()=>Zr,MissingPDFException:()=>ui,OPS:()=>fe,OutputScale:()=>oo,PDFDataRangeTransport:()=>_l,PDFDateString:()=>Xh,PDFWorker:()=>Bs,PasswordResponses:()=>Cd,PermissionFlag:()=>Sd,PixelsPerInch:()=>Is,RenderingCancelledException:()=>io,TextLayer:()=>Ht,TouchManager:()=>Fn,UnexpectedResponseException:()=>Pn,Util:()=>B,VerbosityLevel:()=>En,XfaLayer:()=>Cl,build:()=>Kf,createValidAbsoluteUrl:()=>kd,fetchData:()=>Dn,getDocument:()=>zf,getFilenameFromUrl:()=>Nd,getPdfFilenameFromUrl:()=>jd,getXfaPageViewport:()=>Bd,isDataScheme:()=>Rn,isPdfFile:()=>no,noContextMenu:()=>ge,normalizeUnicode:()=>Ld,setLayerDimensions:()=>fs,shadow:()=>$,stopEvent:()=>te,version:()=>qf});const Pt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Bh=[1,0,0,1,0,0],qr=[.001,0,0,.001,0,0],wd=1e7,Kr=1.35,Qt={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Ue={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},xd="pdfjs_internal_editor_",U={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},q={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Sd={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Ot={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Tn={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},St={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,WIDGET:20},ci={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},En={ERRORS:0,WARNINGS:1,INFOS:5},fe={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},Cd={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let kn=En.WARNINGS;function Ad(a){Number.isInteger(a)&&(kn=a)}function Td(){return kn}function Mn(a){kn>=En.INFOS&&console.log(`Info: ${a}`)}function Y(a){kn>=En.WARNINGS&&console.log(`Warning: ${a}`)}function st(a){throw new Error(a)}function yt(a,t){a||st(t)}function Ed(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function kd(a,t=null,e=null){if(!a)return null;try{if(e&&typeof a=="string"&&(e.addDefaultProtocol&&a.startsWith("www.")&&a.match(/\./g)?.length>=2&&(a=`http://${a}`),e.tryConvertEncoding))try{a=Rd(a)}catch{}const s=t?new URL(a,t):new URL(a);if(Ed(s))return s}catch{}return null}function $(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Ye=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Hh extends Ye{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Jr extends Ye{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Zr extends Ye{constructor(t){super(t,"InvalidPDFException")}}class ui extends Ye{constructor(t){super(t,"MissingPDFException")}}class Pn extends Ye{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Md extends Ye{constructor(t){super(t,"FormatError")}}class $e extends Ye{constructor(t){super(t,"AbortException")}}function zh(a){(typeof a!="object"||a?.length===void 0)&&st("Invalid argument for bytesToString");const t=a.length,e=8192;if(t<e)return String.fromCharCode.apply(null,a);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=a.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function On(a){typeof a!="string"&&st("Invalid argument for stringToBytes");const t=a.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=a.charCodeAt(s)&255;return e}function Pd(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function Qr(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Od(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function Dd(){try{return new Function(""),!0}catch{return!1}}class Bt{static get isLittleEndian(){return $(this,"isLittleEndian",Od())}static get isEvalSupported(){return $(this,"isEvalSupported",Dd())}static get isOffscreenCanvasSupported(){return $(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return $(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?$(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):$(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return $(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const to=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class B{static makeHexColor(t,e,s){return`#${to[t]}${to[e]}${to[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],o=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,l=o+h||1,c=o-h||1;return[Math.sqrt(l),Math.sqrt(c)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static#t(t,e,s,i,n,r,o,h,l,c){if(l<=0||l>=1)return;const u=1-l,d=l*l,f=d*l,g=u*(u*(u*t+3*l*e)+3*d*s)+f*i,p=u*(u*(u*n+3*l*r)+3*d*o)+f*h;c[0]=Math.min(c[0],g),c[1]=Math.min(c[1],p),c[2]=Math.max(c[2],g),c[3]=Math.max(c[3],p)}static#e(t,e,s,i,n,r,o,h,l,c,u,d){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,h,-u/c,d);return}const f=c**2-4*u*l;if(f<0)return;const g=Math.sqrt(f),p=2*l;this.#t(t,e,s,i,n,r,o,h,(-c+g)/p,d),this.#t(t,e,s,i,n,r,o,h,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){return l?(l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h)):l=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],this.#e(t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l),l}}function Rd(a){return decodeURIComponent(escape(a))}let eo=null,Gh=null;function Ld(a){return eo||(eo=/([\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,Gh=new Map([["ſt","ſt"]])),a.replaceAll(eo,(t,e,s)=>e?e.normalize("NFKC"):Gh.get(s))}function Fd(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),zh(a)}const so="pdfjs_internal_id_";function Id(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(zh(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const Be="http://www.w3.org/2000/svg";class Is{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Dn(a,t="text"){if(fi(a,document.baseURI)){const e=await fetch(a);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",a,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class di{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let c,u,d,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,u=0,d=0,f=1;break;case 90:c=0,u=1,d=1,f=0;break;case 270:c=0,u=-1,d=-1,f=0;break;case 0:c=1,u=0,d=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(d=-d,f=-f);let g,p,b,m;c===0?(g=Math.abs(l-t[1])*s+n,p=Math.abs(h-t[0])*s+r,b=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(h-t[0])*s+n,p=Math.abs(l-t[1])*s+r,b=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,u*s,d*s,f*s,g-c*s*h-d*s*l,p-u*s*h-f*s*l],this.width=b,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return $(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new di({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return B.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=B.applyTransform([t[0],t[1]],this.transform),s=B.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return B.applyInverseTransform([t,e],this.transform)}}class io extends Ye{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Rn(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function no(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Nd(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function jd(a,t="document.pdf"){if(typeof a!="string")return t;if(Rn(a))return Y('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class Vh{started=Object.create(null);times=[];time(t){t in this.started&&Y(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Y(`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:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
505
- `);return t.join("")}}function fi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ge(a){a.preventDefault()}function te(a){a.preventDefault(),a.stopPropagation()}class Xh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,l==="-"?(r+=c,o+=u):l==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}function Bd(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new di({viewBox:n,userUnit:1,scale:t,rotation:e})}function ro(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(Y(`Not a valid color format: "${a}"`),[0,0,0])}function Hd(a){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,ro(s))}t.remove()}function rt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function Ce(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform().invertSelf();return[t,e,s,i,n,r]}function fs(a,t,e=!1,s=!0){if(t instanceof di){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Bt.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class oo{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class gi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,gi.#n||=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"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",ge,{signal:e}),t.addEventListener("pointerdown",gi.#h,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#h(t){t.stopPropagation()}#a(t){this.#s._focusEventsAllowed=!1,te(t)}#c(t){this.#s._focusEventsAllowed=!0,te(t)}#l(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#a.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ge,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",gi.#n[t]),this.#l(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#l(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#l(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class zd{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ge,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const o=n.x+(e?n.width:0);if(r>s){i=o,s=r;continue}e?o>i&&(i=o):o<i&&(i=o)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",ge,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function Ln(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class Gd{#t=0;get id(){return`${xd}${this.#t++}`}}class ao{#t=Fd();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='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>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return $(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Dn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=ao._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){Y(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class Vd{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),this.#e)return;const h={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class pi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Bt.platform;for(const[s,i,n={}]of t)for(const r of s){const o=r.startsWith("mac+");e&&o?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!o&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||te(e))}}class ho{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Hd(t),$(this,"_colors",t)}convert(t){const e=ro(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return ho._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?B.makeHexColor(...e):t}}class qe{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#h=null;#a=new Vd;#c=null;#l=null;#d=0;#u=new Set;#f=null;#o=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#b=!1;#_=null;#v=null;#w=null;#S=null;#A=!1;#E=null;#M=new Gd;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=U.NONE;#y=new Set;#R=null;#z=null;#G=null;#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#N=[0,0];#F=null;#j=null;#X=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=qe.prototype,e=r=>r.#j.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return $(this,"_keyboardManager",new pi([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,o,h,l,c,u,d,f){const g=this._signal=this.#t.signal;this.#j=t,this.#X=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=o||null,this.#m=h,this.#p=l,this.#b=c,this.#I=u||null,this.viewParameters={realScale:Is.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#a.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#v&&(clearTimeout(this.#v),this.#v=null),this.#F&&(clearTimeout(this.#F),this.#F=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return $(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return $(this,"direction",getComputedStyle(this.#j).direction)}get highlightColors(){return $(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return $(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=t}setMainHighlightColorPicker(t){this.#L=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}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}){switch(t){case"enableNewAltTextWhenAddingImage":this.#b=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#j.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)return s}return null}disableUserSelect(t=!1){this.#X.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Is.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#Y(l),d=this.#C===U.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(U.HIGHLIGHT,f);return}f()}#Q(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new zd(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#P({hasSelectedText:!0}),!(this.#C!==U.HIGHLIGHT&&this.#C!==U.NONE)&&(this.#C===U.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===U.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}}#U(t=""){this.#C===U.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Q()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&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 n of e.items)for(const r of this.#o)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){Y(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#J(h);this.#Z(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){Y(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==U.NONE&&!this.isEditorHandlingKeyboard&&qe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("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}}#P(t){Object.entries(t).some(([s,i])=>this.#V[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)}),this.#C===U.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[q.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==U.NONE,isEmpty:this.#W(),hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:this.#a.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#o){this.#o=t;for(const e of this.#o)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#M.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===U.NONE){this.setEditingState(!1),this.#at(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#ot(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#o){switch(t){case q.CREATE:this.currentLayer.addNewEditor();return;case q.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case q.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#o)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#G?.get(q.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[q.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ot(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#at(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.focusMainContainer(),this.#v=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#ht(){let t=null;for(t of this.#y);return t}updateUI(t){this.#ht===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){this.#l?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#a.undo(),this.#P({hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#W()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#W()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#W()})}cleanUndoStack(t){this.#a.cleanType(t)}#W(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.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.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Z(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Z(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==U.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#P({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#N[0]+=t,this.#N[1]+=e;const[i,n]=this.#N,r=[...this.#y],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=null,this.#N[0]=this.#N[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex;if(!e)return!1;const s=(i,n,r,o)=>{if(this.#s.has(i.id)){const h=this.#i.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return $(this,"imageManager",new ao)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,u,d)=>({x:(c-i)/r,y:1-(l+u-s)/n,width:d/r,height:u/n});break;case"180":o=(l,c,u,d)=>({x:1-(l+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":o=(l,c,u,d)=>({x:1-(c+d-i)/r,y:(l-s)/n,width:d/r,height:u/n});break;default:o=(l,c,u,d)=>({x:(l-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||h.push(o(d,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===U.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ae{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#h=!1;#a=null;#c=null;#l=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Ae.#f||=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){Ae._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Ae.#f.missing),e.setAttribute("data-l10n-id",Ae.#f["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",ge,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#o}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#h=!0,i(n))},{signal:s}),await this.#g(),t}get#o(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#h}),this.#h=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#d=await Ae._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#a.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#o}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#a?.remove(),this.#a=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Ae.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Ae.#f[`${this.#o}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class Fn{#t;#e=!1;#s=null;#i;#r;#n;#h;#a;#c=null;#l;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#h=r,this.#l=new AbortController,this.#a=AbortSignal.any([o,this.#l.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return $(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#a,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#o.bind(this),r),n.addEventListener("touchcancel",this.#o.bind(this),r),this.#r?.()}if(te(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=this.#c,{touch0X:l,touch0Y:c,touch1X:u,touch1Y:d}=h,f=u-l,g=d-c,p=r-i,b=o-n,m=Math.hypot(p,b)||1,v=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(v-m)<=Fn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const y=[(i+r)/2,(n+o)/2];this.#n?.(y,v,m)}#o(t){this.#d.abort(),this.#d=null,this.#h?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#l?.abort(),this.#l=null}}class H{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#h=!1;#a=null;#c=null;#l=null;#d=null;#u="";#f=!1;#o=null;#g=!1;#m=!1;#p=!1;#b=null;#_=0;#v=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=H._zIndex++;static _borderLineWidth=-1;static _colorManager=new ho;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=H.prototype._resizeWithKeyboard,e=qe.TRANSLATE_SMALL,s=qe.TRANSLATE_BIG;return $(this,"_resizerKeyboardManager",new pi([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],H.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;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return $(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Xd({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){if(H._l10n??=t,H._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"}),H._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);H._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){st("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}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.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}#M([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#o||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#o||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,l]=this.getBaseTranslation();r+=h,o+=l;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#o&&(this.#o[0]!==this.x||this.#o[1]!==this.y)}get _hasBeenResized(){return!!this.#o&&(this.#o[2]!==this.width||this.#o[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=H,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return H.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return H.#x(t,e,360-this.parentRotation)}#k(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#h||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#h&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#h&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#a)return;this.#a=document.createElement("div"),this.#a.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#a.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",ge,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=Bt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",te,{passive:!1,signal:r}),window.addEventListener("contextmenu",ge,{signal:r}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#I()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#L(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#l)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#l=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),undo:this.#L.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=H.MIN_SIZE/s,c=H.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,R)=>[u[0]*M+u[2]*R,u[1]*M+u[3]*R],f=this.#k(360-this.rotation),g=(M,R)=>[f[0]*M+f[2]*R,f[1]*M+f[3]*R];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(M,R)=>[0,0],b=(M,R)=>[M,R];break;case"topMiddle":p=(M,R)=>[M/2,0],b=(M,R)=>[M/2,R];break;case"topRight":m=!0,p=(M,R)=>[M,0],b=(M,R)=>[0,R];break;case"middleRight":v=!0,p=(M,R)=>[M,R/2],b=(M,R)=>[0,R/2];break;case"bottomRight":m=!0,p=(M,R)=>[M,R],b=(M,R)=>[0,0];break;case"bottomMiddle":p=(M,R)=>[M/2,R],b=(M,R)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,R)=>[0,R],b=(M,R)=>[M,0];break;case"middleLeft":v=!0,p=(M,R)=>[0,R/2],b=(M,R)=>[M,R/2];break}const y=p(o,h),_=b(o,h);let S=d(..._);const A=H._round(n+S[0]),T=H._round(r+S[1]);let E=1,P=1,N,D;if(e.fromKeyboard)({deltaX:N,deltaY:D}=e);else{const{screenX:M,screenY:R}=e,[G,at]=this.#c;[N,D]=this.screenToPageTranslation(M-G,R-at),this.#c[0]=M,this.#c[1]=R}if([N,D]=g(N/s,D/i),m){const M=Math.hypot(o,h);E=P=Math.max(Math.min(Math.hypot(_[0]-y[0]-N,_[1]-y[1]-D)/M,1/o,1/h),l/o,c/h)}else v?E=Math.max(l,Math.min(1,Math.abs(_[0]-y[0]-N)))/o:P=Math.max(c,Math.min(1,Math.abs(_[1]-y[1]-D)))/h;const L=H._round(o*E),k=H._round(h*P);S=d(...b(L,k));const O=A-S[0],j=T-S[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=L,this.height=k,this.x=O,this.y=j,this.setDims(s*L,i*k),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new gi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Ae.initialize(H._l10n),this.#s=new Ae(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#N();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),Ln(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new Fn({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),o=(A,T)=>[r[0]*A+r[2]*T,r[1]*A+r[3]*T],[h,l]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=H.MIN_SIZE/h,p=H.MIN_SIZE/l;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const b=H._round(d*n),m=H._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),y=H._round(c+v[0]),_=H._round(u+v[1]),S=o(b/2,m/2);this.x=y-S[0],this.y=_-S[1],this.width=b,this.height=m,this.setDims(h*b,l*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#V(t);return}this.#G(t)}get isSelected(){return this._uiManager.isSelected(this)}#G(t){const{isMac:e}=Bt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#V(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=l=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#G(l),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=l;if(d!==this.#r){te(l);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#v);this.#_=c,this.#v=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",te,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#n&&(this.#S||l.isPrimary)&&o(l),te(l)},r));const h=l=>{if(!this.#r||this.#r===l.pointerId){o(l);return}te(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,l=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+l+o,r-d-c-g+h,u+l+f+o,r-d-c+h];case 90:return[u+c+o,r-d+l+h,u+c+g+o,r-d+l+f+h];case 180:return[u-l-f+o,r-d+c+h,u-l+o,r-d+c+g+h];case 270:return[u-c-g+o,r-d-l-f+h,u-c+o,r-d-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#N(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#N()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){st("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[o,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#a.classList.remove("hidden"),Ln(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=this.#j.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#X.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",H._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)this.#a.append(this.#a.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#a.firstChild.before(this.#a.lastChild);let r=0;for(const o of e){const l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",H._l10nResizer[l])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){H._resizerKeyboardManager.exec(this,t)}#j(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&this.#B()}#X(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#a?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#h=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},H._telemetryTimeout),this.#w.set(s,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.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class Xd extends H{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Wh=3285377520,ie=4294901760,Te=65535;class Uh{constructor(t){this.h1=t?t&4294967295:Wh,this.h2=t?t&4294967295:Wh}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,b=t.length;p<b;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let o=0,h=0,l=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Te,g=d&Te;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*u&ie|h*f&Te,h=h<<15|h>>>17,h=h*d&ie|h*g&Te,c^=h,c=c<<13|c>>>19,c=c*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ie|t*36045&Te,e=e*4283543511&ie|((e<<16|t>>>16)*2950163797&ie)>>>16,t^=e>>>1,t=t*444984403&ie|t*60499&Te,e=e*3301882366&ie|((e<<16|t>>>16)*3120437893&ie)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const lo=Object.freeze({map:null,hash:"",transfer:void 0});class co{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof H)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#s.set(t,e);i&&this.#i(),e instanceof H&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?Qr(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Yh(this)}get serializable(){if(this.#s.size===0)return lo;const t=new Map,e=new Uh,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof H?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:lo}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof H))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof H)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Yh extends co{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){st("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return $(this,"modifiedIds",{ids:new Set,hash:""})}}class Wd{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));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.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(yt(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#t.add(s),e?.(t)}catch{Y(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}st("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw Y(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return $(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Pt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),$(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(yt(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return $(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,S){return _.charCodeAt(S)<<24|_.charCodeAt(S+1)<<16|_.charCodeAt(S+2)<<8|_.charCodeAt(S+3)&255}function i(_,S,A,T){const E=_.substring(0,S),P=_.substring(S+A);return E+T+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,S){if(++l>30){Y("Load test font never loaded."),S();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(c.bind(null,_,S))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let b=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)b=b-p+s(u,n)|0;n<u.length&&(b=b-p+s(u+"XXX",n)|0),d=i(d,g,4,Pd(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=_,y.append(S)}this._document.body.append(y),c(u,()=>{y.remove(),e.complete()})}}class Ud{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{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)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Id(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){Y(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const In={DATA:1,ERROR:2},_t={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function $h(){}function Ut(a){if(a instanceof $e||a instanceof Zr||a instanceof ui||a instanceof Hh||a instanceof Pn||a instanceof Jr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||st('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new $e(a.message);case"InvalidPDFException":return new Zr(a.message);case"MissingPDFException":return new ui(a.message);case"PasswordException":return new Hh(a.message,a.code);case"UnexpectedResponseException":return new Pn(a.message,a.status);case"UnknownErrorException":return new Jr(a.message,a.details)}return new Jr(a.message,a.toString())}class mi{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===In.DATA)i.resolve(t.data);else if(t.callback===In.ERROR)i.reject(Ut(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:In.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:In.ERROR,callbackId:t.callbackId,reason:Ut(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:_t.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{yt(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:_t.CANCEL,streamId:n,reason:Ut(l)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(l,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:_t.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){yt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.ERROR,streamId:e,reason:Ut(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,reason:Ut(l)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],o=this.streamSinks[e];switch(t.stream){case _t.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ut(t.reason));break;case _t.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ut(t.reason));break;case _t.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||$h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,reason:Ut(l)})});break;case _t.ENQUEUE:if(yt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case _t.CLOSE:if(yt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case _t.ERROR:yt(r,"error should have stream controller"),r.controller.error(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL:if(!o)break;const h=Ut(t.reason);Promise.try(o.onCancel||$h,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,reason:Ut(l)})}),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class qh{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){st("Abstract method `_createCanvas` called.")}}class Yd extends qh{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Kh{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(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){st("Abstract method `_fetch` called.")}}class Jh extends Kh{async _fetch(t){const e=await Dn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):On(e)}}class Zh{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class $d extends Zh{#t;#e;#s;#i;#r;#n;#h=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#l(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(Be,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Be,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const h=t[0],l=new Array(256);for(let u=0;u<256;u++)l[u]=h[u]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/255;return[n.join(","),r.join(","),o.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Rn(e)?Y('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#a.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#a.get(r),e)return this.#a.set(t,e),e;const o=`g_${this.#i}_transfer_map_${this.#h++}`,h=this.#u(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#p(s,i,n,l),h}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=B.makeHexColor(...r);const o=this.#_(e);if(e=B.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(l,l,l,u),this.#o(u);const d=(f,g)=>{const p=r[f]/255,b=o[f]/255,m=new Array(g+1);for(let v=0;v<=g;v++)m[v]=p+v/g*(b-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#a.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#b(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#b(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#c.get(t);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(t,o)),!e||!s))return o.url;const[h,l]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#l.style.color="";const g=(m,v,y)=>{const _=new Array(256),S=(u-c)/y,A=m/255,T=(v-m)/(255*y);let E=0;for(let P=0;P<=y;P++){const N=Math.round(c+P*S),D=A+P*T;for(let L=E;L<=N;L++)_[L]=D;E=N+1}for(let P=E;P<256;P++)_[P]=_[E-1];return _.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,b=o.filter=this.#g(p);return this.#o(b),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),b),o.url=this.#u(p),o.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#h=0)}#f(t){const e=this.#r.createElementNS(Be,"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)}#o(t){const e=this.#r.createElementNS(Be,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#r.createElementNS(Be,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(Be,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(Be,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#b(t,e){const s=this.#r.createElementNS(Be,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#l.style.color=t,ro(getComputedStyle(this.#l).getPropertyValue("color"))}}class Qh{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(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){st("Abstract method `_fetch` called.")}}class tl extends Qh{async _fetch(t){const e=await Dn(t,"arraybuffer");return new Uint8Array(e)}}Pt&&Y("Please use the `legacy` build in Node.js environments.");async function el(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class qd extends Zh{}class Kd extends qh{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Jd extends Kh{async _fetch(t){return el(t)}}class Zd extends Qh{async _fetch(t){return el(t)}}const Dt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function uo(a,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),a.clip(i)}class fo{getPattern(){st("Abstract method `getPattern` called.")}}class Qd extends fo{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;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Dt.STROKE||i===Dt.FILL){const r=e.current.getClippedPathBoundingBox(i,rt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=B.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),uo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else uo(t,this._bbox),n=this._createGradient(t);return n}}function go(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,u=a.width*4;let d;h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),h[s+1]>h[i+1]&&(d=s,s=i,i=d,d=r,r=o,o=d),h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,b=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,v=(h[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const y=l[n],_=l[n+1],S=l[n+2],A=l[r],T=l[r+1],E=l[r+2],P=l[o],N=l[o+1],D=l[o+2],L=Math.round(g),k=Math.round(v);let O,j,M,R,G,at,ct,At;for(let wt=L;wt<=k;wt++){if(wt<b){const Q=wt<g?0:(g-wt)/(g-b);O=f-(f-p)*Q,j=y-(y-A)*Q,M=_-(_-T)*Q,R=S-(S-E)*Q}else{let Q;wt>v?Q=1:b===v?Q=0:Q=(b-wt)/(b-v),O=p-(p-m)*Q,j=A-(A-P)*Q,M=T-(T-N)*Q,R=E-(E-D)*Q}let nt;wt<g?nt=0:wt>v?nt=1:nt=(g-wt)/(g-v),G=f-(f-m)*nt,at=y-(y-P)*nt,ct=_-(_-N)*nt,At=S-(S-D)*nt;const Vt=Math.round(Math.min(O,G)),Ee=Math.round(Math.max(O,G));let ut=u*wt+Vt*4;for(let Q=Vt;Q<=Ee;Q++)nt=(O-Q)/(O-G),nt<0?nt=0:nt>1&&(nt=1),c[ut++]=j-(j-at)*nt|0,c[ut++]=M-(M-ct)*nt|0,c[ut++]=R-(R-At)*nt|0,c[ut++]=255}}function tf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let u=0;u<l;u++,c++)go(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),go(a,e,s[c+o+1],s[c+1],s[c+o],i[c+o+1],i[c+1],i[c+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)go(a,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class ef extends fo{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),y=v.context,_=y.createImageData(u,d);if(e){const A=_.data;for(let T=0,E=A.length;T<E;T+=4)A[T]=e[0],A[T+1]=e[1],A[T+2]=e[2],A[T+3]=255}for(const A of this._figures)tf(_,A,p);return y.putImageData(_,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){uo(t,this._bbox);let n;if(i===Dt.SHADING)n=B.singularValueDecompose2dScale(rt(t));else if(n=B.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=B.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Dt.SHADING?null:this._background,e.cachedCanvases);return i!==Dt.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class sf extends fo{getPattern(){return"hotpink"}}function nf(a){switch(a[0]){case"RadialAxial":return new Qd(a);case"Mesh":return new ef(a);case"Dummy":return new sf}throw new Error(`Unknown IR type: ${a[0]}`)}const sl={COLORED:1,UNCOLORED:2};class po{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Mn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=B.singularValueDecompose2dScale(this.matrix),m=B.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],y=b[1]*m[1];let _=g,S=p,A=!1,T=!1;const E=Math.ceil(h*v),P=Math.ceil(l*y),N=Math.ceil(g*v),D=Math.ceil(p*y);E>=N?_=h:A=!0,P>=D?S=l:T=!0;const L=this.getSizeAndScale(_,this.ctx.canvas.width,v),k=this.getSizeAndScale(S,this.ctx.canvas.height,y),O=t.cachedCanvases.getCanvas("pattern",L.size,k.size),j=O.context,M=o.createCanvasGraphics(j);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),j.translate(-L.scale*c,-k.scale*u),M.transform(L.scale,0,0,k.scale,0,0),j.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=rt(M.ctx),M.executeOperatorList(s),M.endDrawing(),j.restore(),A||T){const R=O.canvas;A&&(_=h),T&&(S=l);const G=this.getSizeAndScale(_,this.ctx.canvas.width,v),at=this.getSizeAndScale(S,this.ctx.canvas.height,y),ct=G.size,At=at.size,wt=t.cachedCanvases.getCanvas("pattern-workaround",ct,At),nt=wt.context,Vt=A?Math.floor(g/h):0,Ee=T?Math.floor(p/l):0;for(let ut=0;ut<=Vt;ut++)for(let Q=0;Q<=Ee;Q++)nt.drawImage(R,ct*ut,At*Q,ct,At,0,0,ct,At);return{canvas:wt.canvas,scaleX:G.scale,scaleY:at.scale,offsetX:c,offsetY:u}}return{canvas:O.canvas,scaleX:L.scale,scaleY:k.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(po.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(rt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case sl.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case sl.UNCOLORED:const o=B.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new Md(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Dt.SHADING&&(n=B.transform(n,e.baseTransform),this.matrix&&(n=B.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function rf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Bt.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],c=s>>3,u=s&7,d=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const b=t+c;t<b;t++){const m=t<d?a[t]:255;e[f++]=m&128?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(u===0)continue;const p=t<d?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?l:h}return{srcPos:t,destPos:f}}const il=16,nl=100,of=15,rl=10,ol=1e3,Yt=16;function af(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class hf{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Nn(a,t,e,s,i,n,r,o,h,l){const[c,u,d,f,g,p]=rt(a);if(u===0&&d===0){const v=r*c+g,y=Math.round(v),_=o*f+p,S=Math.round(_),A=(r+h)*c+g,T=Math.abs(Math.round(A)-y)||1,E=(o+l)*f+p,P=Math.abs(Math.round(E)-S)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),y,S),a.drawImage(t,e,s,i,n,0,0,T,P),a.setTransform(c,u,d,f,g,p),[T,P]}if(c===0&&f===0){const v=o*d+g,y=Math.round(v),_=r*u+p,S=Math.round(_),A=(o+l)*d+g,T=Math.abs(Math.round(A)-y)||1,E=(r+h)*u+p,P=Math.abs(Math.round(E)-S)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,y,S),a.drawImage(t,e,s,i,n,0,0,P,T),a.setTransform(c,u,d,f,g,p),[P,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*h,m*l]}function lf(a){const{width:t,height:e}=a;if(t>ol||e>ol)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of a.data){let v=128;for(;v>0;)u[d++]=m&v?0:255,v>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[h]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[h]=2,++f),o=1;o<e;o++){d=o*c,l=o*n,u[d-c]!==u[d]&&(r[l]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(h=1;h<t;h++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[l+h]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[l+h]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),l=o*n,u[d]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[l+h]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[l+h]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(o=0;f&&o<=e;o++){let m=o*n;const v=m+t;for(;m<v&&!r[m];)m++;if(m===v)continue;p.moveTo(m%n,o);const y=m;let _=r[m];do{const S=g[_];do m+=S;while(!r[m]);const A=r[m];A!==5&&A!==10?(_=A,r[m]=0):(_=A&51*_>>4,r[m]&=_>>2|_<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(y!==m);--o}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class al{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Bh,this.textMatrixScale=1,this.fontMatrix=qr,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Ot.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=B.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=B.applyTransform(e,t),i=B.applyTransform(e.slice(2),t),n=B.applyTransform([e[0],e[3]],t),r=B.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){B.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,c){const u=B.bezierBoundingBox(e,s,i,n,r,o,h,l,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Dt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Dt.STROKE){e||st("Stroke bounding box must include transform.");const i=B.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=B.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Dt.FILL,e=null){return B.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function hl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0,l;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===Tn.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,y=s+7>>3,_=4294967295,S=Bt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?Yt:i,l=0,f=0;f<g;f++){const A=b-h;let T=0;const E=A>y?s:A*8-7,P=E&-8;let N=0,D=0;for(;T<P;T+=8)D=c[h++],m[l++]=D&128?_:S,m[l++]=D&64?_:S,m[l++]=D&32?_:S,m[l++]=D&16?_:S,m[l++]=D&8?_:S,m[l++]=D&4?_:S,m[l++]=D&2?_:S,m[l++]=D&1?_:S;for(;T<E;T++)N===0&&(D=c[h++],N=128),m[l++]=D&N?_:S,N>>=1}for(;l<v;)m[l++]=0;a.putImageData(o,0,d*Yt)}}else if(t.kind===Tn.RGBA_32BPP){for(f=0,p=s*Yt*4,d=0;d<n;d++)u.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Yt;d<r&&(p=s*i*4,u.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===Tn.RGB_24BPP)for(g=Yt,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),l=0,f=p;f--;)u[l++]=c[h++],u[l++]=c[h++],u[l++]=c[h++],u[l++]=255;a.putImageData(o,0,d*Yt)}else throw new Error(`bad image kind: ${t.kind}`)}function ll(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0;const l=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?Yt:i;({srcPos:h}=rf({src:l,srcPos:h,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*Yt)}}function bi(a,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)a[s]!==void 0&&(t[s]=a[s]);a.setLineDash!==void 0&&(t.setLineDash(a.getLineDash()),t.lineDashOffset=a.lineDashOffset)}function jn(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!Pt){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function cl(a,t){if(t)return!0;const e=B.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*Is.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const cf=["butt","round","square"],uf=["miter","round","bevel"],df={},ul={};class Ns{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){this.ctx=t,this.current=new al(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedCanvases=new hf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...rt(this.compositeCtx))}this.ctx.save(),jn(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=rt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>rl&&typeof s=="function",c=l?Date.now()+of:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(g=r[o],g!==fe.dependency)this[g].apply(this,n[o]);else for(const p of n[o]){const b=p.startsWith("g_")?d:f;if(!b.has(p))return b.get(p,s),o}if(o++,o===h)return o;if(l&&++u>rl){if(Date.now()>c)return s(),o;u=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",c,u;for(;n>2&&o>1||r>2&&h>1;){let d=o,f=h;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/d),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,o,h,0,0,d,f),t=c.canvas,o=d,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=rt(e);let h,l,c,u;if((t.bitmap||t.data)&&t.count>1){const E=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(E),h||(h=new Map,this._cachedBitmapsMap.set(E,h));const P=h.get(l);if(P&&!r){const N=Math.round(Math.min(o[0],o[2])+o[4]),D=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:N,offsetY:D}}c=P}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),ll(u.context,t));let d=B.transform(o,[1/s,0,0,-1/i,0,0]);d=B.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=B.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,v),_=y.context,S=f,A=g;_.translate(-S,-A),_.transform(...d),c||(c=this._scaleImage(u.canvas,Ce(_)),c=c.img,h&&r&&h.set(l,c)),_.imageSmoothingEnabled=cl(rt(_),t.interpolate),Nn(_,c,0,0,c.width,c.height,0,0,s,i),_.globalCompositeOperation="source-in";const T=B.transform(Ce(_),[1,0,0,1,-S,-A]);return _.fillStyle=r?n.getPattern(e,this,T,Dt.FILL):n,_.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=cf[t]}setLineJoin(t){this.ctx.lineJoin=uf[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...rt(this.suspendedCtx)),bi(this.suspendedCtx,n),af(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),bi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,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(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,u){let d=t.canvas,f=h-c,g=l-u;if(r){const b=B.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),v=m.context;v.drawImage(d,-f,-g),v.globalCompositeOperation="destination-atop",v.fillStyle=b,v.fillRect(0,0,s,i),v.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=b,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&o?e.filter=this.filterFactory.addAlphaFilter(o):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(o));const p=new Path2D;p.rect(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(bi(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),bi(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const c=rt(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case fe.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,y=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,y):(i.lineTo(v,o),i.lineTo(v,y),i.lineTo(r,y)),u||n.updateRectMinMax(c,[r,o,v,y]),i.closePath();break;case fe.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.curveTo:h=r,l=o,r=e[g+4],o=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case fe.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,h,l,r,o,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],o=e[g+3],g+=4;break;case fe.curveTo3:h=r,l=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],r,o,r,o,d),g+=4;break;case fe.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,o)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,Ce(e),Dt.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,Ce(e),Dt.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=df}eoClip(){this.pendingClip=ul}beginText(){this.current.textMatrix=Bh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:l}of t)s.addPath(l,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||qr,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Y("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<il?l=il:e>nl&&(l=nl),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=l&Ot.FILL_STROKE_MASK,d=!!(l&Ot.ADD_TO_PATH_FLAG),f=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let p;if((h.disableFontFace||d||f||g)&&(p=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Ot.FILL||u===Ot.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===Ot.STROKE||u===Ot.FILL_STROKE)if(n){const b=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,b,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Ot.FILL||u===Ot.FILL_STROKE)&&r.fillText(t,e,s),(u===Ot.STROKE||u===Ot.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:rt(r),x:e,y:s,fontSize:c,path:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return $(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,c=e.textHScale*l,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],b=e.textRenderingMode===Ot.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(c,-1):n.scale(c,1);let m,v;if(e.patternFill){n.save();const T=e.fillColor.getPattern(n,this,Ce(n),Dt.FILL);m=rt(n),n.restore(),n.fillStyle=T}if(e.patternStroke){n.save();const T=e.strokeColor.getPattern(n,this,Ce(n),Dt.STROKE);v=rt(n),n.restore(),n.strokeStyle=T}let y=e.lineWidth;const _=e.textMatrixScale;if(_===0||y===0){const T=e.textRenderingMode&Ot.FILL_STROKE_MASK;(T===Ot.STROKE||T===Ot.FILL_STROKE)&&(y=this.getSinglePixelWidth())}else y/=_;if(r!==1&&(n.scale(r,r),y/=r),n.lineWidth=y,s.isInvalidPDFjsFont){const T=[];let E=0;for(const P of t)T.push(P.unicode),E+=P.width;n.fillText(T.join(""),0,0),e.x+=E*p*c,n.restore(),this.compose();return}let S=0,A;for(A=0;A<u;++A){const T=t[A];if(typeof T=="number"){S+=f*T*i/1e3;continue}let E=!1;const P=(T.isSpace?h:0)+o,N=T.fontChar,D=T.accent;let L,k,O=T.width;if(d){const M=T.vmetric||g,R=-(T.vmetric?M[1]:O*.5)*p,G=M[2]*p;O=M?-M[0]:O,L=R/r,k=(S+G)/r}else L=S/r,k=0;if(s.remeasure&&O>0){const M=n.measureText(N).width*1e3/i*r;if(O<M&&this.isFontSubpixelAAEnabled){const R=O/M;E=!0,n.save(),n.scale(R,1),L/=R}else O!==M&&(L+=(O-M)/2e3*i/r)}if(this.contentVisible&&(T.isInFont||s.missingFile)){if(b&&!D)n.fillText(N,L,k);else if(this.paintChar(N,L,k,m,v),D){const M=L+i*D.offset.x/r,R=k-i*D.offset.y/r;this.paintChar(D.fontChar,M,R,m,v)}}const j=d?O*p-P*l:O*p+P*l;S+=j,E&&n.restore()}d?e.y-=S:e.x+=S*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||qr,d=t.length,f=s.textRenderingMode===Ot.INVISIBLE;let g,p,b,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=o*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const v=(p.isSpace?l:0)+h,y=i.charProcOperatorList[p.operatorListId];if(!y){Y(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(y),this.restore()),b=B.applyTransform([p.width,0],u)[0]*n+v,e.translate(b,0),s.x+=b*c}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||rt(this.ctx),n={createCanvasGraphics:r=>new Ns(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new po(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=B.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=B.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=nf(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,Ce(e),Dt.SHADING);const i=Ce(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,c]=B.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,c-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){st("Should not call beginInlineImage")}beginImageData(){st("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=rt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(rt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||Mn("TODO: Support non-isolated groups."),t.knockout&&Y("Knockout groups not supported.");const s=rt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=B.getAxialAlignedBoundingBox(t.bbox,rt(e));const n=[0,0,e.canvas.width,e.canvas.height];i=B.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,l),d=u.context;d.translate(-r,-o),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,o),e.save()),bi(e,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=rt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=B.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),jn(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=B.singularValueDecompose2dScale(rt(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(o*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),jn(this.ctx)}else jn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new al(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=lf(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=rt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let c=0,u=r.length;c<u;c+=2){const d=B.transform(h,[e,s,i,n,r[c],r[c+1]]),[f,g]=B.applyTransform([0,0],d);o.drawImage(l.canvas,f,g)}o.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:o,height:h,transform:l}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=c.context;u.save();const d=this.getObject(r,n);ll(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,Ce(e),Dt.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),Nn(e,c.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){Y("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){Y("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,c=i.length;l<c;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Pt){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;hl(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,Ce(i));i.imageSmoothingEnabled=cl(rt(i),t.interpolate),Nn(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;hl(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),Nn(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===ul?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=rt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,u=l*t;r=c<1?1/c:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const u=t*h;r=c>u?c/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const a in fe)Ns.prototype[a]!==void 0&&(Ns.prototype[fe[a]]=Ns.prototype[a]);class vi{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class ff{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return Qr(this.#t)}has(t){return this.#t.has(t)}}const js=Symbol("INTERNAL");class gf{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&Qt.DISPLAY),this.#e=!!(t&Qt.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==js&&st("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class pf{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=Qt.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new gf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(js,!1);for(const s of t.on)this.#e.get(s)._setVisible(js,!0);for(const s of t.off)this.#e.get(s)._setVisible(js,!1);this.#s=this.getHash()}}#r(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return Y(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return Mn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(Y(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Y(`Unknown optional content policy ${t.policy}.`),!0}return Y(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){Y(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(js,!1,!0);i._setVisible(js,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?Qr(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Uh;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class mf{constructor(t,{disableRange:e=!1,disableStream:s=!1}){yt(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:o}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=o,n?.length>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});yt(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?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(){yt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new bf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new vf(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class bf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=no(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class vf{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.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 e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function yf(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=On(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,b,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[b,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[b,m]=u[p];m=o(m),b&&(m=unescape(m),p===0&&(m=h(m))),g.push(m)}return g.join("")}function o(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function h(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,b){return String.fromCharCode(parseInt(b,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function dl(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function Bn(a){try{return new URL(a).origin}catch{}return null}function fl({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function gl(a){const t=a.get("Content-Disposition");if(t){let e=yf(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(no(e))return e}return null}function Hn(a,t){return a===404||a===0&&t.startsWith("file:")?new ui('Missing PDF "'+t+'".'):new Pn(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function pl(a){return a===200||a===206}function ml(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function bl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(Y(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class vl{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=dl(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new _f(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new wf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class _f{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 s=new Headers(t.headers),i=e.url;fetch(i,ml(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=Bn(n.url),!pl(n.status))throw Hn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=fl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=gl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new $e("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class wf{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,ml(n,this._withCredentials,this._abortController)).then(o=>{const h=Bn(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!pl(o.status))throw Hn(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const mo=200,bo=206;function xf(a){const t=a.response;return typeof t!="string"?t:On(t).buffer}class Sf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=dl(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=bo):i.expectedStatus=mo,e.responseType="arraybuffer",yt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||mo;if(!(n===mo&&s.expectedStatus===bo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=xf(i);if(n===bo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(Y('Missing or invalid "Content-Range" header.'),s.onError(0))}else o?s.onDone({begin:0,chunk:o}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Cf{constructor(t){this._source=t,this._manager=new Sf(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(){return yt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Af(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Tf(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Af{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=Bn(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=fl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=gl(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Hn(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.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(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Tf{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,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=Bn(this._manager.getRequestXhr(this._requestId)?.responseURL);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;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=Hn(t,this._url);for(const e of this._requests)e.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(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Ef=/^[a-z][a-z0-9\-+.]+:/i;function kf(a){if(Ef.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class Mf{constructor(t){this.source=t,this.url=kf(t.url),yt(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Pf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Of(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Pf{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 s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new ui(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(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",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new $e("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Of{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(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",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const Df=1e5,$t=30,Rf=.8;class Ht{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#h=0;#a=0;#c=null;#l=null;#d=0;#u=0;#f=Object.create(null);#o=[];#g=null;#m=[];#p=new WeakMap;#b=null;static#_=new Map;static#v=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;this.#b=[1,0,0,-1,-r,o+n],this.#a=i,this.#h=n,Ht.#O(),fs(e,s),this.#t.promise.finally(()=>{Ht.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Bt.platform;return $(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Ht.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,fs(this.#l,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Ht.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new $e("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#o}#E(t){if(this.#s)return;this.#n.ctx??=Ht.#k(this.#r);const e=this.#m,s=this.#o;for(const i of t){if(e.length>Df){Y("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#M(i)}}#M(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=B.transform(this.#b,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Ht.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*Ht.#L(o,this.#r);let c,u;n===0?(c=i[4],u=i[5]-l):(c=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*u/this.#h).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Ht.#S*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);p!==b&&Math.max(p,b)/Math.min(p,b)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Ht.#S>1&&(r=`scale(${1/Ht.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:h,fontSize:l}=s;Ht.#T(i,l*this.#u,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#v.values())t.remove();this.#v.clear()}}static#k(t=null){let e=this.#v.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#v.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==null)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.#S=t.getBoundingClientRect().height,t.remove()}static#L(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=$t,this.#T(i,$t,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+o);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,$t,$t),i.strokeText("g",0,0);let h=i.getImageData(0,0,$t,$t).data;o=0;for(let c=h.length-1-3;c>=0;c-=4)if(h[c]>0){o=Math.ceil(c/4/$t);break}i.clearRect(0,0,$t,$t),i.strokeText("A",0,$t),h=i.getImageData(0,0,$t,$t).data,r=0;for(let c=0,u=h.length;c<u;c+=4)if(h[c]>0){r=$t-Math.floor(c/4/$t);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):Rf;return this.#_.set(t,l),l}}class yi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(yi.shouldBuildText(o))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Lf=65536,Ff=100,If=5e3,Nf=Pt?Kd:Yd,jf=Pt?Jd:Jh,Bf=Pt?qd:$d,Hf=Pt?Zd:tl;function zf(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new vo,{docId:e}=t,s=a.url?Gf(a.url):null,i=a.data?Vf(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof _l?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Lf;let c=a.worker instanceof Bs?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Rn(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||jf,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||Hf,v=a.stopAtErrors!==!0,y=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,_=a.isEvalSupported!==!1,S=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Pt,A=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Pt&&(Bt.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,E=typeof a.disableFontFace=="boolean"?a.disableFontFace:Pt,P=a.fontExtraProperties===!0,N=a.enableXfa===!0,D=a.ownerDocument||globalThis.document,L=a.disableRange===!0,k=a.disableStream===!0,O=a.disableAutoFetch===!0,j=a.pdfBug===!0,M=a.CanvasFactory||Nf,R=a.FilterFactory||Bf,G=a.enableHWA===!0,at=h?h.length:a.length??NaN,ct=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Pt&&!E,At=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===Jh&&m===tl&&f&&b&&fi(f,document.baseURI)&&fi(b,document.baseURI),wt=null;Ad(u);const nt={canvasFactory:new M({ownerDocument:D,enableHWA:G}),filterFactory:new R({docId:e,ownerDocument:D}),cMapReaderFactory:At?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:At?null:new m({baseUrl:b})};if(!c){const ut={verbosity:u,port:vi.workerPort};c=ut.port?Bs.fromPort(ut):new Bs(ut),t._worker=c}const Vt={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:O,rangeChunkSize:l,length:at,docBaseUrl:d,enableXfa:N,evaluatorOptions:{maxImageSize:y,disableFontFace:E,ignoreErrors:v,isEvalSupported:_,isOffscreenCanvasSupported:S,isImageDecoderSupported:A,canvasMaxAreaInBytes:T,fontExtraProperties:P,useSystemFonts:ct,cMapUrl:At?f:null,standardFontDataUrl:At?b:null}},Ee={disableFontFace:E,fontExtraProperties:P,ownerDocument:D,pdfBug:j,styleElement:wt,loadingParams:{disableAutoFetch:O,enableXfa:N}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const ut=c.messageHandler.sendWithPromise("GetDocRequest",Vt,i?[i.buffer]:null);let Q;if(h)Q=new mf(h,{disableRange:L,disableStream:k});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Je;if(Pt)if(fi(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Je=vl}else Je=Mf;else Je=fi(s)?vl:Cf;Q=new Je({url:s,length:at,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:L,disableStream:k})}return ut.then(Je=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Vs=new mi(e,Je,c.port),ke=new Yf(Vs,t,Q,Ee,nt);t._transport=ke,Vs.send("Ready",null)})}).catch(t._capability.reject),t}function Gf(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Pt&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Vf(a){if(Pt&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return On(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(a?.length))return new Uint8Array(a);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function yl(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class vo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${vo.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class _l{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){st("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Xf{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 $(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Wf{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Vh:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new wl,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new di({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return $(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=Ue.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),o||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const b=!!(f&Qt.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=_=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(v.capability.reject(_),this._abortOperatorList({intentState:p,reason:_ instanceof Error?_:new Error(_)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Hs({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(p.renderTasks||=new Set).add(v);const y=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([_,S])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(S.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:_,optionalContentConfig:S}),v.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=Ue.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>yi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new Vh),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},If),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:u,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),c())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.opListReadCapability.reject(u);else throw u}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof io){let i=Ff;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}}if(t.streamReader.cancel(new $e(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class Uf{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){Y("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const ot=class ot{constructor({name:t=null,port:e=null,verbosity:s=Td()}={}){Xs(this,zs);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(pe(ot,vs)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(pe(ot,vs)||Si(ot,vs,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new mi("main","worker",t),this._messageHandler.on("ready",function(){}),Xn(this,zs,Un).call(this)}_initialize(){if(pe(ot,bs)||pe(ot,Gs,Yn)){this._setupFakeWorker();return}let{workerSrc:t}=ot;try{ot._isSameOrigin(window.location.href,t)||(t=ot._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new mi("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,Xn(this,zs,Un).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{Mn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){pe(ot,bs)||(Y("Setting up fake worker."),Si(ot,bs,!0)),ot._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Uf;this._port=e;const s=`fake${zl(ot,Vn)._++}`,i=new mi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new mi(s,s+"_worker",e),Xn(this,zs,Un).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,pe(ot,vs)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=pe(this,vs)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new ot(t)}static get workerSrc(){if(vi.workerSrc)return vi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return $(this,"_setupFakeWorkerGlobal",(async()=>pe(this,Gs,Yn)?pe(this,Gs,Yn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Vn=new WeakMap,bs=new WeakMap,vs=new WeakMap,zs=new WeakSet,Un=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Gs=new WeakSet,Yn=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Xs(ot,Gs),Xs(ot,Vn,0),Xs(ot,bs,!1),Xs(ot,vs),Pt&&(Si(ot,bs,!0),vi.workerSrc||="./pdf.worker.mjs"),ot._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},ot._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Bs=ot;class Yf{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new wl,this.fontLoader=new Wd({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return $(this,"annotationStorage",new co)}getRenderingIntent(t,e=Ue.ENABLE,s=null,i=!1,n=!1){let r=Qt.DISPLAY,o=lo;switch(t){case"any":r=Qt.ANY;break;case"display":break;case"print":r=Qt.PRINT;break;default:Y(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Qt.PRINT&&s instanceof Yh?s:this.annotationStorage;switch(e){case Ue.DISABLE:r+=Qt.ANNOTATIONS_DISABLE;break;case Ue.ENABLE:break;case Ue.ENABLE_FORMS:r+=Qt.ANNOTATIONS_FORMS;break;case Ue.ENABLE_STORAGE:r+=Qt.ANNOTATIONS_STORAGE,o=h.serializable;break;default:Y(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Qt.IS_EDITING),n&&(r+=Qt.OPLIST);const{ids:l,hash:c}=h.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Ht.cleanup(),this._networkStream?.cancelAllRequests(new $e("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{yt(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}yt(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=o=>{e.onProgress?.({loaded:o.loaded,total:o.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{yt(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:o}){if(o){i.close();return}yt(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new Xf(s,this))}),t.on("DocException",s=>{e._capability.reject(Ut(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Ut(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:o,pdfBug:h}=this._params;if("error"in n){const d=n.error;Y(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const l=h&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new Ud(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:l});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;yt(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const o=this.#e.get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":o.objs.resolve(s,r),r?.dataLen>wd&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&Y("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#i.set(n.refStr,t);const r=new Wf(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return yl(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.#n("GetFieldObjects")}hasJSActions(){return this.#n("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#n("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.#n("GetOptionalContentConfig").then(e=>new pf(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new ff(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Ht.cleanup()}}cachedPageNumber(t){if(!yl(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const _i=Symbol("INITIAL_DATA");class wl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:_i}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===_i)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==_i}delete(t){const e=this.#t[t];return!e||e.data===_i?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==_i&&(yield[t,e])}}}class $f{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class Hs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new $f(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Hs.#e.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Hs.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new Ns(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),Hs.#e.delete(this._canvas),this.callback(t||new io(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Hs.#e.delete(this._canvas),this.callback())))}}const qf="4.10.38",Kf="f9bea397f";function xl(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wi(a){return Math.max(0,Math.min(255,255*a))}class Sl{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=wi(t),[t,t,t]}static G_HTML([t]){const e=xl(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(wi)}static RGB_HTML(t){return`#${t.map(xl).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[wi(1-Math.min(1,t+i)),wi(1-Math.min(1,s+i)),wi(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,o=Math.min(i,n,r);return["CMYK",i,n,r,o]}}class Jf{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){st("Abstract method `_createSVG` called.")}}class yo extends Jf{_createSVG(t){return document.createElementNS(Be,t)}}class Cl{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=u}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&yi.shouldBuildText(i.name)&&l.push(u)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);l.push(m),f.append(m);continue}const b=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,b]);else if(g.value){const m=document.createTextNode(g.value);o&&yi.shouldBuildText(p)&&l.push(m),b.append(m)}}for(const u of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.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 xi=1e3,Zf=9,gs=new WeakSet;function Ke(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Qf{static create(t){switch(t.data.annotationType){case St.LINK:return new Al(t);case St.TEXT:return new tg(t);case St.WIDGET:switch(t.data.fieldType){case"Tx":return new eg(t);case"Btn":return t.data.radioButton?new Tl(t):t.data.checkBox?new ig(t):new ng(t);case"Ch":return new rg(t);case"Sig":return new sg(t)}return new ps(t);case St.POPUP:return new _o(t);case St.FREETEXT:return new El(t);case St.LINE:return new ag(t);case St.SQUARE:return new hg(t);case St.CIRCLE:return new lg(t);case St.POLYLINE:return new kl(t);case St.CARET:return new ug(t);case St.INK:return new wo(t);case St.POLYGON:return new cg(t);case St.HIGHLIGHT:return new Ml(t);case St.UNDERLINE:return new dg(t);case St.SQUIGGLY:return new fg(t);case St.STRIKEOUT:return new gg(t);case St.STAMP:return new Pl(t);case St.FILEATTACHMENT:return new pg(t);default:return new pt(t)}}}class pt{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return pt._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s?.splice(0,4,...t);const{width:l,height:c}=Ke(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof ps||(n.tabIndex=xi);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof _o){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=Ke(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(p>0||b>0){const v=`calc(${p}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;r.borderRadius=v}else if(this instanceof Tl){const v=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case ci.SOLID:r.borderStyle="solid";break;case ci.DASHED:r.borderStyle="dashed";break;case ci.BEVELED:Y("Unimplemented border style: beveled");break;case ci.INSET:Y("Unimplemented border style: inset");break;case ci.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=B.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=B.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(l[0]-d)/c}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/u}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Ke(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=Sl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:Sl[`${r}_rgb`](o)})};return $(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const o={detail:{[i]:n},target:t};r(o),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(p=>Math.fround(p));if(t.length===8){const[p,b,m,v]=t.subarray(2,6);if(i===p&&n===b&&e===m&&s===v)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:b}=r;r.borderWidth=0,o=["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="${p}" stroke-width="${b}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,b=t.length;p<b;p+=8){const m=t[p],v=t[p+1],y=t[p+2],_=t[p+3],S=c.createElement("rect"),A=(y-e)/h,T=(n-v)/l,E=(m-y)/h,P=(v-_)/l;S.setAttribute("x",A),S.setAttribute("y",T),S.setAttribute("width",E),S.setAttribute("height",P),f.append(S),o?.push(`<rect vector-effect="non-scaling-stroke" x="${A}" y="${T}" width="${E}" height="${P}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new _o({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){st("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!gs.has(l)){Y(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&gs.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class Al extends pt{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){Y('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,o=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&o.push(d)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const h=this.annotationStorage,l=[];for(const c of o){const{id:u}=c;switch(l.push(u),c.type){case"text":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!gs.has(d)){Y(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class tg extends pt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class ps extends pt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Bt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":B.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Zf,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(Kr*i))||1,u=l/c;r=Math.min(i,h(u/Kr))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/Kr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=B.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class eg extends ps{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let o=i.formattedValue||this.data.textContent?.join(`
505
+ `);return t.join("")}}function fi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ge(a){a.preventDefault()}function te(a){a.preventDefault(),a.stopPropagation()}class Xh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,l==="-"?(r+=c,o+=u):l==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}function Bd(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new di({viewBox:n,userUnit:1,scale:t,rotation:e})}function ro(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(Y(`Not a valid color format: "${a}"`),[0,0,0])}function Hd(a){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,ro(s))}t.remove()}function rt(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function Ce(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform().invertSelf();return[t,e,s,i,n,r]}function fs(a,t,e=!1,s=!0){if(t instanceof di){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Bt.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class oo{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class gi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,gi.#n||=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"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",ge,{signal:e}),t.addEventListener("pointerdown",gi.#h,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#h(t){t.stopPropagation()}#a(t){this.#s._focusEventsAllowed=!1,te(t)}#c(t){this.#s._focusEventsAllowed=!0,te(t)}#l(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#a.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ge,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",gi.#n[t]),this.#l(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#l(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#l(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class zd{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ge,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const o=n.x+(e?n.width:0);if(r>s){i=o,s=r;continue}e?o>i&&(i=o):o<i&&(i=o)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",ge,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function Ln(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class Gd{#t=0;get id(){return`${xd}${this.#t++}`}}class ao{#t=Fd();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='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>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return $(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Dn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=ao._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){Y(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class Vd{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),this.#e)return;const h={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class pi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Bt.platform;for(const[s,i,n={}]of t)for(const r of s){const o=r.startsWith("mac+");e&&o?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!o&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||te(e))}}class ho{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Hd(t),$(this,"_colors",t)}convert(t){const e=ro(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return ho._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?B.makeHexColor(...e):t}}class qe{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#h=null;#a=new Vd;#c=null;#l=null;#d=0;#u=new Set;#f=null;#o=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#b=!1;#_=null;#v=null;#w=null;#S=null;#A=!1;#E=null;#M=new Gd;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=U.NONE;#y=new Set;#R=null;#z=null;#G=null;#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#N=[0,0];#F=null;#j=null;#X=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=qe.prototype,e=r=>r.#j.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return $(this,"_keyboardManager",new pi([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,o,h,l,c,u,d,f){const g=this._signal=this.#t.signal;this.#j=t,this.#X=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=o||null,this.#m=h,this.#p=l,this.#b=c,this.#I=u||null,this.viewParameters={realScale:Is.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#a.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#v&&(clearTimeout(this.#v),this.#v=null),this.#F&&(clearTimeout(this.#F),this.#F=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return $(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return $(this,"direction",getComputedStyle(this.#j).direction)}get highlightColors(){return $(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return $(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=t}setMainHighlightColorPicker(t){this.#L=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}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}){t==="enableNewAltTextWhenAddingImage"&&(this.#b=e)}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#j.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)return s}return null}disableUserSelect(t=!1){this.#X.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*Is.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#Y(l),d=this.#C===U.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(U.HIGHLIGHT,f);return}f()}#Q(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new zd(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#P({hasSelectedText:!0}),!(this.#C!==U.HIGHLIGHT&&this.#C!==U.NONE)&&(this.#C===U.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===U.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}}#U(t=""){this.#C===U.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Q()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&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 n of e.items)for(const r of this.#o)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){Y(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#J(h);this.#Z(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){Y(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==U.NONE&&!this.isEditorHandlingKeyboard&&qe._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("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}}#P(t){Object.entries(t).some(([s,i])=>this.#V[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)}),this.#C===U.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[q.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==U.NONE,isEmpty:this.#W(),hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:this.#a.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#o){this.#o=t;for(const e of this.#o)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#M.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===U.NONE){this.setEditingState(!1),this.#at(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#ot(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#o){switch(t){case q.CREATE:this.currentLayer.addNewEditor();return;case q.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case q.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#o)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#G?.get(q.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[q.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ot(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#at(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.focusMainContainer(),this.#v=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#ht(){let t=null;for(t of this.#y);return t}updateUI(t){this.#ht===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){this.#l?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#a.undo(),this.#P({hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#W()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#W()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#W()})}cleanUndoStack(t){this.#a.cleanType(t)}#W(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.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.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Z(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Z(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==U.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#P({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#N[0]+=t,this.#N[1]+=e;const[i,n]=this.#N,r=[...this.#y],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=null,this.#N[0]=this.#N[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex;if(!e)return!1;const s=(i,n,r,o)=>{if(this.#s.has(i.id)){const h=this.#i.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return $(this,"imageManager",new ao)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,u,d)=>({x:(c-i)/r,y:1-(l+u-s)/n,width:d/r,height:u/n});break;case"180":o=(l,c,u,d)=>({x:1-(l+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":o=(l,c,u,d)=>({x:1-(c+d-i)/r,y:(l-s)/n,width:d/r,height:u/n});break;default:o=(l,c,u,d)=>({x:(l-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||h.push(o(d,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===U.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ae{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#h=!1;#a=null;#c=null;#l=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Ae.#f||=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){Ae._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Ae.#f.missing),e.setAttribute("data-l10n-id",Ae.#f["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",ge,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#o}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#h=!0,i(n))},{signal:s}),await this.#g(),t}get#o(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#h}),this.#h=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#d=await Ae._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#a.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#o}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#a?.remove(),this.#a=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Ae.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Ae.#f[`${this.#o}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class Fn{#t;#e=!1;#s=null;#i;#r;#n;#h;#a;#c=null;#l;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#h=r,this.#l=new AbortController,this.#a=AbortSignal.any([o,this.#l.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return $(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#a,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#o.bind(this),r),n.addEventListener("touchcancel",this.#o.bind(this),r),this.#r?.()}if(te(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=this.#c,{touch0X:l,touch0Y:c,touch1X:u,touch1Y:d}=h,f=u-l,g=d-c,p=r-i,b=o-n,m=Math.hypot(p,b)||1,v=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(v-m)<=Fn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const y=[(i+r)/2,(n+o)/2];this.#n?.(y,v,m)}#o(t){this.#d.abort(),this.#d=null,this.#h?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#l?.abort(),this.#l=null}}class H{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#h=!1;#a=null;#c=null;#l=null;#d=null;#u="";#f=!1;#o=null;#g=!1;#m=!1;#p=!1;#b=null;#_=0;#v=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=H._zIndex++;static _borderLineWidth=-1;static _colorManager=new ho;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=H.prototype._resizeWithKeyboard,e=qe.TRANSLATE_SMALL,s=qe.TRANSLATE_BIG;return $(this,"_resizerKeyboardManager",new pi([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],H.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;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return $(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Xd({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){if(H._l10n??=t,H._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"}),H._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);H._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){st("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}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.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}#M([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#o||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#o||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,l]=this.getBaseTranslation();r+=h,o+=l;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#o&&(this.#o[0]!==this.x||this.#o[1]!==this.y)}get _hasBeenResized(){return!!this.#o&&(this.#o[2]!==this.width||this.#o[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=H,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return H.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return H.#x(t,e,360-this.parentRotation)}#k(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#h||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#h&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#h&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#a)return;this.#a=document.createElement("div"),this.#a.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#a.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",ge,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=Bt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",te,{passive:!1,signal:r}),window.addEventListener("contextmenu",ge,{signal:r}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#I()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#L(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#l)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#l=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),undo:this.#L.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=H.MIN_SIZE/s,c=H.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,R)=>[u[0]*M+u[2]*R,u[1]*M+u[3]*R],f=this.#k(360-this.rotation),g=(M,R)=>[f[0]*M+f[2]*R,f[1]*M+f[3]*R];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(M,R)=>[0,0],b=(M,R)=>[M,R];break;case"topMiddle":p=(M,R)=>[M/2,0],b=(M,R)=>[M/2,R];break;case"topRight":m=!0,p=(M,R)=>[M,0],b=(M,R)=>[0,R];break;case"middleRight":v=!0,p=(M,R)=>[M,R/2],b=(M,R)=>[0,R/2];break;case"bottomRight":m=!0,p=(M,R)=>[M,R],b=(M,R)=>[0,0];break;case"bottomMiddle":p=(M,R)=>[M/2,R],b=(M,R)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,R)=>[0,R],b=(M,R)=>[M,0];break;case"middleLeft":v=!0,p=(M,R)=>[0,R/2],b=(M,R)=>[M,R/2];break}const y=p(o,h),_=b(o,h);let S=d(..._);const A=H._round(n+S[0]),T=H._round(r+S[1]);let E=1,P=1,N,D;if(e.fromKeyboard)({deltaX:N,deltaY:D}=e);else{const{screenX:M,screenY:R}=e,[G,at]=this.#c;[N,D]=this.screenToPageTranslation(M-G,R-at),this.#c[0]=M,this.#c[1]=R}if([N,D]=g(N/s,D/i),m){const M=Math.hypot(o,h);E=P=Math.max(Math.min(Math.hypot(_[0]-y[0]-N,_[1]-y[1]-D)/M,1/o,1/h),l/o,c/h)}else v?E=Math.max(l,Math.min(1,Math.abs(_[0]-y[0]-N)))/o:P=Math.max(c,Math.min(1,Math.abs(_[1]-y[1]-D)))/h;const L=H._round(o*E),k=H._round(h*P);S=d(...b(L,k));const O=A-S[0],j=T-S[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=L,this.height=k,this.x=O,this.y=j,this.setDims(s*L,i*k),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new gi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Ae.initialize(H._l10n),this.#s=new Ae(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#N();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),Ln(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new Fn({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),o=(A,T)=>[r[0]*A+r[2]*T,r[1]*A+r[3]*T],[h,l]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=H.MIN_SIZE/h,p=H.MIN_SIZE/l;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const b=H._round(d*n),m=H._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),y=H._round(c+v[0]),_=H._round(u+v[1]),S=o(b/2,m/2);this.x=y-S[0],this.y=_-S[1],this.width=b,this.height=m,this.setDims(h*b,l*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#V(t);return}this.#G(t)}get isSelected(){return this._uiManager.isSelected(this)}#G(t){const{isMac:e}=Bt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#V(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=l=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#G(l),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=l;if(d!==this.#r){te(l);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#v);this.#_=c,this.#v=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",te,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#n&&(this.#S||l.isPrimary)&&o(l),te(l)},r));const h=l=>{if(!this.#r||this.#r===l.pointerId){o(l);return}te(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,l=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+l+o,r-d-c-g+h,u+l+f+o,r-d-c+h];case 90:return[u+c+o,r-d+l+h,u+c+g+o,r-d+l+f+h];case 180:return[u-l-f+o,r-d+c+h,u-l+o,r-d+c+g+h];case 270:return[u-c-g+o,r-d-l-f+h,u-c+o,r-d-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#N(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#N()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){st("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[o,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#a.classList.remove("hidden"),Ln(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=this.#j.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#X.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",H._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)this.#a.append(this.#a.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#a.firstChild.before(this.#a.lastChild);let r=0;for(const o of e){const l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",H._l10nResizer[l])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){H._resizerKeyboardManager.exec(this,t)}#j(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&this.#B()}#X(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#a?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#h=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},H._telemetryTimeout),this.#w.set(s,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.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class Xd extends H{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Wh=3285377520,ie=4294901760,Te=65535;class Uh{constructor(t){this.h1=t?t&4294967295:Wh,this.h2=t?t&4294967295:Wh}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,b=t.length;p<b;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let o=0,h=0,l=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Te,g=d&Te;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*u&ie|h*f&Te,h=h<<15|h>>>17,h=h*d&ie|h*g&Te,c^=h,c=c<<13|c>>>19,c=c*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&ie|o*f&Te,o=o<<15|o>>>17,o=o*d&ie|o*g&Te,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ie|t*36045&Te,e=e*4283543511&ie|((e<<16|t>>>16)*2950163797&ie)>>>16,t^=e>>>1,t=t*444984403&ie|t*60499&Te,e=e*3301882366&ie|((e<<16|t>>>16)*3120437893&ie)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const lo=Object.freeze({map:null,hash:"",transfer:void 0});class co{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof H)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#s.set(t,e);i&&this.#i(),e instanceof H&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?Qr(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Yh(this)}get serializable(){if(this.#s.size===0)return lo;const t=new Map,e=new Uh,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof H?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:lo}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof H))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof H)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Yh extends co{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){st("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return $(this,"modifiedIds",{ids:new Set,hash:""})}}class Wd{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));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.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(yt(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#t.add(s),e?.(t)}catch{Y(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}st("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw Y(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return $(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Pt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),$(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(yt(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return $(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,S){return _.charCodeAt(S)<<24|_.charCodeAt(S+1)<<16|_.charCodeAt(S+2)<<8|_.charCodeAt(S+3)&255}function i(_,S,A,T){const E=_.substring(0,S),P=_.substring(S+A);return E+T+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,S){if(++l>30){Y("Load test font never loaded."),S();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(c.bind(null,_,S))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let b=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)b=b-p+s(u,n)|0;n<u.length&&(b=b-p+s(u+"XXX",n)|0),d=i(d,g,4,Pd(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=_,y.append(S)}this._document.body.append(y),c(u,()=>{y.remove(),e.complete()})}}class Ud{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{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)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Id(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){Y(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const In={DATA:1,ERROR:2},_t={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function $h(){}function Ut(a){if(a instanceof $e||a instanceof Zr||a instanceof ui||a instanceof Hh||a instanceof Pn||a instanceof Jr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||st('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new $e(a.message);case"InvalidPDFException":return new Zr(a.message);case"MissingPDFException":return new ui(a.message);case"PasswordException":return new Hh(a.message,a.code);case"UnexpectedResponseException":return new Pn(a.message,a.status);case"UnknownErrorException":return new Jr(a.message,a.details)}return new Jr(a.message,a.toString())}class mi{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===In.DATA)i.resolve(t.data);else if(t.callback===In.ERROR)i.reject(Ut(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:In.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:In.ERROR,callbackId:t.callbackId,reason:Ut(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:_t.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{yt(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:_t.CANCEL,streamId:n,reason:Ut(l)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(l,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:_t.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){yt(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:_t.ERROR,streamId:e,reason:Ut(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.START_COMPLETE,streamId:e,reason:Ut(l)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],o=this.streamSinks[e];switch(t.stream){case _t.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Ut(t.reason));break;case _t.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Ut(t.reason));break;case _t.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||$h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.PULL_COMPLETE,streamId:e,reason:Ut(l)})});break;case _t.ENQUEUE:if(yt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case _t.CLOSE:if(yt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case _t.ERROR:yt(r,"error should have stream controller"),r.controller.error(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Ut(t.reason)),this.#r(r,e);break;case _t.CANCEL:if(!o)break;const h=Ut(t.reason);Promise.try(o.onCancel||$h,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:_t.CANCEL_COMPLETE,streamId:e,reason:Ut(l)})}),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class qh{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){st("Abstract method `_createCanvas` called.")}}class Yd extends qh{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Kh{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(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){st("Abstract method `_fetch` called.")}}class Jh extends Kh{async _fetch(t){const e=await Dn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):On(e)}}class Zh{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class $d extends Zh{#t;#e;#s;#i;#r;#n;#h=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#l(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(Be,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Be,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const h=t[0],l=new Array(256);for(let u=0;u<256;u++)l[u]=h[u]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/255;return[n.join(","),r.join(","),o.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Rn(e)?Y('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#a.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#a.get(r),e)return this.#a.set(t,e),e;const o=`g_${this.#i}_transfer_map_${this.#h++}`,h=this.#u(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#p(s,i,n,l),h}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=B.makeHexColor(...r);const o=this.#_(e);if(e=B.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(l,l,l,u),this.#o(u);const d=(f,g)=>{const p=r[f]/255,b=o[f]/255,m=new Array(g+1);for(let v=0;v<=g;v++)m[v]=p+v/g*(b-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#a.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#b(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#b(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#c.get(t);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(t,o)),!e||!s))return o.url;const[h,l]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#l.style.color="";const g=(m,v,y)=>{const _=new Array(256),S=(u-c)/y,A=m/255,T=(v-m)/(255*y);let E=0;for(let P=0;P<=y;P++){const N=Math.round(c+P*S),D=A+P*T;for(let L=E;L<=N;L++)_[L]=D;E=N+1}for(let P=E;P<256;P++)_[P]=_[E-1];return _.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,b=o.filter=this.#g(p);return this.#o(b),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),b),o.url=this.#u(p),o.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#h=0)}#f(t){const e=this.#r.createElementNS(Be,"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)}#o(t){const e=this.#r.createElementNS(Be,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#r.createElementNS(Be,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(Be,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(Be,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#b(t,e){const s=this.#r.createElementNS(Be,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#l.style.color=t,ro(getComputedStyle(this.#l).getPropertyValue("color"))}}class Qh{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(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){st("Abstract method `_fetch` called.")}}class tl extends Qh{async _fetch(t){const e=await Dn(t,"arraybuffer");return new Uint8Array(e)}}Pt&&Y("Please use the `legacy` build in Node.js environments.");async function el(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class qd extends Zh{}class Kd extends qh{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Jd extends Kh{async _fetch(t){return el(t)}}class Zd extends Qh{async _fetch(t){return el(t)}}const Dt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function uo(a,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),a.clip(i)}class fo{getPattern(){st("Abstract method `getPattern` called.")}}class Qd extends fo{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;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Dt.STROKE||i===Dt.FILL){const r=e.current.getClippedPathBoundingBox(i,rt(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=B.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),uo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else uo(t,this._bbox),n=this._createGradient(t);return n}}function go(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,u=a.width*4;let d;h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),h[s+1]>h[i+1]&&(d=s,s=i,i=d,d=r,r=o,o=d),h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,b=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,v=(h[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const y=l[n],_=l[n+1],S=l[n+2],A=l[r],T=l[r+1],E=l[r+2],P=l[o],N=l[o+1],D=l[o+2],L=Math.round(g),k=Math.round(v);let O,j,M,R,G,at,ct,At;for(let wt=L;wt<=k;wt++){if(wt<b){const Q=wt<g?0:(g-wt)/(g-b);O=f-(f-p)*Q,j=y-(y-A)*Q,M=_-(_-T)*Q,R=S-(S-E)*Q}else{let Q;wt>v?Q=1:b===v?Q=0:Q=(b-wt)/(b-v),O=p-(p-m)*Q,j=A-(A-P)*Q,M=T-(T-N)*Q,R=E-(E-D)*Q}let nt;wt<g?nt=0:wt>v?nt=1:nt=(g-wt)/(g-v),G=f-(f-m)*nt,at=y-(y-P)*nt,ct=_-(_-N)*nt,At=S-(S-D)*nt;const Vt=Math.round(Math.min(O,G)),Ee=Math.round(Math.max(O,G));let ut=u*wt+Vt*4;for(let Q=Vt;Q<=Ee;Q++)nt=(O-Q)/(O-G),nt<0?nt=0:nt>1&&(nt=1),c[ut++]=j-(j-at)*nt|0,c[ut++]=M-(M-ct)*nt|0,c[ut++]=R-(R-At)*nt|0,c[ut++]=255}}function tf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let u=0;u<l;u++,c++)go(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),go(a,e,s[c+o+1],s[c+1],s[c+o],i[c+o+1],i[c+1],i[c+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)go(a,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class ef extends fo{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),y=v.context,_=y.createImageData(u,d);if(e){const A=_.data;for(let T=0,E=A.length;T<E;T+=4)A[T]=e[0],A[T+1]=e[1],A[T+2]=e[2],A[T+3]=255}for(const A of this._figures)tf(_,A,p);return y.putImageData(_,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){uo(t,this._bbox);let n;if(i===Dt.SHADING)n=B.singularValueDecompose2dScale(rt(t));else if(n=B.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=B.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Dt.SHADING?null:this._background,e.cachedCanvases);return i!==Dt.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class sf extends fo{getPattern(){return"hotpink"}}function nf(a){switch(a[0]){case"RadialAxial":return new Qd(a);case"Mesh":return new ef(a);case"Dummy":return new sf}throw new Error(`Unknown IR type: ${a[0]}`)}const sl={COLORED:1,UNCOLORED:2};class po{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),Mn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=B.singularValueDecompose2dScale(this.matrix),m=B.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],y=b[1]*m[1];let _=g,S=p,A=!1,T=!1;const E=Math.ceil(h*v),P=Math.ceil(l*y),N=Math.ceil(g*v),D=Math.ceil(p*y);E>=N?_=h:A=!0,P>=D?S=l:T=!0;const L=this.getSizeAndScale(_,this.ctx.canvas.width,v),k=this.getSizeAndScale(S,this.ctx.canvas.height,y),O=t.cachedCanvases.getCanvas("pattern",L.size,k.size),j=O.context,M=o.createCanvasGraphics(j);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),j.translate(-L.scale*c,-k.scale*u),M.transform(L.scale,0,0,k.scale,0,0),j.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=rt(M.ctx),M.executeOperatorList(s),M.endDrawing(),j.restore(),A||T){const R=O.canvas;A&&(_=h),T&&(S=l);const G=this.getSizeAndScale(_,this.ctx.canvas.width,v),at=this.getSizeAndScale(S,this.ctx.canvas.height,y),ct=G.size,At=at.size,wt=t.cachedCanvases.getCanvas("pattern-workaround",ct,At),nt=wt.context,Vt=A?Math.floor(g/h):0,Ee=T?Math.floor(p/l):0;for(let ut=0;ut<=Vt;ut++)for(let Q=0;Q<=Ee;Q++)nt.drawImage(R,ct*ut,At*Q,ct,At,0,0,ct,At);return{canvas:wt.canvas,scaleX:G.scale,scaleY:at.scale,offsetX:c,offsetY:u}}return{canvas:O.canvas,scaleX:L.scale,scaleY:k.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(po.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(rt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case sl.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case sl.UNCOLORED:const o=B.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new Md(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Dt.SHADING&&(n=B.transform(n,e.baseTransform),this.matrix&&(n=B.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function rf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Bt.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],c=s>>3,u=s&7,d=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const b=t+c;t<b;t++){const m=t<d?a[t]:255;e[f++]=m&128?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(u===0)continue;const p=t<d?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?l:h}return{srcPos:t,destPos:f}}const il=16,nl=100,of=15,rl=10,ol=1e3,Yt=16;function af(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class hf{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Nn(a,t,e,s,i,n,r,o,h,l){const[c,u,d,f,g,p]=rt(a);if(u===0&&d===0){const v=r*c+g,y=Math.round(v),_=o*f+p,S=Math.round(_),A=(r+h)*c+g,T=Math.abs(Math.round(A)-y)||1,E=(o+l)*f+p,P=Math.abs(Math.round(E)-S)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),y,S),a.drawImage(t,e,s,i,n,0,0,T,P),a.setTransform(c,u,d,f,g,p),[T,P]}if(c===0&&f===0){const v=o*d+g,y=Math.round(v),_=r*u+p,S=Math.round(_),A=(o+l)*d+g,T=Math.abs(Math.round(A)-y)||1,E=(r+h)*u+p,P=Math.abs(Math.round(E)-S)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,y,S),a.drawImage(t,e,s,i,n,0,0,P,T),a.setTransform(c,u,d,f,g,p),[P,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*h,m*l]}function lf(a){const{width:t,height:e}=a;if(t>ol||e>ol)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of a.data){let v=128;for(;v>0;)u[d++]=m&v?0:255,v>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[h]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[h]=2,++f),o=1;o<e;o++){d=o*c,l=o*n,u[d-c]!==u[d]&&(r[l]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(h=1;h<t;h++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[l+h]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[l+h]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),l=o*n,u[d]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[l+h]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[l+h]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(o=0;f&&o<=e;o++){let m=o*n;const v=m+t;for(;m<v&&!r[m];)m++;if(m===v)continue;p.moveTo(m%n,o);const y=m;let _=r[m];do{const S=g[_];do m+=S;while(!r[m]);const A=r[m];A!==5&&A!==10?(_=A,r[m]=0):(_=A&51*_>>4,r[m]&=_>>2|_<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(y!==m);--o}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class al{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Bh,this.textMatrixScale=1,this.fontMatrix=qr,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Ot.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=B.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=B.applyTransform(e,t),i=B.applyTransform(e.slice(2),t),n=B.applyTransform([e[0],e[3]],t),r=B.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){B.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,c){const u=B.bezierBoundingBox(e,s,i,n,r,o,h,l,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Dt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Dt.STROKE){e||st("Stroke bounding box must include transform.");const i=B.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=B.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Dt.FILL,e=null){return B.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function hl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0,l;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===Tn.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,y=s+7>>3,_=4294967295,S=Bt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?Yt:i,l=0,f=0;f<g;f++){const A=b-h;let T=0;const E=A>y?s:A*8-7,P=E&-8;let N=0,D=0;for(;T<P;T+=8)D=c[h++],m[l++]=D&128?_:S,m[l++]=D&64?_:S,m[l++]=D&32?_:S,m[l++]=D&16?_:S,m[l++]=D&8?_:S,m[l++]=D&4?_:S,m[l++]=D&2?_:S,m[l++]=D&1?_:S;for(;T<E;T++)N===0&&(D=c[h++],N=128),m[l++]=D&N?_:S,N>>=1}for(;l<v;)m[l++]=0;a.putImageData(o,0,d*Yt)}}else if(t.kind===Tn.RGBA_32BPP){for(f=0,p=s*Yt*4,d=0;d<n;d++)u.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Yt;d<r&&(p=s*i*4,u.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===Tn.RGB_24BPP)for(g=Yt,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),l=0,f=p;f--;)u[l++]=c[h++],u[l++]=c[h++],u[l++]=c[h++],u[l++]=255;a.putImageData(o,0,d*Yt)}else throw new Error(`bad image kind: ${t.kind}`)}function ll(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Yt,n=(e-i)/Yt,r=i===0?n:n+1,o=a.createImageData(s,Yt);let h=0;const l=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?Yt:i;({srcPos:h}=rf({src:l,srcPos:h,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*Yt)}}function bi(a,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)a[s]!==void 0&&(t[s]=a[s]);a.setLineDash!==void 0&&(t.setLineDash(a.getLineDash()),t.lineDashOffset=a.lineDashOffset)}function jn(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!Pt){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function cl(a,t){if(t)return!0;const e=B.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*Is.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const cf=["butt","round","square"],uf=["miter","round","bevel"],df={},ul={};class Ns{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){this.ctx=t,this.current=new al(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedCanvases=new hf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...rt(this.compositeCtx))}this.ctx.save(),jn(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=rt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>rl&&typeof s=="function",c=l?Date.now()+of:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(g=r[o],g!==fe.dependency)this[g].apply(this,n[o]);else for(const p of n[o]){const b=p.startsWith("g_")?d:f;if(!b.has(p))return b.get(p,s),o}if(o++,o===h)return o;if(l&&++u>rl){if(Date.now()>c)return s(),o;u=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",c,u;for(;n>2&&o>1||r>2&&h>1;){let d=o,f=h;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/d),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,o,h,0,0,d,f),t=c.canvas,o=d,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=rt(e);let h,l,c,u;if((t.bitmap||t.data)&&t.count>1){const E=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(E),h||(h=new Map,this._cachedBitmapsMap.set(E,h));const P=h.get(l);if(P&&!r){const N=Math.round(Math.min(o[0],o[2])+o[4]),D=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:N,offsetY:D}}c=P}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),ll(u.context,t));let d=B.transform(o,[1/s,0,0,-1/i,0,0]);d=B.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=B.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,v),_=y.context,S=f,A=g;_.translate(-S,-A),_.transform(...d),c||(c=this._scaleImage(u.canvas,Ce(_)),c=c.img,h&&r&&h.set(l,c)),_.imageSmoothingEnabled=cl(rt(_),t.interpolate),Nn(_,c,0,0,c.width,c.height,0,0,s,i),_.globalCompositeOperation="source-in";const T=B.transform(Ce(_),[1,0,0,1,-S,-A]);return _.fillStyle=r?n.getPattern(e,this,T,Dt.FILL):n,_.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=cf[t]}setLineJoin(t){this.ctx.lineJoin=uf[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...rt(this.suspendedCtx)),bi(this.suspendedCtx,n),af(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),bi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,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(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,u){let d=t.canvas,f=h-c,g=l-u;if(r){const b=B.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),v=m.context;v.drawImage(d,-f,-g),v.globalCompositeOperation="destination-atop",v.fillStyle=b,v.fillRect(0,0,s,i),v.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=b,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&o?e.filter=this.filterFactory.addAlphaFilter(o):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(o));const p=new Path2D;p.rect(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(bi(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),bi(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const c=rt(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case fe.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,y=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,y):(i.lineTo(v,o),i.lineTo(v,y),i.lineTo(r,y)),u||n.updateRectMinMax(c,[r,o,v,y]),i.closePath();break;case fe.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case fe.curveTo:h=r,l=o,r=e[g+4],o=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case fe.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,h,l,r,o,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],o=e[g+3],g+=4;break;case fe.curveTo3:h=r,l=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],r,o,r,o,d),g+=4;break;case fe.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,o)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,Ce(e),Dt.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,Ce(e),Dt.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=df}eoClip(){this.pendingClip=ul}beginText(){this.current.textMatrix=Bh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:l}of t)s.addPath(l,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||qr,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Y("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<il?l=il:e>nl&&(l=nl),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=l&Ot.FILL_STROKE_MASK,d=!!(l&Ot.ADD_TO_PATH_FLAG),f=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let p;if((h.disableFontFace||d||f||g)&&(p=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Ot.FILL||u===Ot.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===Ot.STROKE||u===Ot.FILL_STROKE)if(n){const b=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,b,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Ot.FILL||u===Ot.FILL_STROKE)&&r.fillText(t,e,s),(u===Ot.STROKE||u===Ot.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:rt(r),x:e,y:s,fontSize:c,path:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return $(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,c=e.textHScale*l,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],b=e.textRenderingMode===Ot.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(c,-1):n.scale(c,1);let m,v;if(e.patternFill){n.save();const T=e.fillColor.getPattern(n,this,Ce(n),Dt.FILL);m=rt(n),n.restore(),n.fillStyle=T}if(e.patternStroke){n.save();const T=e.strokeColor.getPattern(n,this,Ce(n),Dt.STROKE);v=rt(n),n.restore(),n.strokeStyle=T}let y=e.lineWidth;const _=e.textMatrixScale;if(_===0||y===0){const T=e.textRenderingMode&Ot.FILL_STROKE_MASK;(T===Ot.STROKE||T===Ot.FILL_STROKE)&&(y=this.getSinglePixelWidth())}else y/=_;if(r!==1&&(n.scale(r,r),y/=r),n.lineWidth=y,s.isInvalidPDFjsFont){const T=[];let E=0;for(const P of t)T.push(P.unicode),E+=P.width;n.fillText(T.join(""),0,0),e.x+=E*p*c,n.restore(),this.compose();return}let S=0,A;for(A=0;A<u;++A){const T=t[A];if(typeof T=="number"){S+=f*T*i/1e3;continue}let E=!1;const P=(T.isSpace?h:0)+o,N=T.fontChar,D=T.accent;let L,k,O=T.width;if(d){const M=T.vmetric||g,R=-(T.vmetric?M[1]:O*.5)*p,G=M[2]*p;O=M?-M[0]:O,L=R/r,k=(S+G)/r}else L=S/r,k=0;if(s.remeasure&&O>0){const M=n.measureText(N).width*1e3/i*r;if(O<M&&this.isFontSubpixelAAEnabled){const R=O/M;E=!0,n.save(),n.scale(R,1),L/=R}else O!==M&&(L+=(O-M)/2e3*i/r)}if(this.contentVisible&&(T.isInFont||s.missingFile)){if(b&&!D)n.fillText(N,L,k);else if(this.paintChar(N,L,k,m,v),D){const M=L+i*D.offset.x/r,R=k-i*D.offset.y/r;this.paintChar(D.fontChar,M,R,m,v)}}const j=d?O*p-P*l:O*p+P*l;S+=j,E&&n.restore()}d?e.y-=S:e.x+=S*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||qr,d=t.length,f=s.textRenderingMode===Ot.INVISIBLE;let g,p,b,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=o*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const v=(p.isSpace?l:0)+h,y=i.charProcOperatorList[p.operatorListId];if(!y){Y(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(y),this.restore()),b=B.applyTransform([p.width,0],u)[0]*n+v,e.translate(b,0),s.x+=b*c}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||rt(this.ctx),n={createCanvasGraphics:r=>new Ns(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new po(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=B.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=B.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=nf(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,Ce(e),Dt.SHADING);const i=Ce(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,c]=B.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,c-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){st("Should not call beginInlineImage")}beginImageData(){st("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=rt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(rt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||Mn("TODO: Support non-isolated groups."),t.knockout&&Y("Knockout groups not supported.");const s=rt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=B.getAxialAlignedBoundingBox(t.bbox,rt(e));const n=[0,0,e.canvas.width,e.canvas.height];i=B.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,l),d=u.context;d.translate(-r,-o),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,o),e.save()),bi(e,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=rt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=B.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),jn(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=B.singularValueDecompose2dScale(rt(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(o*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),jn(this.ctx)}else jn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new al(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=lf(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=rt(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let c=0,u=r.length;c<u;c+=2){const d=B.transform(h,[e,s,i,n,r[c],r[c+1]]),[f,g]=B.applyTransform([0,0],d);o.drawImage(l.canvas,f,g)}o.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:o,height:h,transform:l}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=c.context;u.save();const d=this.getObject(r,n);ll(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,Ce(e),Dt.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),Nn(e,c.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){Y("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){Y("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,c=i.length;l<c;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Pt){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;hl(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,Ce(i));i.imageSmoothingEnabled=cl(rt(i),t.interpolate),Nn(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;hl(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),Nn(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===ul?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=rt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,u=l*t;r=c<1?1/c:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const u=t*h;r=c>u?c/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const a in fe)Ns.prototype[a]!==void 0&&(Ns.prototype[fe[a]]=Ns.prototype[a]);class vi{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class ff{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return Qr(this.#t)}has(t){return this.#t.has(t)}}const js=Symbol("INTERNAL");class gf{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&Qt.DISPLAY),this.#e=!!(t&Qt.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==js&&st("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class pf{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=Qt.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new gf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(js,!1);for(const s of t.on)this.#e.get(s)._setVisible(js,!0);for(const s of t.off)this.#e.get(s)._setVisible(js,!1);this.#s=this.getHash()}}#r(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return Y(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return Mn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(Y(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return Y(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Y(`Unknown optional content policy ${t.policy}.`),!0}return Y(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){Y(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(js,!1,!0);i._setVisible(js,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?Qr(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Uh;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class mf{constructor(t,{disableRange:e=!1,disableStream:s=!1}){yt(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:o}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=o,n?.length>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});yt(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?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(){yt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new bf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new vf(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class bf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=no(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class vf{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.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 e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function yf(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=On(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,b,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[b,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[b,m]=u[p];m=o(m),b&&(m=unescape(m),p===0&&(m=h(m))),g.push(m)}return g.join("")}function o(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function h(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,b){return String.fromCharCode(parseInt(b,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function dl(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function Bn(a){try{return new URL(a).origin}catch{}return null}function fl({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function gl(a){const t=a.get("Content-Disposition");if(t){let e=yf(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(no(e))return e}return null}function Hn(a,t){return a===404||a===0&&t.startsWith("file:")?new ui('Missing PDF "'+t+'".'):new Pn(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function pl(a){return a===200||a===206}function ml(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function bl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(Y(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class vl{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=dl(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new _f(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new wf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class _f{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 s=new Headers(t.headers),i=e.url;fetch(i,ml(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=Bn(n.url),!pl(n.status))throw Hn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=fl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=gl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new $e("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class wf{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,ml(n,this._withCredentials,this._abortController)).then(o=>{const h=Bn(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!pl(o.status))throw Hn(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:bl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const mo=200,bo=206;function xf(a){const t=a.response;return typeof t!="string"?t:On(t).buffer}class Sf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=dl(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=bo):i.expectedStatus=mo,e.responseType="arraybuffer",yt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||mo;if(!(n===mo&&s.expectedStatus===bo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=xf(i);if(n===bo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(Y('Missing or invalid "Content-Range" header.'),s.onError(0))}else o?s.onDone({begin:0,chunk:o}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Cf{constructor(t){this._source=t,this._manager=new Sf(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(){return yt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Af(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Tf(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Af{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=Bn(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=fl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=gl(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Hn(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.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(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Tf{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,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=Bn(this._manager.getRequestXhr(this._requestId)?.responseURL);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;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=Hn(t,this._url);for(const e of this._requests)e.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(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Ef=/^[a-z][a-z0-9\-+.]+:/i;function kf(a){if(Ef.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class Mf{constructor(t){this.source=t,this.url=kf(t.url),yt(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return yt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Pf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Of(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Pf{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 s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new ui(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(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",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new $e("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Of{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(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",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const Df=1e5,$t=30,Rf=.8;class Ht{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#h=0;#a=0;#c=null;#l=null;#d=0;#u=0;#f=Object.create(null);#o=[];#g=null;#m=[];#p=new WeakMap;#b=null;static#_=new Map;static#v=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;this.#b=[1,0,0,-1,-r,o+n],this.#a=i,this.#h=n,Ht.#O(),fs(e,s),this.#t.promise.finally(()=>{Ht.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Bt.platform;return $(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Ht.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,fs(this.#l,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Ht.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new $e("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#o}#E(t){if(this.#s)return;this.#n.ctx??=Ht.#k(this.#r);const e=this.#m,s=this.#o;for(const i of t){if(e.length>Df){Y("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#M(i)}}#M(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=B.transform(this.#b,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Ht.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*Ht.#L(o,this.#r);let c,u;n===0?(c=i[4],u=i[5]-l):(c=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*u/this.#h).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Ht.#S*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);p!==b&&Math.max(p,b)/Math.min(p,b)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Ht.#S>1&&(r=`scale(${1/Ht.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:h,fontSize:l}=s;Ht.#T(i,l*this.#u,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#v.values())t.remove();this.#v.clear()}}static#k(t=null){let e=this.#v.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#v.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==null)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.#S=t.getBoundingClientRect().height,t.remove()}static#L(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=$t,this.#T(i,$t,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+o);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,$t,$t),i.strokeText("g",0,0);let h=i.getImageData(0,0,$t,$t).data;o=0;for(let c=h.length-1-3;c>=0;c-=4)if(h[c]>0){o=Math.ceil(c/4/$t);break}i.clearRect(0,0,$t,$t),i.strokeText("A",0,$t),h=i.getImageData(0,0,$t,$t).data,r=0;for(let c=0,u=h.length;c<u;c+=4)if(h[c]>0){r=$t-Math.floor(c/4/$t);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):Rf;return this.#_.set(t,l),l}}class yi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(yi.shouldBuildText(o))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Lf=65536,Ff=100,If=5e3,Nf=Pt?Kd:Yd,jf=Pt?Jd:Jh,Bf=Pt?qd:$d,Hf=Pt?Zd:tl;function zf(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new vo,{docId:e}=t,s=a.url?Gf(a.url):null,i=a.data?Vf(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof _l?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Lf;let c=a.worker instanceof Bs?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Rn(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||jf,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||Hf,v=a.stopAtErrors!==!0,y=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,_=a.isEvalSupported!==!1,S=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Pt,A=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Pt&&(Bt.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,E=typeof a.disableFontFace=="boolean"?a.disableFontFace:Pt,P=a.fontExtraProperties===!0,N=a.enableXfa===!0,D=a.ownerDocument||globalThis.document,L=a.disableRange===!0,k=a.disableStream===!0,O=a.disableAutoFetch===!0,j=a.pdfBug===!0,M=a.CanvasFactory||Nf,R=a.FilterFactory||Bf,G=a.enableHWA===!0,at=h?h.length:a.length??NaN,ct=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Pt&&!E,At=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===Jh&&m===tl&&f&&b&&fi(f,document.baseURI)&&fi(b,document.baseURI),wt=null;Ad(u);const nt={canvasFactory:new M({ownerDocument:D,enableHWA:G}),filterFactory:new R({docId:e,ownerDocument:D}),cMapReaderFactory:At?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:At?null:new m({baseUrl:b})};if(!c){const ut={verbosity:u,port:vi.workerPort};c=ut.port?Bs.fromPort(ut):new Bs(ut),t._worker=c}const Vt={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:O,rangeChunkSize:l,length:at,docBaseUrl:d,enableXfa:N,evaluatorOptions:{maxImageSize:y,disableFontFace:E,ignoreErrors:v,isEvalSupported:_,isOffscreenCanvasSupported:S,isImageDecoderSupported:A,canvasMaxAreaInBytes:T,fontExtraProperties:P,useSystemFonts:ct,cMapUrl:At?f:null,standardFontDataUrl:At?b:null}},Ee={disableFontFace:E,fontExtraProperties:P,ownerDocument:D,pdfBug:j,styleElement:wt,loadingParams:{disableAutoFetch:O,enableXfa:N}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const ut=c.messageHandler.sendWithPromise("GetDocRequest",Vt,i?[i.buffer]:null);let Q;if(h)Q=new mf(h,{disableRange:L,disableStream:k});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Je;if(Pt)if(fi(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Je=vl}else Je=Mf;else Je=fi(s)?vl:Cf;Q=new Je({url:s,length:at,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:L,disableStream:k})}return ut.then(Je=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Vs=new mi(e,Je,c.port),ke=new Yf(Vs,t,Q,Ee,nt);t._transport=ke,Vs.send("Ready",null)})}).catch(t._capability.reject),t}function Gf(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Pt&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Vf(a){if(Pt&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return On(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(a?.length))return new Uint8Array(a);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function yl(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class vo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${vo.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class _l{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){st("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Xf{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 $(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Wf{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Vh:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new wl,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new di({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return $(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=Ue.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),o||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const b=!!(f&Qt.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=_=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(v.capability.reject(_),this._abortOperatorList({intentState:p,reason:_ instanceof Error?_:new Error(_)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Hs({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(p.renderTasks||=new Set).add(v);const y=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([_,S])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(S.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:_,optionalContentConfig:S}),v.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=Ue.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>yi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new Vh),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},If),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:u,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),c())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.opListReadCapability.reject(u);else throw u}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof io){let i=Ff;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}}if(t.streamReader.cancel(new $e(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class Uf{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){Y("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const ot=class ot{constructor({name:t=null,port:e=null,verbosity:s=Td()}={}){Xs(this,zs);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(pe(ot,vs)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(pe(ot,vs)||Si(ot,vs,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new mi("main","worker",t),this._messageHandler.on("ready",function(){}),Xn(this,zs,Un).call(this)}_initialize(){if(pe(ot,bs)||pe(ot,Gs,Yn)){this._setupFakeWorker();return}let{workerSrc:t}=ot;try{ot._isSameOrigin(window.location.href,t)||(t=ot._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new mi("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,Xn(this,zs,Un).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{Mn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){pe(ot,bs)||(Y("Setting up fake worker."),Si(ot,bs,!0)),ot._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Uf;this._port=e;const s=`fake${zl(ot,Vn)._++}`,i=new mi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new mi(s,s+"_worker",e),Xn(this,zs,Un).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,pe(ot,vs)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=pe(this,vs)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new ot(t)}static get workerSrc(){if(vi.workerSrc)return vi.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return $(this,"_setupFakeWorkerGlobal",(async()=>pe(this,Gs,Yn)?pe(this,Gs,Yn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Vn=new WeakMap,bs=new WeakMap,vs=new WeakMap,zs=new WeakSet,Un=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Gs=new WeakSet,Yn=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Xs(ot,Gs),Xs(ot,Vn,0),Xs(ot,bs,!1),Xs(ot,vs),Pt&&(Si(ot,bs,!0),vi.workerSrc||="./pdf.worker.mjs"),ot._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},ot._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let Bs=ot;class Yf{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new wl,this.fontLoader=new Wd({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return $(this,"annotationStorage",new co)}getRenderingIntent(t,e=Ue.ENABLE,s=null,i=!1,n=!1){let r=Qt.DISPLAY,o=lo;switch(t){case"any":r=Qt.ANY;break;case"display":break;case"print":r=Qt.PRINT;break;default:Y(`getRenderingIntent - invalid intent: ${t}`)}const h=r&Qt.PRINT&&s instanceof Yh?s:this.annotationStorage;switch(e){case Ue.DISABLE:r+=Qt.ANNOTATIONS_DISABLE;break;case Ue.ENABLE:break;case Ue.ENABLE_FORMS:r+=Qt.ANNOTATIONS_FORMS;break;case Ue.ENABLE_STORAGE:r+=Qt.ANNOTATIONS_STORAGE,o=h.serializable;break;default:Y(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=Qt.IS_EDITING),n&&(r+=Qt.OPLIST);const{ids:l,hash:c}=h.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Ht.cleanup(),this._networkStream?.cancelAllRequests(new $e("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{yt(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}yt(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=o=>{e.onProgress?.({loaded:o.loaded,total:o.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{yt(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:o}){if(o){i.close();return}yt(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new Xf(s,this))}),t.on("DocException",s=>{e._capability.reject(Ut(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Ut(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:o,pdfBug:h}=this._params;if("error"in n){const d=n.error;Y(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const l=h&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new Ud(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:l});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;yt(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const o=this.#e.get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":o.objs.resolve(s,r),r?.dataLen>wd&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&Y("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#i.set(n.refStr,t);const r=new Wf(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return yl(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.#n("GetFieldObjects")}hasJSActions(){return this.#n("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#n("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.#n("GetOptionalContentConfig").then(e=>new pf(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new ff(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Ht.cleanup()}}cachedPageNumber(t){if(!yl(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const _i=Symbol("INITIAL_DATA");class wl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:_i}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===_i)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==_i}delete(t){const e=this.#t[t];return!e||e.data===_i?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==_i&&(yield[t,e])}}}class $f{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class Hs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new $f(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Hs.#e.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Hs.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new Ns(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),Hs.#e.delete(this._canvas),this.callback(t||new io(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Hs.#e.delete(this._canvas),this.callback())))}}const qf="4.10.38",Kf="f9bea397f";function xl(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function wi(a){return Math.max(0,Math.min(255,255*a))}class Sl{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=wi(t),[t,t,t]}static G_HTML([t]){const e=xl(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(wi)}static RGB_HTML(t){return`#${t.map(xl).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[wi(1-Math.min(1,t+i)),wi(1-Math.min(1,s+i)),wi(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,o=Math.min(i,n,r);return["CMYK",i,n,r,o]}}class Jf{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){st("Abstract method `_createSVG` called.")}}class yo extends Jf{_createSVG(t){return document.createElementNS(Be,t)}}class Cl{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=u}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&yi.shouldBuildText(i.name)&&l.push(u)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);l.push(m),f.append(m);continue}const b=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,b]);else if(g.value){const m=document.createTextNode(g.value);o&&yi.shouldBuildText(p)&&l.push(m),b.append(m)}}for(const u of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.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 xi=1e3,Zf=9,gs=new WeakSet;function Ke(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class Qf{static create(t){switch(t.data.annotationType){case St.LINK:return new Al(t);case St.TEXT:return new tg(t);case St.WIDGET:switch(t.data.fieldType){case"Tx":return new eg(t);case"Btn":return t.data.radioButton?new Tl(t):t.data.checkBox?new ig(t):new ng(t);case"Ch":return new rg(t);case"Sig":return new sg(t)}return new ps(t);case St.POPUP:return new _o(t);case St.FREETEXT:return new El(t);case St.LINE:return new ag(t);case St.SQUARE:return new hg(t);case St.CIRCLE:return new lg(t);case St.POLYLINE:return new kl(t);case St.CARET:return new ug(t);case St.INK:return new wo(t);case St.POLYGON:return new cg(t);case St.HIGHLIGHT:return new Ml(t);case St.UNDERLINE:return new dg(t);case St.SQUIGGLY:return new fg(t);case St.STRIKEOUT:return new gg(t);case St.STAMP:return new Pl(t);case St.FILEATTACHMENT:return new pg(t);default:return new pt(t)}}}class pt{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return pt._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s?.splice(0,4,...t);const{width:l,height:c}=Ke(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof ps||(n.tabIndex=xi);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof _o){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=Ke(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(p>0||b>0){const v=`calc(${p}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;r.borderRadius=v}else if(this instanceof Tl){const v=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case ci.SOLID:r.borderStyle="solid";break;case ci.DASHED:r.borderStyle="dashed";break;case ci.BEVELED:Y("Unimplemented border style: beveled");break;case ci.INSET:Y("Unimplemented border style: inset");break;case ci.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=B.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=B.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(l[0]-d)/c}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/u}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Ke(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=Sl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:Sl[`${r}_rgb`](o)})};return $(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const o={detail:{[i]:n},target:t};r(o),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(p=>Math.fround(p));if(t.length===8){const[p,b,m,v]=t.subarray(2,6);if(i===p&&n===b&&e===m&&s===v)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:b}=r;r.borderWidth=0,o=["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="${p}" stroke-width="${b}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,b=t.length;p<b;p+=8){const m=t[p],v=t[p+1],y=t[p+2],_=t[p+3],S=c.createElement("rect"),A=(y-e)/h,T=(n-v)/l,E=(m-y)/h,P=(v-_)/l;S.setAttribute("x",A),S.setAttribute("y",T),S.setAttribute("width",E),S.setAttribute("height",P),f.append(S),o?.push(`<rect vector-effect="non-scaling-stroke" x="${A}" y="${T}" width="${E}" height="${P}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new _o({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){st("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!gs.has(l)){Y(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&gs.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class Al extends pt{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){Y('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,o=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&o.push(d)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const h=this.annotationStorage,l=[];for(const c of o){const{id:u}=c;switch(l.push(u),c.type){case"text":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!gs.has(d)){Y(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class tg extends pt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class ps extends pt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Bt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":B.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Zf,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(Kr*i))||1,u=l/c;r=Math.min(i,h(u/Kr))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/Kr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=B.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class eg extends ps{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let o=i.formattedValue||this.data.textContent?.join(`
506
506
  `)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const h={userValue:n,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=o??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",o??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),gs.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=xi,this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",c=>{t.setValue(e,{value:c.target.value}),this.setPropertyOnSiblings(s,"value",c.target.value,"value"),h.formattedValue=null}),s.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue??"";s.value=h.userValue=u,h.formattedValue=null});let l=c=>{const{formattedValue:u}=h;u!=null&&(c.target.value=u),c.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",u=>{if(h.focused)return;const{target:d}=u;h.userValue&&(d.value=h.userValue),h.lastCommittedValue=d.value,h.commitKey=1,this.data.actions?.Focus||(h.focused=!0)}),s.addEventListener("updatefromsandbox",u=>{this.showElementAndHideCanvas(u.target);const d={value(f){h.userValue=f.detail.value??"",t.setValue(e,{value:h.userValue.toString()}),f.target.value=h.userValue},formattedValue(f){const{formattedValue:g}=f.detail;h.formattedValue=g,g!=null&&f.target!==document.activeElement&&(f.target.value=g),t.setValue(e,{formattedValue:g})},selRange(f){f.target.setSelectionRange(...f.detail.selRange)},charLimit:f=>{const{charLimit:g}=f.detail,{target:p}=f;if(g===0){p.removeAttribute("maxLength");return}p.setAttribute("maxLength",g);let b=h.userValue;!b||b.length<=g||(b=b.slice(0,g),p.value=h.userValue=b,t.setValue(e,{value:b}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:p.selectionStart,selEnd:p.selectionEnd}}))}};this._dispatchEventFromSandbox(d,u)}),s.addEventListener("keydown",u=>{h.commitKey=1;let d=-1;if(u.key==="Escape"?d=0:u.key==="Enter"&&!this.data.multiLine?d=2:u.key==="Tab"&&(h.commitKey=3),d===-1)return;const{value:f}=u.target;h.lastCommittedValue!==f&&(h.lastCommittedValue=f,h.userValue=f,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:f,willCommit:!0,commitKey:d,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}))});const c=l;l=null,s.addEventListener("blur",u=>{if(!h.focused||!u.relatedTarget)return;this.data.actions?.Blur||(h.focused=!1);const{value:d}=u.target;h.userValue=d,h.lastCommittedValue!==d&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:d,willCommit:!0,commitKey:h.commitKey,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}),c(u)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",u=>{h.lastCommittedValue=null;const{data:d,target:f}=u,{value:g,selectionStart:p,selectionEnd:b}=f;let m=p,v=b;switch(u.inputType){case"deleteWordBackward":{const y=g.substring(0,p).match(/\w*[^\w]*$/);y&&(m-=y[0].length);break}case"deleteWordForward":{const y=g.substring(p).match(/^[^\w]*\w*/);y&&(v+=y[0].length);break}case"deleteContentBackward":p===b&&(m-=1);break;case"deleteContentForward":p===b&&(v+=1);break}u.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:g,change:d||"",willCommit:!1,selStart:m,selEnd:v}})}),this._setEventListeners(s,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],u=>u.target.value)}if(l&&s.addEventListener("blur",l),this.data.comb){const u=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.letterSpacing=`calc(${u}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class sg extends ps{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class ig extends ps{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return gs.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=xi,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s)){const c=h&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=c),t.setValue(l.id,{value:c})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Tl extends ps{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(gs.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=xi,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue;r.target.checked=o!=null&&o===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",o=>{const h={value:l=>{const c=r===l.detail.value;for(const u of this._getElementsByName(l.target.name)){const d=c&&u.id===s;u.domElement&&(u.domElement.checked=d),t.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(h,o)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class ng extends Al{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class rg extends ps{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");gs.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=xi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue;for(const d of i.options)d.selected=d.value===u});for(const c of this.data.options){const u=document.createElement("option");u.textContent=c.displayValue,u.value=c.exportValue,s.value.includes(c.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let r=null;if(n){const c=document.createElement("option");c.value=" ",c.setAttribute("hidden",!0),c.setAttribute("selected",!0),i.prepend(c),r=()=>{c.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const o=c=>{const u=c?"value":"textContent",{options:d,multiple:f}=i;return f?Array.prototype.filter.call(d,g=>g.selected).map(g=>g[u]):d.selectedIndex===-1?null:d[d.selectedIndex][u]};let h=o(!1);const l=c=>{const u=c.target.options;return Array.prototype.map.call(u,d=>({displayValue:d.textContent,exportValue:d.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",c=>{const u={value(d){r?.();const f=d.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const p of i.options)p.selected=g.has(p.value);t.setValue(e,{value:o(!0)}),h=o(!1)},multipleSelection(d){i.multiple=!0},remove(d){const f=i.options,g=d.detail.remove;f[g].selected=!1,i.remove(g),f.length>0&&Array.prototype.findIndex.call(f,b=>b.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=o(!1)},insert(d){const{index:f,displayValue:g,exportValue:p}=d.detail.insert,b=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,b?b.before(m):i.append(m),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},items(d){const{items:f}=d.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:b}=g,m=document.createElement("option");m.textContent=p,m.value=b,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},indices(d){const f=new Set(d.detail.indices);for(const g of d.target.options)g.selected=f.has(g.index);t.setValue(e,{value:o(!0)}),h=o(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,c)}),i.addEventListener("input",c=>{const u=o(!0),d=o(!1);t.setValue(e,{value:u}),c.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:d,changeEx:u,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],c=>c.target.value)):i.addEventListener("input",function(c){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class _o extends pt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:pt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new og({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${so}${s}`).join(",")),this.container}}class og{#t=this.#E.bind(this);#e=this.#T.bind(this);#s=this.#k.bind(this);#i=this.#x.bind(this);#r=null;#n=null;#h=null;#a=null;#c=null;#l=null;#d=null;#u=!1;#f=null;#o=null;#g=null;#m=null;#p=null;#b=null;#_=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:l,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#h=r,this.#m=o,this.#l=h,this.#r=e,this.#g=l,this.#d=c,this.#c=s,this.#a=Xh.toDateObject(n),this.trigger=s.flatMap(d=>d.getElementsToTriggerPopup());for(const d of this.trigger)d.addEventListener("click",this.#i),d.addEventListener("mouseenter",this.#s),d.addEventListener("mouseleave",this.#e),d.classList.add("popupTriggerArea");for(const d of s)d.container?.addEventListener("keydown",this.#t);this.#n.hidden=!0,u&&this.#x()}render(){if(this.#f)return;const t=this.#f=document.createElement("div");if(t.className="popup",this.#r){const n=t.style.outlineColor=B.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=B.makeHexColor(...this.#r.map(o=>Math.floor(.7*(255-o)+o)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=this.#p,t.append(e),this.#a){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#a.valueOf()})),e.append(n)}const i=this.#v;if(i)Cl.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#h);t.append(n)}this.#n.append(t)}get#v(){const t=this.#m,e=this.#h;return t?.str&&(!e?.str||e.str===t.str)&&this.#m.html||null}get#w(){return this.#v?.attributes?.style?.fontSize||0}get#S(){return this.#v?.attributes?.style?.color||null}#A(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#S,fontSize:this.#w?`calc(${this.#w}px * var(--scale-factor))`:""}};for(const n of t.split(`
507
507
  `))e.push({name:"span",value:n,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const o=i[n];s.append(document.createTextNode(o)),n<r-1&&s.append(document.createElement("br"))}return s}#E(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#u)&&this.#x()}updateEdited({rect:t,popupContent:e}){this.#b||={contentsObj:this.#h,richText:this.#m},t&&(this.#o=null),e&&(this.#m=this.#A(e),this.#h=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#b&&({contentsObj:this.#h,richText:this.#m}=this.#b,this.#b=null,this.#f?.remove(),this.#f=null,this.#o=null)}#M(){if(this.#o!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#l;let r=!!this.#d,o=r?this.#d:this.#g;for(const g of this.#c)if(!o||B.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const h=B.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),c=r?o[2]-o[0]+5:0,u=h[0]+c,d=h[1];this.#o=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#o[0]}%`,f.top=`${this.#o[1]}%`}#x(){this.#u=!this.#u,this.#u?(this.#k(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#T(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#k(){this.#f||this.render(),this.isVisible?this.#u&&this.#n.classList.add("focused"):(this.#M(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#T(){this.#n.classList.remove("focused"),!(this.#u||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#n.hidden=!0)}maybeShow(){this.#_&&(this.#f||this.#k(),this.#_=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class El extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=U.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class ag extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Ke(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class hg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Ke(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class lg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Ke(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class kl extends pt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:r}=Ke(t),o=this.svgFactory.create(n,r,!0);let h=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];h.push(`${d},${f}`)}h=h.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",h),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class cg extends kl{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class ug extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class wo extends pt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?U.HIGHLIGHT:U.INK}#s(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:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:o,height:h}=this.#s(e,t),l=this.svgFactory.create(o,h,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let u=0,d=s.length;u<d;u++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[u].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,o=this.#e.length;r<o;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:o,height:h}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${h}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ml extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=U.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class dg extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class fg extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class gg extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class Pl extends pt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=U.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class pg extends pt{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=Bt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class mg{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){this.div=t,this.#t=e,this.#e=s,this.#i=o||null,this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#r(t,e){const s=t.firstChild||t,i=s.id=`${so}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,o]of n)s.setAttribute(r,o);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;fs(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new yo,annotationStorage:t.annotationStorage||new co,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const o=r.annotationType===St.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=Ke(r.rect);if(c<=0||u<=0)continue}n.data=r;const h=Qf.create(n);if(!h.isRenderable)continue;if(!o&&r.popupRef){const c=i.get(r.popupRef);c?c.push(h):i.set(r.popupRef,[h])}const l=h.render();r.hidden&&(l.style.visibility="hidden"),await this.#r(l,r.id),h._isEditable&&(this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,fs(e,{rotation:t.rotation}),this.#n(),e.hidden=!1}#n(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const zn=/\r\n?|\n/g;class Ct extends H{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Ct.prototype,e=n=>n.isEmpty(),s=qe.TRANSLATE_SMALL,i=qe.TRANSLATE_BIG;return $(this,"_keyboardManager",new pi([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=U.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Ct._defaultColor||H._defaultLineColor,this.#r=t.fontSize||Ct._defaultFontSize}static initialize(t,e){H.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case q.FREETEXT_SIZE:Ct._defaultFontSize=e;break;case q.FREETEXT_COLOR:Ct._defaultColor=e;break}}updateParams(t,e){switch(t){case q.FREETEXT_SIZE:this.#n(e);break;case q.FREETEXT_COLOR:this.#h(e);break}}static get defaultPropertiesToUpdate(){return[[q.FREETEXT_SIZE,Ct._defaultFontSize],[q.FREETEXT_COLOR,Ct._defaultColor||H._defaultLineColor]]}get propertiesToUpdate(){return[[q.FREETEXT_SIZE,this.#r],[q.FREETEXT_COLOR,this.#t]]}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#c()},s=this.#r;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#h(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Ct._internalPadding*t,-(Ct._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(U.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;const t=this._uiManager.combinedSignal(this.#i);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})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#a(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(Ct.#l(s)),e=s);return t.join(`
508
508
  `)}#c(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,r=n.style.display,o=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=r,n.classList.toggle("hidden",o)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#e,e=this.#e=this.#a().trimEnd();if(t===e)return;const s=i=>{if(this.#e=i,!i){this.remove();return}this.#d(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Ct._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#s),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:s}=this.editorDiv;if(s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),Ln(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[o,h]=this.getInitialTranslation();[o,h]=this.pageTranslationToScreen(o,h);const[l,c]=this.pageDimensions,[u,d]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=t+(r[0]-u)/l,g=e+this.height-(r[1]-d)/c;break;case 90:f=t+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[h,-o];break;case 180:f=t-this.width+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[-o,-h];break;case 270:f=t+(r[0]-u-this.height*c)/l,g=e+(r[1]-d-this.width*l)/c,[o,h]=[-h,o];break}this.setAt(f*i,g*n,o,h)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#d(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(zn,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=Ct.#f(e.getData("text")||"").replaceAll(zn,`
@@ -512,4 +512,4 @@ void main() {
512
512
  `)}`,this.#d();const u=new Range;let d=l.reduce((f,g)=>f+g.length,0);for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const g=f.nodeValue.length;if(d<=g){u.setStart(f,d),u.setEnd(f,d);break}d-=g}n.removeAllRanges(),n.addRange(u)}#d(){if(this.editorDiv.replaceChildren(),!!this.#e)for(const t of this.#e.split(`
513
513
  `)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#u(){return this.#e.replaceAll(" "," ")}static#f(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof El){const{data:{defaultAppearanceData:{fontSize:r,fontColor:o},rect:h,rotation:l,id:c,popupRef:u},textContent:d,textPosition:f,parent:{page:{pageNumber:g}}}=t;if(!d||d.length===0)return null;i=t={annotationType:U.FREETEXT,color:Array.from(o),fontSize:r,value:d.join(`
514
514
  `),position:f,pageIndex:g-1,rect:h.slice(0),rotation:l,id:c,deleted:!1,popupRef:u}}const n=await super.deserialize(t,e,s);return n.#r=t.fontSize,n.#t=B.makeHexColor(...t.color),n.#e=Ct.#f(t.value),n.annotationElementId=t.id||null,n._initialData=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Ct._internalPadding*this.parentScale,s=this.getRect(e,e),i=H._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:U.FREETEXT,color:i,fontSize:this.#r,value:this.#u(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#o(n)?null:(n.id=this.annotationElementId,n)}#o(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((r,o)=>r!==i[o])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,e.replaceChildren();for(const n of this.#e.split(`
515
- `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=Ct._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class I{static PRECISION=1e-4;toSVGPath(){st("Abstract method `toSVGPath` must be implemented.")}get box(){st("Abstract getter `box` must be implemented.")}serialize(t,e){st("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){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,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class ms{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#h;#a;#c;#l;#d;#u;#f=[];static#o=8;static#g=2;static#m=ms.#o+ms.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#l=ms.#o*i,this.#c=ms.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#h+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#h+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#h=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const u=t-l,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#l,p=g/f,b=p*u,m=p*d;let v=o,y=h;o=l,h=c,l+=b,c+=m,this.#f?.push(t,e);const _=-m/g,S=b/g,A=_*this.#u,T=S*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+A,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+A-s)/n,(h+T-i)/r),this.#n.set([o-A,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-A-s)/n,(h-T-i)/r)),this.#n.set([v,y,o,h,l,c],6),!this.isEmpty()):(this.#n.set([v,y,o,h,l,c],6),Math.abs(Math.atan2(y-h,v-o)-Math.atan2(m,b))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,v,y]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((y+h)/2-i)/r),!0):([v,y,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,v,y]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#b();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#v(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#_(s),s.join(" ")}#b(){const[t,e,s,i]=this.#t,[n,r,o,h]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${o} ${h} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#v(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=this.#n.subarray(16,18),[h,l,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Ol(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=h.length-2;u<d;u+=2)h[u]=(this.#f[u]-i)/r,h[u+1]=(this.#f[u+1]-n)/o;if(h[h.length-2]=(this.#h-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#w(h);const l=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){l[u]=l[u+1]=NaN;continue}l[u]=t[u],l[u+1]=t[u+1]}c=this.#A(l,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[u+d],l[c+1]=e[u+d+1],c+=2}return this.#S(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,c]=this.#p(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,o,h]=this.#t,[l,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class Ol extends I{#t;#e=new Float32Array(4);#s;#i;#r;#n;#h;constructor(t,e,s,i,n,r){super(),this.#h=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#a(r);const[o,h,l,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/l,t[u+1]=(t[u+1]-h)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/l,e[u+1]=(e[u+1]-h)/c}toSVGPath(){const t=[`M${this.#h[4]} ${this.#h[5]}`];for(let e=6,s=this.#h.length;e<s;e+=6){if(isNaN(this.#h[e])){t.push(`L${this.#h[e+4]} ${this.#h[e+5]}`);continue}t.push(`C${this.#h[e]} ${this.#h[e+1]} ${this.#h[e+2]} ${this.#h[e+3]} ${this.#h[e+4]} ${this.#h[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=I._rescale(this.#h,t,i,r,-o),l=I._rescale(this.#r,t,i,r,-o);break;case 90:h=I._rescaleAndSwap(this.#h,t,e,r,o),l=I._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=I._rescale(this.#h,s,e,-r,o),l=I._rescale(this.#r,s,e,-r,o);break;case 270:h=I._rescaleAndSwap(this.#h,s,i,-r,-o),l=I._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#h;let s=e[4],i=e[5],n=s,r=i,o=s,h=i,l=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),o=Math.max(o,e[f+4]),h=Math.max(h,e[f+5]),c<e[f+5]?(l=e[f+4],c=e[f+5]):c===e[f+5]&&(l=u(l,e[f+4]));else{const p=B.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),o=Math.max(o,p[2]),h=Math.max(h,p[3]),c<p[3]?(l=p[2],c=p[3]):c===p[3]&&(l=u(l,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=o-n+2*this.#s,d[3]=h-r+2*this.#s,this.lastPoint=[l,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new ms(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,u=n*l,d=r*c,f=s*l+o,g=i*c+h,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let b=2;b<this.#r.length;b+=2)p.add({x:this.#r[b]*u+f,y:this.#r[b+1]*d+g});return p.getOutlines()}}class xo{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,h=-1/0;const l=10**-4;for(const{x:b,y:m,width:v,height:y}of t){const _=Math.floor((b-e)/l)*l,S=Math.ceil((b+v+e)/l)*l,A=Math.floor((m-e)/l)*l,T=Math.ceil((m+y+e)/l)*l,E=[_,A,T,!0],P=[S,A,T,!1];this.#s.push(E,P),n=Math.min(n,_),r=Math.max(r,S),o=Math.min(o,A),h=Math.max(h,T)}const c=r-n+2*s,u=h-o+2*s,d=n-s,f=o-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const b of this.#s){const[m,v,y]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[2]=(y-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#h(e)):(this.#a(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,u]=r;s.delete(r);let d=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,h,l,c,u]=g,d!==o&&(n.push(d,f,o,f===h?h:l),d=o),f=f===h?l:h}n.push(d,f)}return new bg(i,this.#t,this.#e)}#n(t){const e=this.#i;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#h([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#a([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let o=0;o<r;o++){const[h,l]=this.#i[o];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(l<=d||f<=h)){if(d>=h){if(f>l)n[c][1]=l;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class bg extends I{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],o=e[n+1];r===s?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],o=s-t,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let u=0;u<l.length;u+=2)c[u]=t+l[u]*o,c[u+1]=i-l[u+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class So extends ms{newFreeDrawOutline(t,e,s,i,n,r){return new vg(t,e,s,i,n,r)}}class vg extends Ol{newOutliner(t,e,s,i,n,r=0){return new So(t,e,s,i,n,r)}}class ne{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#h=null;#a;#c=null;#l=null;#d;static#u=null;static get _keyboardManager(){return $(this,"_keyboardManager",new pi([[["Escape","mac+Escape"],ne.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ne.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ne.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ne.prototype._moveToPrevious],[["Home","mac+Home"],ne.prototype._moveToBeginning],[["End","mac+End"],ne.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=q.HIGHLIGHT_COLOR,this.#h=t):(this.#n=!0,this.#d=q.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color||this.#l?.highlightColors.values().next().value||"#FFFF98",ne.#u||=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.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#l._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",ge,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#l.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",ne.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#o.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#o(t,e){e.stopPropagation(),this.#a.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#o(e,t)}_moveToNext(t){if(!this.#b){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#b){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#b){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){ne._keyboardManager.exec(this,t)}#m(t){if(this.#b){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#b){this.#h?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#l.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class mt extends H{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#h=null;#a=0;#c=null;#l=null;#d=null;#u=!1;#f=null;#o;#g=null;#m="";#p;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=U.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=mt.prototype;return $(this,"_keyboardManager",new pi([[["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||mt._defaultColor,this.#p=t.thickness||mt._defaultThickness,this.#o=t.opacity||mt._defaultOpacity,this.#s=t.boxes||null,this.#b=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#v(t),this.#M()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#h=t.focusNode,this.#a=t.focusOffset,this.#_(),this.#M(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new xo(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new xo(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#v({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:mt.#x(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:mt.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=h*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=h*c/u;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){H.initialize(t,e),mt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case q.HIGHLIGHT_DEFAULT_COLOR:mt._defaultColor=e;break;case q.HIGHLIGHT_THICKNESS:mt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case q.HIGHLIGHT_COLOR:this.#w(e);break;case q.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[q.HIGHLIGHT_DEFAULT_COLOR,mt._defaultColor],[q.HIGHLIGHT_THICKNESS,mt._defaultThickness]]}get propertiesToUpdate(){return[[q.HIGHLIGHT_COLOR,this.color||mt._defaultColor],[q.HIGHLIGHT_THICKNESS,this.#p||mt._defaultThickness],[q.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#o=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#o;this.addCommands({cmd:e.bind(this,t,mt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new ne({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#M(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#M(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#v({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#M(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#o},rootClass:{highlight:!0,free:this.#u},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=mt.#x(this.#l.box,t)):s=mt.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:mt.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),Ln(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){mt._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#h,this.#a)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#L(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let o=0;for(const{x:h,y:l,width:c,height:u}of n){const d=h*t+s,f=(1-l)*e+i;r[o]=r[o+4]=d,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=d+c*t,r[o+5]=r[o+7]=f-u*e,o+=8}return r}#I(t){return this.#l.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",te,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ge,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new So({x:i,y:n},[r,o,h,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#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(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,s){let i=null;if(t instanceof Ml){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:y,popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),opacity:y,quadPoints:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof wo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),thickness:y,inkLists:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=B.makeHexColor(...n),l.#o=h||1,o&&(l.#p=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[c,u]=l.pageDimensions,[d,f]=l.pageTranslation;if(r){const g=l.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});l.#_(),l.#M(),l.rotate(l.rotation)}else if(o){l.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new So(p,[0,0,c,u],1,l.#p/2,!0,.001);for(let y=0,_=g.length;y<_;y+=2)p.x=g[y]-d,p.y=u-(g[y+1]-f),b.add(p);const{id:m,clipPathId:v}=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:b.toSVGPath()}},!0,!0);l.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),l.#M()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=H._colorManager.convert(this.color),i={annotationType:U.HIGHLIGHT,color:s,opacity:this.#o,thickness:this.#p,quadPoints:this.#L(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class yg{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){st("Not implemented")}}class z extends H{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#h=null;static#a=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#l(t),this.#f())}#l({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(z._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){st("Not implemented")}static get typesMap(){st("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(z.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=o=>{i.updateProperty(e,o);const h=this.#t.updateProperty(e,o);h&&this.#m(h),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.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,z._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#o([t,e,s,i]){const{parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#o(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[o,h]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(o/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/o)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){st("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(z.#h&&z.#h!==l)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=z.#i=new AbortController,g=t.combinedSignal(f);if(z.#n||=h,z.#h??=l,window.addEventListener("pointerup",p=>{z.#n===p.pointerId?this._endDraw(p):z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{z.#n===p.pointerId?this._currentParent.endDrawingSession():z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{z.#h===p.pointerType&&((z.#a||=new Set).add(p.pointerId),z.#s.isCancellable()&&(z.#s.removeLastElement(),z.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ge,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===z.#c&&te(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),z.#s){t.drawLayer.updateProperties(this._currentDrawId,z.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),z.#s=this.createDrawerInstance(r,o,u,d,c),z.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(z.#r.toSVGProperties(),z.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(z.#c=-1,!z.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(z.#n===i){if(z.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,z.#s.add(e,s)),z.#c=t.timeStamp,te(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,z.#s=null,z.#r=null,z.#h=null,z.#c=NaN),z.#i&&(z.#i.abort(),z.#i=null,z.#n=NaN,z.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,z.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=z.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:q.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(q.DRAW_STEP),!z.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:z.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:z.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){st("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class _g{#t=new Float64Array(6);#e;#s;#i;#r;#n;#h="";#a=0;#c=new Gn;#l;#d;constructor(t,e,s,i,n,r){this.#l=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const o=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:o,points:this.#n}],this.#t.set(o,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return I._normalizePoint(t,e,this.#l,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),o=t-n,h=e-r;return Math.hypot(this.#l*o,this.#d*h)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...I.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#l=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const o=this.#s.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#a=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#a=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#h="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#a=0,this.toSVGPath()}return{path:{d:this.#h}}}toSVGPath(){const t=I.svgRound(this.#e[4]),e=I.svgRound(this.#e[5]);if(this.#n.length===2)return this.#h=`${this.#h} M ${t} ${e} Z`,this.#h;if(this.#n.length<=6){const i=this.#h.lastIndexOf("M");this.#h=`${this.#h.slice(0,i)} M ${t} ${e}`,this.#a=6}if(this.#n.length===4){const i=I.svgRound(this.#e[10]),n=I.svgRound(this.#e[11]);return this.#h=`${this.#h} L ${i} ${n}`,this.#a=12,this.#h}const s=[];this.#a===0&&(s.push(`M ${t} ${e}`),this.#a=6);for(let i=this.#a,n=this.#e.length;i<n;i+=6){const[r,o,h,l,c,u]=this.#e.slice(i,i+6).map(I.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${u}`)}return this.#h+=s.join(" "),this.#a=this.#e.length,this.#h}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#h=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Gn extends I{#t;#e=0;#s;#i;#r;#n;#h;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#h=i,this.#a=n,this.#c=r,this.#s=o??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${I.svgRound(e[4])} ${I.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${I.svgRound(e[10])} ${I.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,h,l,c]=e.subarray(s,s+6).map(I.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,u]=this.#d();let d,f,g,p,b,m,v,y,_;switch(this.#a){case 0:_=I._rescale,d=t,f=e+i,g=s,p=-i,b=t+h*s,m=e+(1-l-u)*i,v=t+(h+c)*s,y=e+(1-l)*i;break;case 90:_=I._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+l*s,m=e+h*i,v=t+(l+u)*s,y=e+(h+c)*i;break;case 180:_=I._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-h-c)*s,m=e+l*i,v=t+(1-h)*s,y=e+(l+u)*i;break;case 270:_=I._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-l-u)*s,m=e+(1-h-c)*i,v=t+(1-l)*s,y=e+(1-h)*i;break}for(const{line:S,points:A}of this.#i)r.push(_(S,d,f,g,p,n?new Array(S.length):null)),o.push(_(A,d,f,g,p,n?new Array(A.length):null));return{lines:r,points:o,rect:[b,m,v,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let u,d,f,g,p;switch(h){case 0:p=I._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=I._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=I._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=I._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const v=m.length;if(v===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(v===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const y=new Float32Array(3*(v-2));r.push(y);let[_,S,A,T]=m.subarray(0,4);y.set([NaN,NaN,NaN,NaN,_,S],0);for(let E=4;E<v;E+=2){const P=m[E],N=m[E+1];y.set(I.createBezierPoints(_,S,A,T,P,N),(E-2)*3),[_,S,A,T]=[A,T,P,N]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(y=>y??NaN),u,d,f,g),points:p(o[m].map(y=>y??NaN),u,d,f,g)});const b=new Gn;return b.build(c,s,i,1,h,l,n),b}#l(t=this.#c){const e=this.#s+t/2*this.#h;return this.#a%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let o=4,h=i.length;o<h;o+=6){const[l,c]=i.subarray(o,o+2);t[0]=Math.min(t[0],l),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],l),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,u,d,f,g]=i.subarray(o,o+6);B.bezierBoundingBox(n,r,l,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#l();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#l();this.#c=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#h=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(I.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${I.svgRound(o)} ${I.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=I.PRECISION||Math.abs(c-r)<=I.PRECISION){const p=t+s/2-(o+l/2),b=e+i/2-(h+c/2);return{path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}const u=(s-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${I.svgRound(o)} ${I.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${I.svgRound(n)} ${I.svgRound(r)}) scale(${u} ${d}) translate(${I.svgRound(-n)} ${I.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=I.PRECISION||Math.abs(u-r)<=I.PRECISION){const b=t+s/2-(h+c/2),m=e+i/2-(l+u/2);for(const{line:v,points:y}of this.#i)I._translate(v,b,m,v),I._translate(y,b,m,y);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(h+n)+t+n,p=-f*(l+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:b,points:m}of this.#i)I._rescale(b,g,p,d,f,b),I._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)I._translate(l,o,h,l),I._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)I._rescale(u,o,h,l,c,u),I._rescale(d,o,h,l,c,d);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t[0])} ${I.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Co extends yg{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:H._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Co(this.#t);return t.updateAll(this),t}}class Ao extends z{static _type="ink";static _editorType=U.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){H.initialize(t,e),this._defaultDrawingOptions=new Co(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return $(this,"typesMap",new Map([[q.INK_THICKNESS,"stroke-width"],[q.INK_COLOR,"stroke"],[q.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new _g(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Gn.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof wo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:U.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.slice(0),rotation:h,id:l,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=Ao.getDefaultDrawingOptions({stroke:B.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":o}}=this,h={annotationType:U.INK,color:H._colorManager.convert(n),opacity:r,thickness:o,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?h:this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,o)=>r!==e[o])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class To extends H{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#h=null;#a=null;#c=!1;#l=!1;static _type="stamp";static _editorType=U.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){H.initialize(t,e)}static get supportedTypes(){return $(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return $(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(U.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}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#o()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#h){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,o=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=To.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#h?.remove(),this.#h=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#h===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#o():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#a!==null&&clearTimeout(this.#a);const t=200;this.#a=setTimeout(()=>{this.#a=null,this.#m()},t)}#o(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[o,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#h=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#l||(this.parent.addUndoableEditor(this),this.#l=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&l.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new oo;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const A=Math.min(e/i,e/n);h=Math.floor(i*A),l=Math.floor(n*A)}c=document.createElement("canvas");const d=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*r.sy);this.#c||(o=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",b="#42414d");const m=15,v=m*r.sx,y=m*r.sy,_=new OffscreenCanvas(v*2,y*2),S=_.getContext("2d");S.fillStyle=p,S.fillRect(0,0,v*2,y*2),S.fillStyle=b,S.fillRect(0,0,v,y),S.fillRect(v,y,v,y),g.fillStyle=g.createPattern(_,"repeat"),g.fillRect(0,0,d,f),g.drawImage(o,0,0,o.width,o.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&o.width<t&&o.height<t)d=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);d=Math.floor(i*b),f=Math.floor(n*b),this.#c||(o=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:h,height:l,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,o=this.#t;for(;n>2*t||r>2*e;){const h=n,l=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 c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(o,0,0,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new oo,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#h;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#c?this.#t:this.#g(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}getImageForAltText(){return this.#h}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*Is.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*Is.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof Pl){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:y,parent:{page:{pageNumber:_}}}=t,S=y.querySelector("canvas"),A=s.imageManager.getFromCanvas(y.id,S);S.remove();const T=(await e._structTree.getAriaAttributes(`${so}${b}`))?.get("aria-label")||"";i=t={annotationType:U.STAMP,bitmapId:A.id,bitmap:A.bitmap,pageIndex:_-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:T},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:u}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,o&&(n.#t=o)):n.#i=h,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#l=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:U.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const o=this.#b(s);if(o.isSame)return null;o.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#p(!1))}return s}#b(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class He{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#h=!1;#a=!1;#c=!1;#l=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([Ct,Ao,To,mt].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const u=[...He.#g.values()];if(!He._initialized){He._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#o=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#u=h,this.drawLayer=o,this._structTree=i,this.#o.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===U.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case U.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case U.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case U.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of He.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}cleanUndoStack(t){this.#o.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#o.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#o.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#a=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#o.isDeletedAnnotationElement(r))continue;let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#o.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#v(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of He.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#a=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#o.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#o.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Bt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),mt.startHighlighting(this,this.#o.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#o._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#o.combinedSignal(this.#i);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.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#o.isDeletedAnnotationElement(e)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#o.addDeletedAnnotationElement(t.annotationElementId),H.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#o.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#o.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#o._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#o.getId()}get#p(){return He.#g.get(this.#o.getMode())}combinedSignal(t){return this.#o.combinedSignal(t)}#b(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#o,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await He.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#o,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[u,d]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:e}=Bt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#h&&(this.#h=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#o.getMode()===U.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===U.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#h=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#o.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#l){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#o.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#o,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#l?(this.#o.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#o.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#o.removeLayer(this)}#v(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,fs(this.div,t);for(const e of this.#o.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#v();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,fs(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#o.viewParameters.realScale}}class zt{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return $(this,"_svgFactory",new yo)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=zt._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#h(t,e){const s=zt._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=zt._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#a(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=zt._svgFactory.createElement("defs");n.append(r);const o=zt._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const l=s?this.#h(r,h):null,c=zt._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=zt._svgFactory.createElement("defs");i.append(n);const r=zt._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const u=zt._svgFactory.createElement("mask");n.append(u),h=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",h),u.setAttribute("maskUnits","objectBoundingBox");const d=zt._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=zt._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=zt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,o=typeof t=="number"?this.#s.get(t):t;if(o){if(s&&this.#a(o,s),i&&zt.#r(o,i),n){const{classList:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:xo},V.AbortException,V.AnnotationEditorLayer,V.AnnotationEditorParamsType,V.AnnotationEditorType,V.AnnotationEditorUIManager,V.AnnotationLayer,V.AnnotationMode,V.ColorPicker,V.DOMSVGFactory,V.DrawLayer,V.FeatureTest;var wg=V.GlobalWorkerOptions;V.ImageKind,V.InvalidPDFException,V.MissingPDFException,V.OPS,V.OutputScale,V.PDFDataRangeTransport,V.PDFDateString,V.PDFWorker,V.PasswordResponses,V.PermissionFlag,V.PixelsPerInch,V.RenderingCancelledException,V.TextLayer,V.TouchManager,V.UnexpectedResponseException,V.Util,V.VerbosityLevel,V.XfaLayer,V.build,V.createValidAbsoluteUrl,V.fetchData;var xg=V.getDocument;V.getFilenameFromUrl,V.getPdfFilenameFromUrl,V.getXfaPageViewport,V.isDataScheme,V.isPdfFile,V.noContextMenu,V.normalizeUnicode,V.setLayerDimensions,V.shadow,V.stopEvent;var Sg=V.version;let Dl=null;function Cg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function Ag(){const a=Dl??Cg();return Dl=a,a/72}function Tg(a,t=500){if(typeof a!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,a.apply(this,s)},t)}}function Eg(a){return a.arrayBuffer?a.arrayBuffer():new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>{const i=s.result;if(!(i instanceof ArrayBuffer)){e(new Error("Failed to read file as ArrayBuffer."));return}t(i)}),s.addEventListener("error",e),s.readAsArrayBuffer(a)})}Rl()||(wg.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Sg}/pdf.worker.min.mjs`);function Rl(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"&&globalThis.self===window.top}catch{return!1}}async function kg({page:a,data:t,scale:e,password:s},i){const n=Ag()/window.devicePixelRatio;if(Rl()){const r=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-DuXj-zBo.js").href:new URL("assets/pdfjs.worker-DuXj-zBo.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return r.postMessage({data:t,password:s,id:i,page:a,units:n,scale:e}),await new Promise(h=>{r.addEventListener("message",l=>{if(l.data.status!=="success")return;const{bitmap:c,width:u,height:d,pages:f}=l.data;if(c){const g=document.createElement("canvas"),p=g.getContext("bitmaprenderer");g.width=u,g.height=d,p?.transferFromImageBitmap(c),h({pages:f,canvas:g})}else h({pages:f,canvas:null})})})}else{const r=await Eg(t),o=await xg({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),u=document.createElement("canvas"),f={canvasContext:u.getContext("2d"),viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),l.render(f).promise.then(()=>({canvas:u,pages:h}))}}const Gt=new Map;function Mg(a){const t=new Nr(a);return Gt.set(a,t),t}function Pg(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Og({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await cd(a),n=s.filter(o=>o!==null),r=Eu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function Dg(a,t){if(!Gt.get(a))return;const s=1/3,i=Bg(t,s);Fl(a,i,s)}async function Rg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Ll(t,{data:a}),{...i,pages:1}}async function Ll(a,{data:t,scale:e=.5}){if(!Gt.get(a))return;const i=URL.createObjectURL(t),n=await Mt.fromURL(i);n.scale(e),Fl(a,n,e),URL.revokeObjectURL(i)}function Fl(a,t,e){const s=Gt.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Lg(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function Fg(a,t,e){!e||!a||(e.scale(1/t),Lg(a,e))}function Ig(a,t){if(!a)return;const e=a._cornerSize||6;a.borderScaleFactor=1/t,a.cornerSize=e*(1/t),a.touchCornerSize=e*4*(1/t),a.setCoords()}function Ng(a){const t=Gt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function jg(a){const t=Gt.get(a);t&&(t.clear(),Gt.delete(a))}function Bg(a,t){return new Mt(a,{scaleX:t,scaleY:t})}function Eo(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function Il(a,t,e){const s=a.type;return{"application/pdf":Hg,"image/png":jl,"image/jpeg":jl}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function Hg(a,t,e){const s=Pg(a),i=await Nl({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Nl(a,t){return kg(a,t).then(({canvas:e,pages:s})=>(e&&t&&Dg(t,e),s))}async function jl(a,t,e){return await Rg(a,e)}function zg(a,t){const e=Gt.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof Jt?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function Gg(a,t){const e=Gt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(Wl);i instanceof Jt?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),Eo(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Vg(a){const t=Gt.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof Jt?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Bl(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{};let h=null,l=null,c=1,u={...Xl};function d(){if(!t||Gt.has(t))return;const k=Mg(t);return k.on("selection:created",O=>{if(r?.(O),O.selected.length<=1)return;const j=k.getActiveObject();j&&(l=j,e?.value&&l.set(e.value),l._cornerSize=l.cornerSize,S(c))}),k.on("selection:cleared",O=>{o?.(O),T(k)}),s&&k.on("mouse:down",s),i&&k.on("mouse:move",i),n&&k.on("mouse:up",n),k}function f(k,O){return Il(k,O,t)}function g(k){return Nl(k,t)}function p({data:k,scale:O=.5}){return Ll(t,{data:k,scale:O})}async function b(k,O,j){const M=Gt.get(t);if(!M)return;const R=await Mt.fromURL(k,{},{...$n,...O});Eo(R,j),M.add(R),v(M,R),M.setActiveObject(R)}function m(k,O,j){const M=Gt.get(t);if(!M)return;const R=new kt(k,{...Gl,...O});Eo(R,j),M.add(R),v(M,R),M.setActiveObject(R)}function v(k,O){O.on("selected",j=>y({canvas:k,target:j.target})),O.on("modified",j=>y({canvas:k,target:j.target})),O.on("scaling",()=>T(k)),O.on("moving",()=>T(k)),O.on("rotating",()=>T(k)),O._cornerSize=O._cornerSize??O.cornerSize}async function y({canvas:k,target:O,stroke:j=u.stroke,uuid:M=Date.now()}){if(k.getActiveObjects().length>1||h?.stroke===`${j}-${M}`)return;const G=await Og(u,M,j);T(k),h=G,l=O,_(k,O,M),S(c,!0),G&&k.add(G)}function _(k,O,j){h&&(h.on("selected",()=>{k.remove(O),T(k)}),h.on("mouseover",()=>{y({canvas:k,target:O,stroke:u.hoverStroke,uuid:j})}),h.on("mouseout",()=>{y({canvas:k,target:O,stroke:u.stroke,uuid:j})}))}function S(k,O=!1){const j=Gt.get(t);c=k,j&&(Ig(l,k),Fg(l,k,h),!O&&j.renderAll())}function A(k){if(!k)return;u={...u,...k};const O=Gt.get(t);!h||!l||!O||y({target:l,canvas:O})}function T(k){l=null,h&&(k.remove(h),h=null)}function E(){Ng(t)}function P(){jg(t)}function N(k){zg(t,k)}function D(){return Gg(t,v)}function L(){Vg(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:E,deleteCanvas:P,scaleFabric:S,setCloseSvgOptions:A,setActiveFabric:N,copyActiveFabric:D,deleteActiveFabric:L}}function Xg(a){let t=0;const e=Tg(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});W.onMounted(()=>{window.addEventListener("resize",e)}),W.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const Wg=W.defineComponent({__name:"pdf-canvas",props:{file:{},page:{default:1},canvasId:{default:"PDF-canvas"},fileZoom:{default:1},fileScale:{default:1},canvasScale:{default:1},canvasClass:{default:""},isDrop:{type:Boolean,default:!1},password:{},dropTextOptions:{},dropImageOptions:{},selectionOptions:{},closeSvgOptions:{},manualReload:{type:Boolean},onDestroy:{type:Function,default:W.onBeforeUnmount}},emits:["loaded","reload","pointerDown","pointerMove","pointerUp","selectionCreated","selectionCleared"],setup(a,{expose:t,emit:e}){const s=a,i=e,{onDestroy:n}=s,r=W.ref(null),o=`${s.canvasId}-${s.page-1}`,h=W.computed(()=>s.fileZoom*s.canvasScale),l=W.computed(()=>({...Vl,...s.selectionOptions})),{createCanvas:c,specifyPage:u,addFabric:d,addTextFabric:f,renderImage:g,clearActive:p,deleteCanvas:b,scaleFabric:m,setActiveFabric:v,setCloseSvgOptions:y,copyActiveFabric:_,deleteActiveFabric:S}=Bl({id:o,selectionOptions:l,pointerDown:D=>i("pointerDown",D),pointerMove:D=>i("pointerMove",D),pointerUp:D=>i("pointerUp",D),selectionCreated:D=>i("selectionCreated",D),selectionCleared:D=>i("selectionCleared",D)});A(),Xg(N);async function A(){const{file:D,page:L,fileScale:k}=s;globalThis.requestAnimationFrame(async()=>{if(await W.nextTick(),c(),D.data?.type.startsWith("image/")){const j=D.data;j&&g({data:j,scale:k/3}),i("loaded");return}D.data&&await u({page:L,data:D.data,scale:k,password:s.password}),i("loaded")})}function T(D){if(!s.isDrop||!D.dataTransfer)return;const{dataTransfer:L,offsetX:k,offsetY:O}=D,j=L.getData("text/plain"),M=L.getData("text/uri-list"),R=L.getData("custom/offset"),G=R?JSON.parse(R):null,at={top:O,left:k},ct={x:G?.offsetX??0,y:G?.offsetY??0};M?E(M,at,ct):j&&P(j,at,ct)}function E(D,L,k){d(D,{...s.dropImageOptions,...L},k)}function P(D,L,k){f(D,{...s.dropTextOptions,...L},k)}function N(){s.manualReload||A(),i("reload")}return W.watch([()=>s.fileScale,()=>s.page,()=>s.file,()=>s.password],N),W.watch(h,D=>m(D),{immediate:!0}),W.watch(()=>s.closeSvgOptions,y,{immediate:!0}),n(b),t({reload:A,addImage:E,addText:P,clearActive:p,deleteCanvas:b,setActiveFabric:v,copyActiveFabric:_,deleteActiveFabric:S,canvasRef:r}),(D,L)=>(W.openBlock(),W.createElementBlock("div",{style:W.normalizeStyle({transform:`scale(${h.value})`}),onDragover:L[0]||(L[0]=W.withModifiers(()=>{},["prevent"])),onDragenter:L[1]||(L[1]=W.withModifiers(()=>{},["prevent"])),onDrop:W.withModifiers(T,["stop","prevent"])},[W.createElementVNode("canvas",{id:o,ref_key:"canvasRef",ref:r,class:W.normalizeClass(a.canvasClass)},null,2)],36))}});J.default=Wg,J.loadFile=Il,J.useFabric=Bl,Object.defineProperties(J,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
515
+ `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=Ct._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class I{static PRECISION=1e-4;toSVGPath(){st("Abstract method `toSVGPath` must be implemented.")}get box(){st("Abstract getter `box` must be implemented.")}serialize(t,e){st("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){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,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class ms{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#h;#a;#c;#l;#d;#u;#f=[];static#o=8;static#g=2;static#m=ms.#o+ms.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#l=ms.#o*i,this.#c=ms.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#h+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#h+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#h=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const u=t-l,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#l,p=g/f,b=p*u,m=p*d;let v=o,y=h;o=l,h=c,l+=b,c+=m,this.#f?.push(t,e);const _=-m/g,S=b/g,A=_*this.#u,T=S*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+A,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+A-s)/n,(h+T-i)/r),this.#n.set([o-A,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-A-s)/n,(h-T-i)/r)),this.#n.set([v,y,o,h,l,c],6),!this.isEmpty()):(this.#n.set([v,y,o,h,l,c],6),Math.abs(Math.atan2(y-h,v-o)-Math.atan2(m,b))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,v,y]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((y+h)/2-i)/r),!0):([v,y,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,v,y]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#b();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#v(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#_(s),s.join(" ")}#b(){const[t,e,s,i]=this.#t,[n,r,o,h]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${o} ${h} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#v(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=this.#n.subarray(16,18),[h,l,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Ol(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=h.length-2;u<d;u+=2)h[u]=(this.#f[u]-i)/r,h[u+1]=(this.#f[u+1]-n)/o;if(h[h.length-2]=(this.#h-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#w(h);const l=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){l[u]=l[u+1]=NaN;continue}l[u]=t[u],l[u+1]=t[u+1]}c=this.#A(l,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[u+d],l[c+1]=e[u+d+1],c+=2}return this.#S(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,c]=this.#p(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,o,h]=this.#t,[l,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class Ol extends I{#t;#e=new Float32Array(4);#s;#i;#r;#n;#h;constructor(t,e,s,i,n,r){super(),this.#h=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#a(r);const[o,h,l,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/l,t[u+1]=(t[u+1]-h)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/l,e[u+1]=(e[u+1]-h)/c}toSVGPath(){const t=[`M${this.#h[4]} ${this.#h[5]}`];for(let e=6,s=this.#h.length;e<s;e+=6){if(isNaN(this.#h[e])){t.push(`L${this.#h[e+4]} ${this.#h[e+5]}`);continue}t.push(`C${this.#h[e]} ${this.#h[e+1]} ${this.#h[e+2]} ${this.#h[e+3]} ${this.#h[e+4]} ${this.#h[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=I._rescale(this.#h,t,i,r,-o),l=I._rescale(this.#r,t,i,r,-o);break;case 90:h=I._rescaleAndSwap(this.#h,t,e,r,o),l=I._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=I._rescale(this.#h,s,e,-r,o),l=I._rescale(this.#r,s,e,-r,o);break;case 270:h=I._rescaleAndSwap(this.#h,s,i,-r,-o),l=I._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#h;let s=e[4],i=e[5],n=s,r=i,o=s,h=i,l=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),o=Math.max(o,e[f+4]),h=Math.max(h,e[f+5]),c<e[f+5]?(l=e[f+4],c=e[f+5]):c===e[f+5]&&(l=u(l,e[f+4]));else{const p=B.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),o=Math.max(o,p[2]),h=Math.max(h,p[3]),c<p[3]?(l=p[2],c=p[3]):c===p[3]&&(l=u(l,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=o-n+2*this.#s,d[3]=h-r+2*this.#s,this.lastPoint=[l,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new ms(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,u=n*l,d=r*c,f=s*l+o,g=i*c+h,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let b=2;b<this.#r.length;b+=2)p.add({x:this.#r[b]*u+f,y:this.#r[b+1]*d+g});return p.getOutlines()}}class xo{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,h=-1/0;const l=10**-4;for(const{x:b,y:m,width:v,height:y}of t){const _=Math.floor((b-e)/l)*l,S=Math.ceil((b+v+e)/l)*l,A=Math.floor((m-e)/l)*l,T=Math.ceil((m+y+e)/l)*l,E=[_,A,T,!0],P=[S,A,T,!1];this.#s.push(E,P),n=Math.min(n,_),r=Math.max(r,S),o=Math.min(o,A),h=Math.max(h,T)}const c=r-n+2*s,u=h-o+2*s,d=n-s,f=o-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const b of this.#s){const[m,v,y]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[2]=(y-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#h(e)):(this.#a(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,u]=r;s.delete(r);let d=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,h,l,c,u]=g,d!==o&&(n.push(d,f,o,f===h?h:l),d=o),f=f===h?l:h}n.push(d,f)}return new bg(i,this.#t,this.#e)}#n(t){const e=this.#i;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#h([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#a([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let o=0;o<r;o++){const[h,l]=this.#i[o];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(l<=d||f<=h)){if(d>=h){if(f>l)n[c][1]=l;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class bg extends I{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],o=e[n+1];r===s?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],o=s-t,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let u=0;u<l.length;u+=2)c[u]=t+l[u]*o,c[u+1]=i-l[u+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class So extends ms{newFreeDrawOutline(t,e,s,i,n,r){return new vg(t,e,s,i,n,r)}}class vg extends Ol{newOutliner(t,e,s,i,n,r=0){return new So(t,e,s,i,n,r)}}class ne{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#h=null;#a;#c=null;#l=null;#d;static#u=null;static get _keyboardManager(){return $(this,"_keyboardManager",new pi([[["Escape","mac+Escape"],ne.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ne.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ne.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ne.prototype._moveToPrevious],[["Home","mac+Home"],ne.prototype._moveToBeginning],[["End","mac+End"],ne.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=q.HIGHLIGHT_COLOR,this.#h=t):(this.#n=!0,this.#d=q.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color||this.#l?.highlightColors.values().next().value||"#FFFF98",ne.#u||=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.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#l._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",ge,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#l.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",ne.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#o.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#o(t,e){e.stopPropagation(),this.#a.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#o(e,t)}_moveToNext(t){if(!this.#b){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#b){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#b){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){ne._keyboardManager.exec(this,t)}#m(t){if(this.#b){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#b){this.#h?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#l.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class mt extends H{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#h=null;#a=0;#c=null;#l=null;#d=null;#u=!1;#f=null;#o;#g=null;#m="";#p;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=U.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=mt.prototype;return $(this,"_keyboardManager",new pi([[["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||mt._defaultColor,this.#p=t.thickness||mt._defaultThickness,this.#o=t.opacity||mt._defaultOpacity,this.#s=t.boxes||null,this.#b=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#v(t),this.#M()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#h=t.focusNode,this.#a=t.focusOffset,this.#_(),this.#M(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new xo(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new xo(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#v({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:mt.#x(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:mt.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=h*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=h*c/u;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){H.initialize(t,e),mt._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case q.HIGHLIGHT_DEFAULT_COLOR:mt._defaultColor=e;break;case q.HIGHLIGHT_THICKNESS:mt._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case q.HIGHLIGHT_COLOR:this.#w(e);break;case q.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[q.HIGHLIGHT_DEFAULT_COLOR,mt._defaultColor],[q.HIGHLIGHT_THICKNESS,mt._defaultThickness]]}get propertiesToUpdate(){return[[q.HIGHLIGHT_COLOR,this.color||mt._defaultColor],[q.HIGHLIGHT_THICKNESS,this.#p||mt._defaultThickness],[q.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#o=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#o;this.addCommands({cmd:e.bind(this,t,mt._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:q.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new ne({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#M(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#M(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#v({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#M(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#o},rootClass:{highlight:!0,free:this.#u},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=mt.#x(this.#l.box,t)):s=mt.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:mt.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),Ln(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){mt._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#h,this.#a)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#L(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let o=0;for(const{x:h,y:l,width:c,height:u}of n){const d=h*t+s,f=(1-l)*e+i;r[o]=r[o+4]=d,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=d+c*t,r[o+5]=r[o+7]=f-u*e,o+=8}return r}#I(t){return this.#l.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",te,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ge,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new So({x:i,y:n},[r,o,h,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#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(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,s){let i=null;if(t instanceof Ml){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:y,popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),opacity:y,quadPoints:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof wo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:U.HIGHLIGHT,color:Array.from(v),thickness:y,inkLists:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=B.makeHexColor(...n),l.#o=h||1,o&&(l.#p=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[c,u]=l.pageDimensions,[d,f]=l.pageTranslation;if(r){const g=l.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});l.#_(),l.#M(),l.rotate(l.rotation)}else if(o){l.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new So(p,[0,0,c,u],1,l.#p/2,!0,.001);for(let y=0,_=g.length;y<_;y+=2)p.x=g[y]-d,p.y=u-(g[y+1]-f),b.add(p);const{id:m,clipPathId:v}=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:b.toSVGPath()}},!0,!0);l.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),l.#M()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=H._colorManager.convert(this.color),i={annotationType:U.HIGHLIGHT,color:s,opacity:this.#o,thickness:this.#p,quadPoints:this.#L(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class yg{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){st("Not implemented")}}class z extends H{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#h=null;static#a=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#l(t),this.#f())}#l({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(z._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){st("Not implemented")}static get typesMap(){st("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(z.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=o=>{i.updateProperty(e,o);const h=this.#t.updateProperty(e,o);h&&this.#m(h),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.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,z._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#o([t,e,s,i]){const{parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#o(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[o,h]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(o/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/o)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,z._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){st("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(z.#h&&z.#h!==l)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=z.#i=new AbortController,g=t.combinedSignal(f);if(z.#n||=h,z.#h??=l,window.addEventListener("pointerup",p=>{z.#n===p.pointerId?this._endDraw(p):z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{z.#n===p.pointerId?this._currentParent.endDrawingSession():z.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{z.#h===p.pointerType&&((z.#a||=new Set).add(p.pointerId),z.#s.isCancellable()&&(z.#s.removeLastElement(),z.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ge,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===z.#c&&te(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),z.#s){t.drawLayer.updateProperties(this._currentDrawId,z.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),z.#s=this.createDrawerInstance(r,o,u,d,c),z.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(z.#r.toSVGProperties(),z.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(z.#c=-1,!z.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(z.#n===i){if(z.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,z.#s.add(e,s)),z.#c=t.timeStamp,te(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,z.#s=null,z.#r=null,z.#h=null,z.#c=NaN),z.#i&&(z.#i.abort(),z.#i=null,z.#n=NaN,z.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,z.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=z.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:q.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(q.DRAW_STEP),!z.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:z.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:z.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){st("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class _g{#t=new Float64Array(6);#e;#s;#i;#r;#n;#h="";#a=0;#c=new Gn;#l;#d;constructor(t,e,s,i,n,r){this.#l=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const o=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:o,points:this.#n}],this.#t.set(o,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return I._normalizePoint(t,e,this.#l,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),o=t-n,h=e-r;return Math.hypot(this.#l*o,this.#d*h)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...I.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#l=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const o=this.#s.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#a=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#a=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#h="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#a=0,this.toSVGPath()}return{path:{d:this.#h}}}toSVGPath(){const t=I.svgRound(this.#e[4]),e=I.svgRound(this.#e[5]);if(this.#n.length===2)return this.#h=`${this.#h} M ${t} ${e} Z`,this.#h;if(this.#n.length<=6){const i=this.#h.lastIndexOf("M");this.#h=`${this.#h.slice(0,i)} M ${t} ${e}`,this.#a=6}if(this.#n.length===4){const i=I.svgRound(this.#e[10]),n=I.svgRound(this.#e[11]);return this.#h=`${this.#h} L ${i} ${n}`,this.#a=12,this.#h}const s=[];this.#a===0&&(s.push(`M ${t} ${e}`),this.#a=6);for(let i=this.#a,n=this.#e.length;i<n;i+=6){const[r,o,h,l,c,u]=this.#e.slice(i,i+6).map(I.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${u}`)}return this.#h+=s.join(" "),this.#a=this.#e.length,this.#h}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#h=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Gn extends I{#t;#e=0;#s;#i;#r;#n;#h;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#h=i,this.#a=n,this.#c=r,this.#s=o??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${I.svgRound(e[4])} ${I.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${I.svgRound(e[10])} ${I.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,h,l,c]=e.subarray(s,s+6).map(I.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,u]=this.#d();let d,f,g,p,b,m,v,y,_;switch(this.#a){case 0:_=I._rescale,d=t,f=e+i,g=s,p=-i,b=t+h*s,m=e+(1-l-u)*i,v=t+(h+c)*s,y=e+(1-l)*i;break;case 90:_=I._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+l*s,m=e+h*i,v=t+(l+u)*s,y=e+(h+c)*i;break;case 180:_=I._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-h-c)*s,m=e+l*i,v=t+(1-h)*s,y=e+(l+u)*i;break;case 270:_=I._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-l-u)*s,m=e+(1-h-c)*i,v=t+(1-l)*s,y=e+(1-h)*i;break}for(const{line:S,points:A}of this.#i)r.push(_(S,d,f,g,p,n?new Array(S.length):null)),o.push(_(A,d,f,g,p,n?new Array(A.length):null));return{lines:r,points:o,rect:[b,m,v,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let u,d,f,g,p;switch(h){case 0:p=I._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=I._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=I._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=I._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const v=m.length;if(v===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(v===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const y=new Float32Array(3*(v-2));r.push(y);let[_,S,A,T]=m.subarray(0,4);y.set([NaN,NaN,NaN,NaN,_,S],0);for(let E=4;E<v;E+=2){const P=m[E],N=m[E+1];y.set(I.createBezierPoints(_,S,A,T,P,N),(E-2)*3),[_,S,A,T]=[A,T,P,N]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(y=>y??NaN),u,d,f,g),points:p(o[m].map(y=>y??NaN),u,d,f,g)});const b=new Gn;return b.build(c,s,i,1,h,l,n),b}#l(t=this.#c){const e=this.#s+t/2*this.#h;return this.#a%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let o=4,h=i.length;o<h;o+=6){const[l,c]=i.subarray(o,o+2);t[0]=Math.min(t[0],l),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],l),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,u,d,f,g]=i.subarray(o,o+6);B.bezierBoundingBox(n,r,l,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#l();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#l();this.#c=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#h=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(I.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${I.svgRound(o)} ${I.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=I.PRECISION||Math.abs(c-r)<=I.PRECISION){const p=t+s/2-(o+l/2),b=e+i/2-(h+c/2);return{path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}const u=(s-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${I.svgRound(o)} ${I.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${I.svgRound(n)} ${I.svgRound(r)}) scale(${u} ${d}) translate(${I.svgRound(-n)} ${I.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=I.PRECISION||Math.abs(u-r)<=I.PRECISION){const b=t+s/2-(h+c/2),m=e+i/2-(l+u/2);for(const{line:v,points:y}of this.#i)I._translate(v,b,m,v),I._translate(y,b,m,y);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(h+n)+t+n,p=-f*(l+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:b,points:m}of this.#i)I._rescale(b,g,p,d,f,b),I._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)I._translate(l,o,h,l),I._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)I._rescale(u,o,h,l,c,u),I._rescale(d,o,h,l,c,d);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t)} ${I.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${I.svgRound(t[0])} ${I.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Co extends yg{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:H._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Co(this.#t);return t.updateAll(this),t}}class Ao extends z{static _type="ink";static _editorType=U.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){H.initialize(t,e),this._defaultDrawingOptions=new Co(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return $(this,"typesMap",new Map([[q.INK_THICKNESS,"stroke-width"],[q.INK_COLOR,"stroke"],[q.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new _g(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Gn.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof wo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:U.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.slice(0),rotation:h,id:l,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=Ao.getDefaultDrawingOptions({stroke:B.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":o}}=this,h={annotationType:U.INK,color:H._colorManager.convert(n),opacity:r,thickness:o,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?h:this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,o)=>r!==e[o])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class To extends H{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#h=null;#a=null;#c=!1;#l=!1;static _type="stamp";static _editorType=U.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){H.initialize(t,e)}static get supportedTypes(){return $(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return $(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(U.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}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#o()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#h){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,o=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=To.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#h?.remove(),this.#h=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#h===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#o():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#a!==null&&clearTimeout(this.#a);const t=200;this.#a=setTimeout(()=>{this.#a=null,this.#m()},t)}#o(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[o,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#h=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#l||(this.parent.addUndoableEditor(this),this.#l=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&l.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new oo;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const A=Math.min(e/i,e/n);h=Math.floor(i*A),l=Math.floor(n*A)}c=document.createElement("canvas");const d=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*r.sy);this.#c||(o=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",b="#42414d");const m=15,v=m*r.sx,y=m*r.sy,_=new OffscreenCanvas(v*2,y*2),S=_.getContext("2d");S.fillStyle=p,S.fillRect(0,0,v*2,y*2),S.fillStyle=b,S.fillRect(0,0,v,y),S.fillRect(v,y,v,y),g.fillStyle=g.createPattern(_,"repeat"),g.fillRect(0,0,d,f),g.drawImage(o,0,0,o.width,o.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&o.width<t&&o.height<t)d=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);d=Math.floor(i*b),f=Math.floor(n*b),this.#c||(o=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:h,height:l,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,o=this.#t;for(;n>2*t||r>2*e;){const h=n,l=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 c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(o,0,0,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new oo,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#h;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#c?this.#t:this.#g(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}getImageForAltText(){return this.#h}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*Is.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*Is.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof Pl){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:y,parent:{page:{pageNumber:_}}}=t,S=y.querySelector("canvas"),A=s.imageManager.getFromCanvas(y.id,S);S.remove();const T=(await e._structTree.getAriaAttributes(`${so}${b}`))?.get("aria-label")||"";i=t={annotationType:U.STAMP,bitmapId:A.id,bitmap:A.bitmap,pageIndex:_-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:T},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:u}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,o&&(n.#t=o)):n.#i=h,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#l=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:U.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const o=this.#b(s);if(o.isSame)return null;o.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#p(!1))}return s}#b(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class He{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#h=!1;#a=!1;#c=!1;#l=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([Ct,Ao,To,mt].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const u=[...He.#g.values()];if(!He._initialized){He._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#o=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#u=h,this.drawLayer=o,this._structTree=i,this.#o.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===U.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case U.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case U.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case U.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of He.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}cleanUndoStack(t){this.#o.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#o.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#o.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#a=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#o.isDeletedAnnotationElement(r))continue;let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#o.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#v(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of He.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#a=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#o.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#o.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Bt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),mt.startHighlighting(this,this.#o.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#o._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#o.combinedSignal(this.#i);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.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#o.isDeletedAnnotationElement(e)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#o.addDeletedAnnotationElement(t.annotationElementId),H.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#o.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#o.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#o._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#o.getId()}get#p(){return He.#g.get(this.#o.getMode())}combinedSignal(t){return this.#o.combinedSignal(t)}#b(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#o,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await He.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#o,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[u,d]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:e}=Bt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#h&&(this.#h=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#o.getMode()===U.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===U.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:e}=Bt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#h=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#o.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#l){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#o.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#o,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#l?(this.#o.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#o.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#o.removeLayer(this)}#v(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,fs(this.div,t);for(const e of this.#o.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#v();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,fs(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#o.viewParameters.realScale}}class zt{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return $(this,"_svgFactory",new yo)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=zt._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#h(t,e){const s=zt._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=zt._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#a(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=zt._svgFactory.createElement("defs");n.append(r);const o=zt._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const l=s?this.#h(r,h):null,c=zt._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=zt._svgFactory.createElement("defs");i.append(n);const r=zt._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const u=zt._svgFactory.createElement("mask");n.append(u),h=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",h),u.setAttribute("maskUnits","objectBoundingBox");const d=zt._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=zt._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=zt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,o=typeof t=="number"?this.#s.get(t):t;if(o){if(s&&this.#a(o,s),i&&zt.#r(o,i),n){const{classList:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:xo},V.AbortException,V.AnnotationEditorLayer,V.AnnotationEditorParamsType,V.AnnotationEditorType,V.AnnotationEditorUIManager,V.AnnotationLayer,V.AnnotationMode,V.ColorPicker,V.DOMSVGFactory,V.DrawLayer,V.FeatureTest;var wg=V.GlobalWorkerOptions;V.ImageKind,V.InvalidPDFException,V.MissingPDFException,V.OPS,V.OutputScale,V.PDFDataRangeTransport,V.PDFDateString,V.PDFWorker,V.PasswordResponses,V.PermissionFlag,V.PixelsPerInch,V.RenderingCancelledException,V.TextLayer,V.TouchManager,V.UnexpectedResponseException,V.Util,V.VerbosityLevel,V.XfaLayer,V.build,V.createValidAbsoluteUrl,V.fetchData;var xg=V.getDocument;V.getFilenameFromUrl,V.getPdfFilenameFromUrl,V.getXfaPageViewport,V.isDataScheme,V.isPdfFile,V.noContextMenu,V.normalizeUnicode,V.setLayerDimensions,V.shadow,V.stopEvent;var Sg=V.version;let Dl=null;function Cg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function Ag(){const a=Dl??Cg();return Dl=a,a/72}function Tg(a,t=500){if(typeof a!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,a.apply(this,s)},t)}}function Eg(a){return a.arrayBuffer?a.arrayBuffer():new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>{const i=s.result;if(!(i instanceof ArrayBuffer)){e(new Error("Failed to read file as ArrayBuffer."));return}t(i)}),s.addEventListener("error",e),s.readAsArrayBuffer(a)})}Rl()||(wg.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Sg}/pdf.worker.min.mjs`);function Rl(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"&&globalThis.self===window.top}catch{return!1}}async function kg({page:a,data:t,scale:e,password:s},i){const n=Ag()/window.devicePixelRatio;if(Rl()){const r=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-BHKxIhYa.js").href:new URL("assets/pdfjs.worker-BHKxIhYa.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:dt&&dt.tagName.toUpperCase()==="SCRIPT"&&dt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return r.postMessage({data:t,password:s,id:i,page:a,units:n,scale:e}),await new Promise(h=>{r.addEventListener("message",l=>{if(l.data.status!=="success")return;const{bitmap:c,width:u,height:d,pages:f}=l.data;if(c){const g=document.createElement("canvas"),p=g.getContext("bitmaprenderer");g.width=u,g.height=d,p?.transferFromImageBitmap(c),h({pages:f,canvas:g})}else h({pages:f,canvas:null})})})}else{const r=await Eg(t),o=await xg({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),u=document.createElement("canvas"),f={canvasContext:u.getContext("2d"),viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),l.render(f).promise.then(()=>({canvas:u,pages:h}))}}const Gt=new Map;function Mg(a){const t=new Nr(a);return Gt.set(a,t),t}function Pg(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Og({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await cd(a),n=s.filter(o=>o!==null),r=Eu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function Dg(a,t){if(!Gt.get(a))return;const s=1/3,i=Bg(t,s);Fl(a,i,s)}async function Rg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Ll(t,{data:a}),{...i,pages:1}}async function Ll(a,{data:t,scale:e=.5}){if(!Gt.get(a))return;const i=URL.createObjectURL(t),n=await Mt.fromURL(i);n.scale(e),Fl(a,n,e),URL.revokeObjectURL(i)}function Fl(a,t,e){const s=Gt.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Lg(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function Fg(a,t,e){!e||!a||(e.scale(1/t),Lg(a,e))}function Ig(a,t){if(!a)return;const e=a._cornerSize||6;a.borderScaleFactor=1/t,a.cornerSize=e*(1/t),a.touchCornerSize=e*4*(1/t),a.setCoords()}function Ng(a){const t=Gt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function jg(a){const t=Gt.get(a);t&&(t.clear(),Gt.delete(a))}function Bg(a,t){return new Mt(a,{scaleX:t,scaleY:t})}function Eo(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function Il(a,t,e){const s=a.type;return{"application/pdf":Hg,"image/png":jl,"image/jpeg":jl}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function Hg(a,t,e){const s=Pg(a),i=await Nl({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Nl(a,t){return kg(a,t).then(({canvas:e,pages:s})=>(e&&t&&Dg(t,e),s))}async function jl(a,t,e){return await Rg(a,e)}function zg(a,t){const e=Gt.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof Jt?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function Gg(a,t){const e=Gt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(Wl);i instanceof Jt?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),Eo(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Vg(a){const t=Gt.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof Jt?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Bl(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{};let h=null,l=null,c=1,u={...Xl};function d(){if(!t||Gt.has(t))return;const k=Mg(t);return k.on("selection:created",O=>{if(r?.(O),O.selected.length<=1)return;const j=k.getActiveObject();j&&(l=j,e?.value&&l.set(e.value),l._cornerSize=l.cornerSize,S(c))}),k.on("selection:cleared",O=>{o?.(O),T(k)}),s&&k.on("mouse:down",s),i&&k.on("mouse:move",i),n&&k.on("mouse:up",n),k}function f(k,O){return Il(k,O,t)}function g(k){return Nl(k,t)}function p({data:k,scale:O=.5}){return Ll(t,{data:k,scale:O})}async function b(k,O,j){const M=Gt.get(t);if(!M)return;const R=await Mt.fromURL(k,{},{...$n,...O});Eo(R,j),M.add(R),v(M,R),M.setActiveObject(R)}function m(k,O,j){const M=Gt.get(t);if(!M)return;const R=new kt(k,{...Gl,...O});Eo(R,j),M.add(R),v(M,R),M.setActiveObject(R)}function v(k,O){O.on("selected",j=>y({canvas:k,target:j.target})),O.on("modified",j=>y({canvas:k,target:j.target})),O.on("scaling",()=>T(k)),O.on("moving",()=>T(k)),O.on("rotating",()=>T(k)),O._cornerSize=O._cornerSize??O.cornerSize}async function y({canvas:k,target:O,stroke:j=u.stroke,uuid:M=Date.now()}){if(k.getActiveObjects().length>1||h?.stroke===`${j}-${M}`)return;const G=await Og(u,M,j);T(k),h=G,l=O,_(k,O,M),S(c,!0),G&&k.add(G)}function _(k,O,j){h&&(h.on("selected",()=>{k.remove(O),T(k)}),h.on("mouseover",()=>{y({canvas:k,target:O,stroke:u.hoverStroke,uuid:j})}),h.on("mouseout",()=>{y({canvas:k,target:O,stroke:u.stroke,uuid:j})}))}function S(k,O=!1){const j=Gt.get(t);c=k,j&&(Ig(l,k),Fg(l,k,h),!O&&j.renderAll())}function A(k){if(!k)return;u={...u,...k};const O=Gt.get(t);!h||!l||!O||y({target:l,canvas:O})}function T(k){l=null,h&&(k.remove(h),h=null)}function E(){Ng(t)}function P(){jg(t)}function N(k){zg(t,k)}function D(){return Gg(t,v)}function L(){Vg(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:E,deleteCanvas:P,scaleFabric:S,setCloseSvgOptions:A,setActiveFabric:N,copyActiveFabric:D,deleteActiveFabric:L}}function Xg(a){let t=0;const e=Tg(()=>{t!==window.innerWidth&&(t=window.innerWidth,a())});W.onMounted(()=>{window.addEventListener("resize",e)}),W.onBeforeUnmount(()=>{window.removeEventListener("resize",e)})}const Wg=W.defineComponent({__name:"pdf-canvas",props:{file:{},page:{default:1},canvasId:{default:"PDF-canvas"},fileZoom:{default:1},fileScale:{default:1},canvasScale:{default:1},canvasClass:{default:""},isDrop:{type:Boolean,default:!1},password:{},dropTextOptions:{},dropImageOptions:{},selectionOptions:{},closeSvgOptions:{},manualReload:{type:Boolean},onDestroy:{type:Function,default:W.onBeforeUnmount}},emits:["loaded","reload","pointerDown","pointerMove","pointerUp","selectionCreated","selectionCleared"],setup(a,{expose:t,emit:e}){const s=a,i=e,{onDestroy:n}=s,r=W.ref(null),o=`${s.canvasId}-${s.page-1}`,h=W.computed(()=>s.fileZoom*s.canvasScale),l=W.computed(()=>({...Vl,...s.selectionOptions})),{createCanvas:c,specifyPage:u,addFabric:d,addTextFabric:f,renderImage:g,clearActive:p,deleteCanvas:b,scaleFabric:m,setActiveFabric:v,setCloseSvgOptions:y,copyActiveFabric:_,deleteActiveFabric:S}=Bl({id:o,selectionOptions:l,pointerDown:D=>i("pointerDown",D),pointerMove:D=>i("pointerMove",D),pointerUp:D=>i("pointerUp",D),selectionCreated:D=>i("selectionCreated",D),selectionCleared:D=>i("selectionCleared",D)});A(),Xg(N);async function A(){const{file:D,page:L,fileScale:k}=s;globalThis.requestAnimationFrame(async()=>{if(await W.nextTick(),c(),D.data?.type.startsWith("image/")){const j=D.data;j&&g({data:j,scale:k/3}),i("loaded");return}D.data&&await u({page:L,data:D.data,scale:k,password:s.password}),i("loaded")})}function T(D){if(!s.isDrop||!D.dataTransfer)return;const{dataTransfer:L,offsetX:k,offsetY:O}=D,j=L.getData("text/plain"),M=L.getData("text/uri-list"),R=L.getData("custom/offset"),G=R?JSON.parse(R):null,at={top:O,left:k},ct={x:G?.offsetX??0,y:G?.offsetY??0};M?E(M,at,ct):j&&P(j,at,ct)}function E(D,L,k){d(D,{...s.dropImageOptions,...L},k)}function P(D,L,k){f(D,{...s.dropTextOptions,...L},k)}function N(){s.manualReload||A(),i("reload")}return W.watch([()=>s.fileScale,()=>s.page,()=>s.file,()=>s.password],N),W.watch(h,D=>m(D),{immediate:!0}),W.watch(()=>s.closeSvgOptions,y,{immediate:!0}),n(b),t({reload:A,addImage:E,addText:P,clearActive:p,deleteCanvas:b,setActiveFabric:v,copyActiveFabric:_,deleteActiveFabric:S,canvasRef:r}),(D,L)=>(W.openBlock(),W.createElementBlock("div",{style:W.normalizeStyle({transform:`scale(${h.value})`}),onDragover:L[0]||(L[0]=W.withModifiers(()=>{},["prevent"])),onDragenter:L[1]||(L[1]=W.withModifiers(()=>{},["prevent"])),onDrop:W.withModifiers(T,["stop","prevent"])},[W.createElementVNode("canvas",{id:o,ref_key:"canvasRef",ref:r,class:W.normalizeClass(a.canvasClass)},null,2)],36))}});J.default=Wg,J.loadFile=Il,J.useFabric=Bl,Object.defineProperties(J,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));