try{let t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},e=(new t.Error).stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="b5e343c1-21eb-4b95-8c7d-c4d5fcaf38a2",t._sentryDebugIdIdentifier="sentry-dbid-b5e343c1-21eb-4b95-8c7d-c4d5fcaf38a2")}catch(t){}"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8181],{72037:(t,e,i)=>{i.d(e,{D6:()=>i1,EA:()=>iZ,Tm:()=>i0,YE:()=>i2,dU:()=>iQ,ng:()=>iJ});var s=i(8159),a=i(22037).hp,r={};r.d=(t,e)=>{for(var i in e)r.o(e,i)&&!r.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var n=globalThis.pdfjsLib={};r.d(n,{AbortException:()=>O,AnnotationEditorLayer:()=>iX,AnnotationEditorParamsType:()=>p,AnnotationEditorType:()=>u,AnnotationEditorUIManager:()=>tw,AnnotationLayer:()=>iF,AnnotationMode:()=>c,ColorPicker:()=>iV,DOMSVGFactory:()=>ii,DrawLayer:()=>iY,FeatureTest:()=>z,GlobalWorkerOptions:()=>en,ImageKind:()=>f,InvalidPDFException:()=>R,MissingPDFException:()=>P,OPS:()=>y,OutputScale:()=>tp,PDFDataRangeTransport:()=>eY,PDFDateString:()=>to,PDFWorker:()=>e0,PasswordResponses:()=>_,PermissionFlag:()=>g,PixelsPerInch:()=>X,RenderingCancelledException:()=>J,TextLayer:()=>eU,UnexpectedResponseException:()=>D,Util:()=>j,VerbosityLevel:()=>v,XfaLayer:()=>is,build:()=>e8,createValidAbsoluteUrl:()=>T,fetchData:()=>Y,getDocument:()=>eq,getFilenameFromUrl:()=>te,getPdfFilenameFromUrl:()=>ti,getXfaPageViewport:()=>tl,isDataScheme:()=>Z,isPdfFile:()=>tt,noContextMenu:()=>tr,normalizeUnicode:()=>V,setLayerDimensions:()=>tu,shadow:()=>M,version:()=>e4});let o="object"==typeof s&&s+""=="[object process]"&&!s.versions.nw&&!(s.versions.electron&&s.type&&"browser"!==s.type),l=[1,0,0,1,0,0],h=[.001,0,0,.001,0,0],d={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},c={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},u={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},p={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},g={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},m={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},f={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},b={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},A={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},v={ERRORS:0,WARNINGS:1,INFOS:5},y={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},_={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},w=v.WARNINGS;function x(t){w>=v.INFOS&&console.log(`Info: ${t}`)}function E(t){w>=v.WARNINGS&&console.log(`Warning: ${t}`)}function C(t){throw Error(t)}function S(t,e){t||C(e)}function T(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){let e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{var s;s=t,t=decodeURIComponent(escape(s))}catch{}}let a=e?new URL(t,e):new URL(t);if(function(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function M(t,e,i,s=!1){return Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1}),i}let k=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=Error(),t.constructor=t,t}();class I extends k{constructor(t,e){super(t,"PasswordException"),this.code=e}}class L extends k{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class R extends k{constructor(t){super(t,"InvalidPDFException")}}class P extends k{constructor(t){super(t,"MissingPDFException")}}class D extends k{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class F extends k{constructor(t){super(t,"FormatError")}}class O extends k{constructor(t){super(t,"AbortException")}}function N(t){("object"!=typeof t||t?.length===void 0)&&C("Invalid argument for bytesToString");let e=t.length;if(e<8192)return String.fromCharCode.apply(null,t);let i=[];for(let s=0;st.toString(16).padStart(2,"0"));class j{static makeHexColor(t,e,i){return`#${U[t]}${U[e]}${U[i]}`}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){let i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){let i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),a=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],a[0],r[0]),Math.min(i[1],s[1],a[1],r[1]),Math.max(i[0],s[0],a[0],r[0]),Math.max(i[1],s[1],a[1],r[1])]}static inverseTransform(t){let e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){let e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],a=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],n=(i+r)/2,o=Math.sqrt((i+r)**2-4*(i*r-a*s))/2;return[Math.sqrt(n+o||1),Math.sqrt(n-o||1)]}static normalizeRect(t){let e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){let i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;let a=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 a>r?null:[i,a,s,r]}static #t(t,e,i,s,a,r,n,o,l,h){if(l<=0||l>=1)return;let d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*s,g=d*(d*(d*a+3*l*r)+3*c*n)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static #e(t,e,i,s,a,r,n,o,l,h,d,c){if(1e-12>Math.abs(l)){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,a,r,n,o,-d/h,c);return}let u=h**2-4*d*l;if(u<0)return;let p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,a,r,n,o,(-h+p)/g,c),this.#t(t,e,i,s,a,r,n,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,s,a,r,n,o,l){return l?(l[0]=Math.min(l[0],t,n),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,n),l[3]=Math.max(l[3],e,o)):l=[Math.min(t,n),Math.min(e,o),Math.max(t,n),Math.max(e,o)],this.#e(t,i,a,n,e,s,r,o,3*(-t+3*(i-a)+n),6*(t-2*i+a),3*(i-t),l),this.#e(t,i,a,n,e,s,r,o,3*(-e+3*(s-r)+o),6*(e-2*s+r),3*(s-e),l),l}}let $=null,G=null;function V(t){return $||($=/([\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,G=new Map([["ſt","ſt"]])),t.replaceAll($,(t,e,i)=>e?e.normalize("NFKC"):G.get(i))}let W="pdfjs_internal_id_",q={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8},K="http://www.w3.org/2000/svg";class X{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Y(t,e="text"){if(ta(t,document.baseURI)){let i=await fetch(t);if(!i.ok)throw Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,s)=>{let a=new XMLHttpRequest;a.open("GET",t,!0),a.responseType=e,a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){if(200===a.status||0===a.status){switch(e){case"arraybuffer":case"blob":case"json":i(a.response);return}i(a.responseText);return}s(Error(a.statusText))}},a.send(null)})}class Q{constructor({viewBox:t,scale:e,rotation:i,offsetX:s=0,offsetY:a=0,dontFlip:r=!1}){let n,o,l,h,d,c,u,p;this.viewBox=t,this.scale=e,this.rotation=i,this.offsetX=s,this.offsetY=a;let g=(t[2]+t[0])/2,m=(t[3]+t[1])/2;switch((i%=360)<0&&(i+=360),i){case 180:n=-1,o=0,l=0,h=1;break;case 90:n=0,o=1,l=1,h=0;break;case 270:n=0,o=-1,l=-1,h=0;break;case 0:n=1,o=0,l=0,h=-1;break;default:throw Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(l=-l,h=-h),0===n?(d=Math.abs(m-t[1])*e+s,c=Math.abs(g-t[0])*e+a,u=(t[3]-t[1])*e,p=(t[2]-t[0])*e):(d=Math.abs(g-t[0])*e+s,c=Math.abs(m-t[1])*e+a,u=(t[2]-t[0])*e,p=(t[3]-t[1])*e),this.transform=[n*e,o*e,l*e,h*e,d-n*e*g-l*e*m,c-o*e*g-h*e*m],this.width=u,this.height=p}get rawDims(){let{viewBox:t}=this;return M(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:a=!1}={}){return new Q({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:a})}convertToViewportPoint(t,e){return j.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){let e=j.applyTransform([t[0],t[1]],this.transform),i=j.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return j.applyInverseTransform([t,e],this.transform)}}class J extends k{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Z(t){let e=t.length,i=0;for(;i=1&&s<=12?s-1:0;let a=parseInt(e[3],10);a=a>=1&&a<=31?a:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let n=parseInt(e[5],10);n=n>=0&&n<=59?n:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;let l=e[7]||"Z",h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(r+=h,n+=d):"+"===l&&(r-=h,n-=d),new Date(Date.UTC(i,s,a,r,n,o))}}function tl(t,{scale:e=1,rotation:i=0}){let{width:s,height:a}=t.attributes.style;return new Q({viewBox:[0,0,parseInt(s),parseInt(a)],scale:e,rotation:i})}function th(t){if(t.startsWith("#")){let e=parseInt(t.slice(1),16);return[(0xff0000&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(t=>parseInt(t)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(E(`Not a valid color format: "${t}"`),[0,0,0])}function td(t){let{a:e,b:i,c:s,d:a,e:r,f:n}=t.getTransform();return[e,i,s,a,r,n]}function tc(t){let{a:e,b:i,c:s,d:a,e:r,f:n}=t.getTransform().invertSelf();return[e,i,s,a,r,n]}function tu(t,e,i=!1,s=!0){if(e instanceof Q){let{pageWidth:s,pageHeight:a}=e.rawDims,{style:r}=t,n=z.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${a}px`,h=n?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,d=n?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;i&&e.rotation%180!=0?(r.width=d,r.height=h):(r.width=h,r.height=d)}s&&t.setAttribute("data-main-rotation",e.rotation)}class tp{constructor(){let t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class tg{#s=null;#a=null;#r;#n=null;#o=null;static #l=null;constructor(t){this.#r=t,tg.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){let t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");let e=this.#r._uiManager._signal;t.addEventListener("contextmenu",tr,{signal:e}),t.addEventListener("pointerdown",tg.#h,{signal:e});let i=this.#n=document.createElement("div");i.className="buttons",t.append(i);let s=this.#r.toolbarPosition;if(s){let{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=`${100*i}%`,e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#s}static #h(t){t.stopPropagation()}#c(t){this.#r._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()}#u(t){this.#r._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()}#p(t){let e=this.#r._uiManager._signal;t.addEventListener("focusin",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",tr,{signal:e})}hide(){this.#s.classList.add("hidden"),this.#a?.hideDropdown()}show(){this.#s.classList.remove("hidden"),this.#o?.shown()}#d(){let{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.className="delete",i.tabIndex=0,i.setAttribute("data-l10n-id",tg.#l[t]),this.#p(i),i.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#n.append(i)}get #g(){let t=document.createElement("div");return t.className="divider",t}async addAltText(t){let e=await t.render();this.#p(e),this.#n.prepend(e,this.#g),this.#o=t}addColorPicker(t){this.#a=t;let e=t.renderButton();this.#p(e),this.#n.prepend(e,this.#g)}remove(){this.#s.remove(),this.#a?.destroy(),this.#a=null}}class tm{#n=null;#s=null;#m;constructor(t){this.#m=t}#f(){let t=this.#s=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",tr,{signal:this.#m._signal});let e=this.#n=document.createElement("div");return e.className="buttons",t.append(e),this.#b(),t}#A(t,e){let i=0,s=0;for(let a of t){let t=a.y+a.height;if(ti){s=r,i=t;continue}e?r>s&&(s=r):r{this.#m.highlightSelection("floating_button")},{signal:i}),this.#n.append(t)}}function tf(t,e,i){for(let s of i)e.addEventListener(s,t[s].bind(t))}class tb{#v=0;get id(){return`pdfjs_internal_editor_${this.#v++}`}}class tA{#y=(function(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();let t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return N(t)})();#v=0;#_=null;static get _isSVGFittingCanvas(){let t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;return e.src='data:image/svg+xml;charset=UTF-8,',M(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async #w(t,e){this.#_||=new Map;let i=this.#_.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#y}_${this.#v++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await Y(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){let e=tA._isSVGFittingCanvas,s=new FileReader,a=new Image,r=new Promise((t,r)=>{a.onload=()=>{i.bitmap=a,i.isSvg=!0,t()},s.onload=async()=>{let t=i.svgUrl=s.result;a.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},a.onerror=s.onerror=r});s.readAsDataURL(t),await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){console.error(t),i=null}return this.#_.set(t,i),i&&this.#_.set(i.id,i),i}async getFromFile(t){let{lastModified:e,name:i,size:s,type:a}=t;return this.#w(`${e}_${i}_${s}_${a}`,t)}async getFromUrl(t){return this.#w(t,t)}async getFromBlob(t,e){let i=await e;return this.#w(t,i)}async getFromId(t){this.#_||=new Map;let e=this.#_.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){let{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#_||=new Map;let i=this.#_.get(t);if(i?.bitmap)return i.refCounter+=1,i;let s=new OffscreenCanvas(e.width,e.height);return s.getContext("2d").drawImage(e,0,0),i={bitmap:s.transferToImageBitmap(),id:`image_${this.#y}_${this.#v++}`,refCounter:1,isSvg:!1},this.#_.set(t,i),this.#_.set(i.id,i),i}getSvgUrl(t){let e=this.#_.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#_||=new Map;let e=this.#_.get(t);if(!e||(e.refCounter-=1,0!==e.refCounter))return;let{bitmap:i}=e;if(!e.url&&!e.file){let t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class tv{#x=[];#E=!1;#C;#S=-1;constructor(t=128){this.#C=t}add({cmd:t,undo:e,post:i,mustExec:s,type:a=NaN,overwriteIfSameType:r=!1,keepUndo:n=!1}){if(s&&t(),this.#E)return;let o={cmd:t,undo:e,post:i,type:a};if(-1===this.#S){this.#x.length>0&&(this.#x.length=0),this.#S=0,this.#x.push(o);return}if(r&&this.#x[this.#S].type===a){n&&(o.undo=this.#x[this.#S].undo),this.#x[this.#S]=o;return}let l=this.#S+1;l===this.#C?this.#x.splice(0,1):(this.#S=l,lt===e[i]))return t_._colorsMapping.get(t);return e}getHexCode(t){let e=this._colors.get(t);return e?j.makeHexColor(...e):t}}class tw{#M=new AbortController;#k=null;#I=new Map;#L=new Map;#R=null;#P=null;#D=null;#F=new tv;#O=null;#N=0;#B=new Set;#H=null;#z=null;#U=new Set;#j=!1;#$=!1;#G=!1;#V=null;#W=null;#q=null;#K=null;#X=!1;#Y=null;#Q=new tb;#J=!1;#Z=!1;#tt=null;#te=null;#ti=null;#ts=null;#ta=u.NONE;#tr=new Set;#tn=null;#to=null;#tl=null;#th={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#td=[0,0];#tc=null;#tu=null;#tp=null;#tg=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=tw.prototype,e=t=>t.#tu.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){let{type:t}=e;return"text"!==t&&"number"!==t}return!0},s=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return M(this,"_keyboardManager",new ty([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#tu.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#tu.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-a,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[a,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-a],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,a],checker:e}]]))}constructor(t,e,i,s,a,r,n,o,l,h,d){let c=this._signal=this.#M.signal;this.#tu=t,this.#tp=e,this.#R=i,this._eventBus=s,s._on("editingaction",this.onEditingAction.bind(this),{signal:c}),s._on("pagechanging",this.onPageChanging.bind(this),{signal:c}),s._on("scalechanging",this.onScaleChanging.bind(this),{signal:c}),s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:c}),s._on("setpreference",this.onSetPreference.bind(this),{signal:c}),s._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:c}),this.#tm(),this.#tf(),this.#tb(),this.#P=a.annotationStorage,this.#V=a.filterFactory,this.#to=r,this.#K=n||null,this.#j=o,this.#$=l,this.#G=h,this.#ts=d||null,this.viewParameters={realScale:X.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){for(let t of(this.#tg?.resolve(),this.#tg=null,this.#M?.abort(),this.#M=null,this._signal=null,this.#L.values()))t.destroy();this.#L.clear(),this.#I.clear(),this.#U.clear(),this.#k=null,this.#tr.clear(),this.#F.destroy(),this.#R?.destroy(),this.#Y?.hide(),this.#Y=null,this.#W&&(clearTimeout(this.#W),this.#W=null),this.#tc&&(clearTimeout(this.#tc),this.#tc=null)}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#ts}get useNewAltTextFlow(){return this.#$}get useNewAltTextWhenAddingImage(){return this.#G}get hcmFilter(){return M(this,"hcmFilter",this.#to?this.#V.addHCMFilter(this.#to.foreground,this.#to.background):"none")}get direction(){return M(this,"direction",getComputedStyle(this.#tu).direction)}get highlightColors(){return M(this,"highlightColors",this.#K?new Map(this.#K.split(",").map(t=>t.split("=").map(t=>t.trim()))):null)}get highlightColorNames(){return M(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){this.#ti=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}){"enableNewAltTextWhenAddingImage"===t&&(this.#G=e)}onPageChanging({pageNumber:t}){this.#N=t-1}focusMainContainer(){this.#tu.focus()}findParent(t,e){for(let i of this.#L.values()){let{x:s,y:a,width:r,height:n}=i.div.getBoundingClientRect();if(t>=s&&t<=s+r&&e>=a&&e<=a+n)return i}return null}disableUserSelect(t=!1){this.#tp.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#U.add(t)}removeShouldRescale(t){this.#U.delete(t)}onScaleChanging({scale:t}){for(let e of(this.commitOrRemove(),this.viewParameters.realScale=t*X.PDF_TO_CSS_UNITS,this.#U))e.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#tA({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#tv(t){let{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(let e of this.#L.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){let e=document.getSelection();if(!e||e.isCollapsed)return;let{anchorNode:i,anchorOffset:s,focusNode:a,focusOffset:r}=e,n=e.toString(),o=this.#tA(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();let h=this.#tv(o),d=this.#ta===u.NONE,c=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:a,focusOffset:r,text:n}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(u.HIGHLIGHT,c);return}c()}#ty(){let t=document.getSelection();if(!t||t.isCollapsed)return;let e=this.#tA(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#Y||=new tm(this),this.#Y.show(e,i,"ltr"===this.direction))}addToAnnotationStorage(t){t.isEmpty()||!this.#P||this.#P.has(t.id)||this.#P.setValue(t.id,t)}#t_(){let t=document.getSelection();if(!t||t.isCollapsed){this.#tn&&(this.#Y?.hide(),this.#tn=null,this.#tw({hasSelectedText:!1}));return}let{anchorNode:e}=t;if(e===this.#tn)return;let i=this.#tA(t).closest(".textLayer");if(!i){this.#tn&&(this.#Y?.hide(),this.#tn=null,this.#tw({hasSelectedText:!1}));return}if(this.#Y?.hide(),this.#tn=e,this.#tw({hasSelectedText:!0}),(this.#ta===u.HIGHLIGHT||this.#ta===u.NONE)&&(this.#ta===u.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#X=this.isShiftKeyDown,!this.isShiftKeyDown)){let t=this.#ta===u.HIGHLIGHT?this.#tv(i):null;t?.toggleDrawing();let e=new AbortController,s=this.combinedSignal(e),a=i=>{("pointerup"!==i.type||0===i.button)&&(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#tx("main_toolbar"))};window.addEventListener("pointerup",a,{signal:s}),window.addEventListener("blur",a,{signal:s})}}#tx(t=""){this.#ta===u.HIGHLIGHT?this.highlightSelection(t):this.#j&&this.#ty()}#tm(){document.addEventListener("selectionchange",this.#t_.bind(this),{signal:this._signal})}#tE(){if(this.#q)return;this.#q=new AbortController;let t=this.combinedSignal(this.#q);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#tC(){this.#q?.abort(),this.#q=null}blur(){if(this.isShiftKeyDown=!1,this.#X&&(this.#X=!1,this.#tx("main_toolbar")),!this.hasSelection)return;let{activeElement:t}=document;for(let e of this.#tr)if(e.div.contains(t)){this.#te=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#te)return;let[t,e]=this.#te;this.#te=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#tb(){if(this.#tt)return;this.#tt=new AbortController;let t=this.combinedSignal(this.#tt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#tS(){this.#tt?.abort(),this.#tt=null}#tT(){if(this.#O)return;this.#O=new AbortController;let t=this.combinedSignal(this.#O);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})}#tM(){this.#O?.abort(),this.#O=null}#tf(){let t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#tb(),this.#tT()}removeEditListeners(){this.#tS(),this.#tM()}dragOver(t){for(let{type:e}of t.dataTransfer.items)for(let i of this.#z)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(let e of t.dataTransfer.items)for(let i of this.#z)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#k?.commitOrRemove(),!this.hasSelection)return;let e=[];for(let t of this.#tr){let i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();let{clipboardData:e}=t;for(let t of e.items)for(let e of this.#z)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){E(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();let s=this.currentLayer;try{let t=[];for(let e of i){let i=await s.deserialize(e);if(!i)return;t.push(i)}this.addCommands({cmd:()=>{for(let e of t)this.#tk(e);this.#tI(t)},undo:()=>{for(let e of t)e.remove()},mustExec:!0})}catch(t){E(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#ta===u.NONE||this.isEditorHandlingKeyboard||tw._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#X&&(this.#X=!1,this.#tx("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#tw(t){Object.entries(t).some(([t,e])=>this.#th[t]!==e)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#th,t)}),this.#ta===u.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#tL([[p.HIGHLIGHT_FREE,!0]]))}#tL(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#tE(),this.#tT(),this.#tw({isEditing:this.#ta!==u.NONE,isEmpty:this.#tR(),hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:this.#F.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#tC(),this.#tM(),this.#tw({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#z)for(let e of(this.#z=t,this.#z))this.#tL(e.defaultPropertiesToUpdate)}getId(){return this.#Q.id}get currentLayer(){return this.#L.get(this.#N)}getLayer(t){return this.#L.get(t)}get currentPageIndex(){return this.#N}addLayer(t){this.#L.set(t.pageIndex,t),this.#J?t.enable():t.disable()}removeLayer(t){this.#L.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#ta!==t&&(!this.#tg||(await this.#tg.promise,this.#tg))){if(this.#tg=Promise.withResolvers(),this.#ta=t,t===u.NONE){this.setEditingState(!1),this.#tP(),this.#tg.resolve();return}for(let e of(this.setEditingState(!0),await this.#tD(),this.unselectAll(),this.#L.values()))e.updateMode(t);if(!e){i&&this.addNewEditorFromKeyboard(),this.#tg.resolve();return}for(let t of this.#I.values())t.annotationElementId===e?(this.setSelected(t),t.enterInEditMode()):t.unselect();this.#tg.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#ta&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#z){switch(t){case p.CREATE:this.currentLayer.addNewEditor();return;case p.HIGHLIGHT_DEFAULT_COLOR:this.#ti?.updateColor(e);break;case p.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#tl||=new Map).set(t,e),this.showAllEditors("highlight",e)}for(let i of this.#tr)i.updateParams(t,e);for(let i of this.#z)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(let i of this.#I.values())i.editorType===t&&i.show(e);(this.#tl?.get(p.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#tL([[p.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#Z!==t)for(let e of(this.#Z=t,this.#L.values()))t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}async #tD(){if(!this.#J){this.#J=!0;let t=[];for(let e of this.#L.values())t.push(e.enable());for(let e of(await Promise.all(t),this.#I.values()))e.enable()}}#tP(){if(this.unselectAll(),this.#J){for(let t of(this.#J=!1,this.#L.values()))t.disable();for(let t of this.#I.values())t.disable()}}getEditors(t){let e=[];for(let i of this.#I.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#W&&clearTimeout(this.#W),this.#W=setTimeout(()=>{this.focusMainContainer(),this.#W=null},0)),this.#I.delete(t.id),this.unselect(t),t.annotationElementId&&this.#B.has(t.annotationElementId)||this.#P?.remove(t.id)}addDeletedAnnotationElement(t){this.#B.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#B.has(t)}removeDeletedAnnotationElement(t){this.#B.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#tk(t){let e=this.#L.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#k!==t&&(this.#k=t,t&&this.#tL(t.propertiesToUpdate))}get #tF(){let t=null;for(t of this.#tr);return t}updateUI(t){this.#tF===t&&this.#tL(t.propertiesToUpdate)}toggleSelected(t){if(this.#tr.has(t)){this.#tr.delete(t),t.unselect(),this.#tw({hasSelectedEditor:this.hasSelection});return}this.#tr.add(t),t.select(),this.#tL(t.propertiesToUpdate),this.#tw({hasSelectedEditor:!0})}setSelected(t){for(let e of this.#tr)e!==t&&e.unselect();this.#tr.clear(),this.#tr.add(t),t.select(),this.#tL(t.propertiesToUpdate),this.#tw({hasSelectedEditor:!0})}isSelected(t){return this.#tr.has(t)}get firstSelectedEditor(){return this.#tr.values().next().value}unselect(t){t.unselect(),this.#tr.delete(t),this.#tw({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#tr.size}get isEnterHandled(){return 1===this.#tr.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#F.undo(),this.#tw({hasSomethingToUndo:this.#F.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#tR()})}redo(){this.#F.redo(),this.#tw({hasSomethingToUndo:!0,hasSomethingToRedo:this.#F.hasSomethingToRedo(),isEmpty:this.#tR()})}addCommands(t){this.#F.add(t),this.#tw({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#tR()})}#tR(){if(0===this.#I.size)return!0;if(1===this.#I.size)for(let t of this.#I.values())return t.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let t=[...this.#tr];this.addCommands({cmd:()=>{for(let e of t)e.remove()},undo:()=>{for(let e of t)this.#tk(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}hasSomethingToControl(){return this.#k||this.hasSelection}#tI(t){for(let t of this.#tr)t.unselect();for(let e of(this.#tr.clear(),t))!e.isEmpty()&&(this.#tr.add(e),e.select());this.#tw({hasSelectedEditor:this.hasSelection})}selectAll(){for(let t of this.#tr)t.commit();this.#tI(this.#I.values())}unselectAll(){if((!this.#k||(this.#k.commitOrRemove(),this.#ta===u.NONE))&&this.hasSelection){for(let t of this.#tr)t.unselect();this.#tr.clear(),this.#tw({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#td[0]+=t,this.#td[1]+=e;let[s,a]=this.#td,r=[...this.#tr];for(let i of(this.#tc&&clearTimeout(this.#tc),this.#tc=setTimeout(()=>{this.#tc=null,this.#td[0]=this.#td[1]=0,this.addCommands({cmd:()=>{for(let t of r)this.#I.has(t.id)&&t.translateInPage(s,a)},undo:()=>{for(let t of r)this.#I.has(t.id)&&t.translateInPage(-s,-a)},mustExec:!1})},1e3),r))i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection)for(let t of(this.disableUserSelect(!0),this.#H=new Map,this.#tr))this.#H.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}endDragSession(){if(!this.#H)return!1;this.disableUserSelect(!1);let t=this.#H;this.#H=null;let e=!1;for(let[{x:i,y:s,pageIndex:a},r]of t)r.newX=i,r.newY=s,r.newPageIndex=a,e||=i!==r.savedX||s!==r.savedY||a!==r.savedPageIndex;if(!e)return!1;let i=(t,e,i,s)=>{if(this.#I.has(t.id)){let a=this.#L.get(s);a?t._setParentAndPosition(a,e,i):(t.pageIndex=s,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(let[e,{newX:s,newY:a,newPageIndex:r}]of t)i(e,s,a,r)},undo:()=>{for(let[e,{savedX:s,savedY:a,savedPageIndex:r}]of t)i(e,s,a,r)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#H)for(let i of this.#H.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){let e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#tr.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#ta}get imageManager(){return M(this,"imageManager",new tA)}getSelectionBoxes(t){let e;if(!t)return null;let i=document.getSelection();for(let e=0,s=i.rangeCount;e({x:(e-a)/n,y:1-(t+i-s)/r,width:o/n,height:i/r});break;case"180":e=(t,e,i,o)=>({x:1-(t+i-s)/r,y:1-(e+o-a)/n,width:i/r,height:o/n});break;case"270":e=(t,e,i,o)=>({x:1-(e+o-a)/n,y:(t-s)/r,width:o/n,height:i/r});break;default:e=(t,e,i,o)=>({x:(t-s)/r,y:(e-a)/n,width:i/r,height:o/n})}let o=[];for(let t=0,s=i.rangeCount;tt.stopPropagation(),{signal:i});let s=t=>{t.preventDefault(),this.#r._uiManager.editAltText(this.#r),this.#tV&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#tq}})};return t.addEventListener("click",s,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#tU=!0,s(e))},{signal:i}),await this.#tK(),t}get #tq(){return this.#o&&"added"||null===this.#o&&this.guessedText&&"review"||"missing"}finish(){this.#tN&&(this.#tN.focus({focusVisible:this.#tU}),this.#tU=!1)}isEmpty(){return this.#tV?null===this.#o:!this.#o&&!this.#tO}hasData(){return this.#tV?null!==this.#o||!!this.#t$:this.isEmpty()}get guessedText(){return this.#t$}async setGuessedText(t){null===this.#o&&(this.#t$=t,this.#tG=await tx._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#tK())}toggleAltTextBadge(t=!1){if(!this.#tV||this.#o){this.#tj?.remove(),this.#tj=null;return}if(!this.#tj){let t=this.#tj=document.createElement("div");t.className="noAltTextBadge",this.#r.div.append(t)}this.#tj.classList.toggle("hidden",!t)}serialize(t){let e=this.#o;return t||this.#t$!==e||(e=this.#tG),{altText:e,decorative:this.#tO,guessedText:this.#t$,textWithDisclaimer:this.#tG}}get data(){return{altText:this.#o,decorative:this.#tO}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:a=!1}){i&&(this.#t$=i,this.#tG=s),(this.#o!==t||this.#tO!==e)&&(a||(this.#o=t,this.#tO=e),this.#tK())}toggle(t=!1){this.#tN&&(!t&&this.#tz&&(clearTimeout(this.#tz),this.#tz=null),this.#tN.disabled=!t)}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#tq}})}destroy(){this.#tN?.remove(),this.#tN=null,this.#tB=null,this.#tH=null,this.#tj?.remove(),this.#tj=null}async #tK(){let t=this.#tN;if(!t)return;if(this.#tV){if(t.classList.toggle("done",!!this.#o),t.setAttribute("data-l10n-id",tx.#tW[this.#tq]),this.#tB?.setAttribute("data-l10n-id",tx.#tW[`${this.#tq}-label`]),!this.#o){this.#tH?.remove();return}}else{if(!this.#o&&!this.#tO){t.classList.remove("done"),this.#tH?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#tH;if(!e){this.#tH=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#r.id}`;let i=this.#r._uiManager._signal;i.addEventListener("abort",()=>{clearTimeout(this.#tz),this.#tz=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#tz=setTimeout(()=>{this.#tz=null,this.#tH.classList.add("show"),this.#r._reportTelemetry({action:"alt_text_tooltip"})},100)},{signal:i}),t.addEventListener("mouseleave",()=>{this.#tz&&(clearTimeout(this.#tz),this.#tz=null),this.#tH?.classList.remove("show")},{signal:i})}this.#tO?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#o),e.parentNode||t.append(e);let i=this.#r.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class tE{#tX=null;#tY=null;#o=null;#tQ=!1;#tJ=!1;#tZ=null;#t0=null;#t1=null;#t2="";#t3=!1;#t5=null;#t6=!1;#t4=!1;#t8=!1;#t7=null;#t9=0;#et=0;#ee=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#ei=!1;#es=tE._zIndex++;static _borderLineWidth=-1;static _colorManager=new t_;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=tE.prototype._resizeWithKeyboard,e=tw.TRANSLATE_SMALL,i=tw.TRANSLATE_BIG;return M(this,"_resizerKeyboardManager",new ty([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],tE.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;let{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:a,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,s],this.pageTranslation=[a,r];let[n,o]=this.parentDimensions;this.x=t.x/n,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return M(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){let e=new tC({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(tE._l10n??=t,tE._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),-1!==tE._borderLineWidth)return;let i=getComputedStyle(document.documentElement);tE._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){C("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ei}set _isDraggable(t){this.#ei=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){let[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#es}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#ea(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#t3?this.#t3=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;let e=t.relatedTarget;!e?.closest(`#${this.id}`)&&(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){let[a,r]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s),this.x=(t+i)/a,this.y=(e+s)/r,this.fixAndSetPosition()}#er([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s),this.x+=i/t,this.y+=s/e,this.fixAndSetPosition()}translate(t,e){this.#er(this.parentDimensions,t,e)}translateInPage(t,e){this.#t5||=[this.x,this.y],this.#er(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#t5||=[this.x,this.y];let[i,s]=this.parentDimensions;if(this.x+=t/i,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:r}=this,[n,o]=this.getBaseTranslation();a+=n,r+=o,this.div.style.left=`${(100*a).toFixed(2)}%`,this.div.style.top=`${(100*r).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#t5&&(this.#t5[0]!==this.x||this.#t5[1]!==this.y)}getBaseTranslation(){let[t,e]=this.parentDimensions,{_borderLineWidth:i}=tE,s=i/t,a=i/e;switch(this.rotation){case 90:return[-s,a];case 180:return[s,a];case 270:return[s,-a];default:return[-s,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){let[e,i]=this.pageDimensions,{x:s,y:a,width:r,height:n}=this;if(r*=e,n*=i,s*=e,a*=i,this._mustFixPosition)switch(t){case 0:s=Math.max(0,Math.min(e-r,s)),a=Math.max(0,Math.min(i-n,a));break;case 90:s=Math.max(0,Math.min(e-n,s)),a=Math.min(i,Math.max(r,a));break;case 180:s=Math.min(e,Math.max(r,s)),a=Math.min(i,Math.max(n,a));break;case 270:s=Math.min(e,Math.max(n,s)),a=Math.max(0,Math.min(i-r,a))}this.x=s/=e,this.y=a/=i;let[o,l]=this.getBaseTranslation();s+=o,a+=l;let{style:h}=this.div;h.left=`${(100*s).toFixed(2)}%`,h.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static #en(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return tE.#en(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return tE.#en(t,e,360-this.parentRotation)}#eo(t){switch(t){case 90:{let[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{let[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){let[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`,this.#tJ||(this.div.style.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){let{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),a=!this.#tJ&&e.endsWith("%");if(s&&a)return;let[r,n]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/r).toFixed(2)}%`),this.#tJ||a||(t.height=`${(100*parseFloat(e)/n).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#el(){if(this.#tZ)return;this.#tZ=document.createElement("div"),this.#tZ.classList.add("resizers");let t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(let i of t){let t=document.createElement("div");this.#tZ.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#eh.bind(this,i),{signal:e}),t.addEventListener("contextmenu",tr,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#tZ)}#eh(t,e){e.preventDefault();let{isMac:i}=z.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);let s=this._isDraggable;this._isDraggable=!1;let a=new AbortController,r=this._uiManager.combinedSignal(a);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#ed.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("contextmenu",tr,{signal:r});let n=this.x,o=this.y,l=this.width,h=this.height,d=this.parent.div.style.cursor,c=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;let u=()=>{a.abort(),this.parent.togglePointerEvents(!0),this.#o?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=d,this.div.style.cursor=c,this.#ec(n,o,l,h)};window.addEventListener("pointerup",u,{signal:r}),window.addEventListener("blur",u,{signal:r})}#ec(t,e,i,s){let a=this.x,r=this.y,n=this.width,o=this.height;(a!==t||r!==e||n!==i||o!==s)&&this.addCommands({cmd:()=>{this.width=n,this.height=o,this.x=a,this.y=r;let[t,e]=this.parentDimensions;this.setDims(t*n,e*o),this.fixAndSetPosition()},undo:()=>{this.width=i,this.height=s,this.x=t,this.y=e;let[a,r]=this.parentDimensions;this.setDims(a*i,r*s),this.fixAndSetPosition()},mustExec:!0})}#ed(t,e){let i,s,a,r;let[n,o]=this.parentDimensions,l=this.x,h=this.y,d=this.width,c=this.height,u=tE.MIN_SIZE/n,p=tE.MIN_SIZE/o,g=t=>Math.round(1e4*t)/1e4,m=this.#eo(this.rotation),f=(t,e)=>[m[0]*t+m[2]*e,m[1]*t+m[3]*e],b=this.#eo(360-this.rotation),A=!1,v=!1;switch(t){case"topLeft":A=!0,i=(t,e)=>[0,0],s=(t,e)=>[t,e];break;case"topMiddle":i=(t,e)=>[t/2,0],s=(t,e)=>[t/2,e];break;case"topRight":A=!0,i=(t,e)=>[t,0],s=(t,e)=>[0,e];break;case"middleRight":v=!0,i=(t,e)=>[t,e/2],s=(t,e)=>[0,e/2];break;case"bottomRight":A=!0,i=(t,e)=>[t,e],s=(t,e)=>[0,0];break;case"bottomMiddle":i=(t,e)=>[t/2,e],s=(t,e)=>[t/2,0];break;case"bottomLeft":A=!0,i=(t,e)=>[0,e],s=(t,e)=>[t,0];break;case"middleLeft":v=!0,i=(t,e)=>[0,e/2],s=(t,e)=>[t,e/2]}let y=i(d,c),_=s(d,c),w=f(..._),x=g(l+w[0]),E=g(h+w[1]),C=1,S=1,[T,M]=this.screenToPageTranslation(e.movementX,e.movementY);if([T,M]=(a=T/n,r=M/o,[b[0]*a+b[2]*r,b[1]*a+b[3]*r]),A){let t=Math.hypot(d,c);C=S=Math.max(Math.min(Math.hypot(_[0]-y[0]-T,_[1]-y[1]-M)/t,1/d,1/c),u/d,p/c)}else v?C=Math.max(u,Math.min(1,Math.abs(_[0]-y[0]-T)))/d:S=Math.max(p,Math.min(1,Math.abs(_[1]-y[1]-M)))/c;let k=g(d*C),I=g(c*S),L=x-(w=f(...s(k,I)))[0],R=E-w[1];this.width=k,this.height=I,this.x=L,this.y=R,this.setDims(n*k,o*I),this.fixAndSetPosition()}altTextFinish(){this.#o?.finish()}async addEditToolbar(){return this._editToolbar||this.#t4||(this._editToolbar=new tg(this),this.div.append(this._editToolbar.render()),this.#o&&await this._editToolbar.addAltText(this.#o)),this._editToolbar}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#o?.destroy())}addContainer(t){let e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){!this.#o&&(tx.initialize(tE._l10n),this.#o=new tx(this),this.#tX&&(this.#o.data=this.#tX,this.#tX=null),await this.addEditToolbar())}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await this.#o?.setGuessedText(t)}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}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.#tQ?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#eu();let[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)}%`);let[i,s]=this.getInitialTranslation();return this.translate(i,s),tf(this,this.div,["pointerdown"]),this.div}pointerdown(t){let{isMac:e}=z.platform;if(0!==t.button||t.ctrlKey&&e){t.preventDefault();return}if(this.#t3=!0,this._isDraggable){this.#ep(t);return}this.#eg(t)}get isSelected(){return this._uiManager.isSelected(this)}#eg(t){let{isMac:e}=z.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#ep(t){let{isSelected:e}=this;this._uiManager.setUpDragSession();let i=new AbortController,s=this._uiManager.combinedSignal(i);e&&(this.div.classList.add("moving"),this.#t9=t.clientX,this.#et=t.clientY,window.addEventListener("pointermove",t=>{let{clientX:e,clientY:i}=t,[s,a]=this.screenToPageTranslation(e-this.#t9,i-this.#et);this.#t9=e,this.#et=i,this._uiManager.dragSelectedEditors(s,a)},{passive:!0,capture:!0,signal:s}));let a=()=>{i.abort(),e&&this.div.classList.remove("moving"),this.#t3=!1,this._uiManager.endDragSession()||this.#eg(t)};window.addEventListener("pointerup",a,{signal:s}),window.addEventListener("blur",a,{signal:s})}moveInDOM(){this.#t7&&clearTimeout(this.#t7),this.#t7=setTimeout(()=>{this.#t7=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition()}getRect(t,e,i=this.rotation){let s=this.parentScale,[a,r]=this.pageDimensions,[n,o]=this.pageTranslation,l=t/s,h=e/s,d=this.x*a,c=this.y*r,u=this.width*a,p=this.height*r;switch(i){case 0:return[d+l+n,r-c-h-p+o,d+l+u+n,r-c-h+o];case 90:return[d+h+n,r-c+l+o,d+h+p+n,r-c+l+u+o];case 180:return[d-l-u+n,r-c+h+o,d-l+n,r-c+h+p+o];case 270:return[d-h-p+n,r-c-l-u+o,d-h+n,r-c-l+o];default:throw Error("Invalid rotation")}}getRectInCurrentCoords(t,e){let[i,s,a,r]=t,n=a-i,o=r-s;switch(this.rotation){case 0:return[i,e-r,n,o];case 90:return[i,e-s,o,n];case 180:return[a,e-s,n,o];case 270:return[a,e-r,o,n];default:throw Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#t4=!0}disableEditMode(){this.#t4=!1}isInEditMode(){return this.#t4}shouldGetKeyboardEvents(){return this.#t8}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}#eu(){if(this.#t1||!this.div)return;this.#t1=new AbortController;let t=this._uiManager.combinedSignal(this.#t1);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#eu()}rotate(t){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){C("An editor must be serializable")}static async deserialize(t,e,i){let s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation,s.#tX=t.accessibilityData;let[a,r]=s.pageDimensions,[n,o,l,h]=s.getRectInCurrentCoords(t.rect,r);return s.x=n/a,s.y=o/r,s.width=l/a,s.height=h/r,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#t1?.abort(),this.#t1=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#t7&&(clearTimeout(this.#t7),this.#t7=null),this.#ea(),this.removeEditToolbar(),this.#ee){for(let t of this.#ee.values())clearTimeout(t);this.#ee=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#el(),this.#tZ.classList.remove("hidden"),tf(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#t0={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let e=this.#tZ.children;if(!this.#tY){this.#tY=Array.from(e);let t=this.#em.bind(this),i=this.#ef.bind(this),s=this._uiManager._signal;for(let e of this.#tY){let a=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:s}),e.addEventListener("blur",i,{signal:s}),e.addEventListener("focus",this.#eb.bind(this,a),{signal:s}),e.setAttribute("data-l10n-id",tE._l10nResizer[a])}}let i=this.#tY[0],s=0;for(let t of e){if(t===i)break;s++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#tY.length/4);if(a!==s){if(as)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#o?.toggleAltTextBadge(!1)}unselect(){this.#tZ?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#t6}set isEditing(t){this.#t6=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#tJ=!0;let{style:i}=this.div;i.aspectRatio=t/e,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.#ee||=new Map;let{action:e}=t,i=this.#ee.get(e);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#ee.delete(e),0===this.#ee.size&&(this.#ee=null)},tE._telemetryTimeout),this.#ee.set(e,i);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#tQ=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#tQ=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){let t=e;(e=document.createElement("div")).classList.add("annotationContent",this.editorType),t.before(e)}}else(e=document.createElement("div")).classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){let{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class tC extends tE{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}class tS{constructor(t){this.h1=t?0xffffffff&t:0xc3d2e1f0,this.h2=t?0xffffffff&t:0xc3d2e1f0}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let s=0,a=t.length;s>>8,e[i++]=255&a)}}else if(ArrayBuffer.isView(t))i=(e=t.slice()).byteLength;else throw Error("Invalid data format, must be a string or TypedArray.");let s=i>>2,a=i-4*s,r=new Uint32Array(e.buffer,0,s),n=0,o=0,l=this.h1,h=this.h2;for(let t=0;t>>17)&0xffff0000|13715*n&65535,l=5*(l=l<<13|l>>>19)+0xe6546b64):(h^=o=0x1b873593*(o=(o=0xcc9e2d51*(o=r[t])&0xffff0000|11601*o&65535)<<15|o>>>17)&0xffff0000|13715*o&65535,h=5*(h=h<<13|h>>>19)+0xe6546b64);switch(n=0,a){case 3:n^=e[4*s+2]<<16;case 2:n^=e[4*s+1]<<8;case 1:n^=e[4*s],n=0x1b873593*(n=(n=0xcc9e2d51*n&0xffff0000|11601*n&65535)<<15|n>>>17)&0xffff0000|13715*n&65535,1&s?l^=n:h^=n}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,e=0xff51afd7*e&0xffff0000|((e<<16|(t=0xed558ccd*t&0xffff0000|36045*t&65535)>>>16)*0xafd7ed55&0xffff0000)>>>16,t^=e>>>1,e=0xc4ceb9fe*e&0xffff0000|((e<<16|(t=0x1a85ec53*t&0xffff0000|60499*t&65535)>>>16)*0xb9fe1a85&0xffff0000)>>>16,((t^=e>>>1)>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}let tT=Object.freeze({map:null,hash:"",transfer:void 0});class tM{#ev=!1;#ey=null;#e_=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){let i=this.#e_.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#e_.get(t)}remove(t){if(this.#e_.delete(t),0===this.#e_.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor){for(let t of this.#e_.values())if(t instanceof tE)return;this.onAnnotationEditor(null)}}setValue(t,e){let i=this.#e_.get(t),s=!1;if(void 0!==i)for(let[t,a]of Object.entries(e))i[t]!==a&&(s=!0,i[t]=a);else s=!0,this.#e_.set(t,e);s&&this.#ew(),e instanceof tE&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#e_.has(t)}getAll(){return this.#e_.size>0?H(this.#e_):null}setAll(t){for(let[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#e_.size}#ew(){this.#ev||(this.#ev=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#ev&&(this.#ev=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new tk(this)}get serializable(){if(0===this.#e_.size)return tT;let t=new Map,e=new tS,i=[],s=Object.create(null),a=!1;for(let[i,r]of this.#e_){let n=r instanceof tE?r.serialize(!1,s):r;n&&(t.set(i,n),e.update(`${i}:${JSON.stringify(n)}`),a||=!!n.bitmap)}if(a)for(let e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:tT}get editorStats(){let t=null,e=new Map;for(let i of this.#e_.values()){if(!(i instanceof tE))continue;let s=i.telemetryFinalData;if(!s)continue;let{type:a}=s;e.has(a)||e.set(a,Object.getPrototypeOf(i).constructor),t||=Object.create(null);let r=t[a]||=new Map;for(let[t,e]of Object.entries(s)){if("type"===t)continue;let i=r.get(t);i||(i=new Map,r.set(t,i));let s=i.get(e)??0;i.set(e,s+1)}}for(let[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#ey=null}get modifiedIds(){if(this.#ey)return this.#ey;let t=[];for(let e of this.#e_.values())e instanceof tE&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#ey={ids:new Set(t),hash:t.join(",")}}}class tk extends tM{#ex;constructor(t){super();let{map:e,hash:i,transfer:s}=t.serializable,a=structuredClone(e,s?{transfer:s}:null);this.#ex={map:a,hash:i,transfer:s}}get print(){C("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ex}get modifiedIds(){return M(this,"modifiedIds",{ids:new Set,hash:""})}}class tI{#eE=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));let e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(let t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#eE.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#eE.has(t.loadedName))){if(S(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:i,src:s,style:a}=t,r=new FontFace(i,s,a);this.addNativeFontFace(r);try{await r.load(),this.#eE.add(i),e?.(t)}catch{E(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}C("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){let e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw E(`Failed to load font '${e.family}': '${i}'.`),t.disableFontFace=!0,i}}return}let e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{let i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return M(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;return o?t=!0:"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent)&&(t=!0),M(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){let{loadingRequests:e}=this,i={done:!1,complete:function(){for(S(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;)setTimeout(e.shift().callback,0)},callback:t};return e.push(i),i}get _loadTestFont(){return M(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){var i;let s,a;function r(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function n(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let o=this._document.createElement("canvas");o.width=1,o.height=1;let l=o.getContext("2d"),h=0,d=`lt${Date.now()}${this.loadTestFontId++}`,c=this._loadTestFont,u=r(c=n(c,976,d.length,d),16);for(s=0,a=d.length-3;s>24&255,i>>16&255,i>>8&255,255&i));let p=`url(data:font/opentype;base64,${btoa(c)});`,g=`@font-face {font-family:"${d}";src:${p}}`;this.insertRule(g);let m=this._document.createElement("div");for(let e of(m.style.visibility="hidden",m.style.width=m.style.height="10px",m.style.position="absolute",m.style.top=m.style.left="0px",[t.loadedName,d])){let t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,m.append(t)}this._document.body.append(m),function t(e,i){if(++h>30){E("Load test font never loaded."),i();return}if(l.font="30px "+e,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){i();return}setTimeout(t.bind(null,e,i))}(d,()=>{m.remove(),e.complete()})}}class tL{constructor(t,{disableFontFace:e=!1,inspectFont:i=null}){for(let e in this.compiledGlyphs=Object.create(null),t)this[e]=t[e];this.disableFontFace=!0===e,this._inspectFont=i}createNativeFontFace(){let t;if(!this.data||this.disableFontFace)return null;if(this.cssFontInfo){let e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){var t;let e;if(!this.data||this.disableFontFace)return null;let i=`url(data:${this.mimetype};base64,${(t=this.data,Uint8Array.prototype.toBase64?t.toBase64():btoa(N(t)))});`;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${i}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${i}}`;return this._inspectFont?.(this,i),e}getPathGenerator(t,e){let i;if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];try{i=t.get(this.loadedName+"_path_"+e)}catch(t){E(`getPathGenerator - ignoring character: "${t}".`)}if(!Array.isArray(i)||0===i.length)return this.compiledGlyphs[e]=function(t,e){};let s=[];for(let t=0,e=i.length;tt.bezierCurveTo(e,a,r,n,o,l)),t+=6}break;case q.MOVE_TO:{let[e,a]=i.slice(t,t+2);s.push(t=>t.moveTo(e,a)),t+=2}break;case q.LINE_TO:{let[e,a]=i.slice(t,t+2);s.push(t=>t.lineTo(e,a)),t+=2}break;case q.QUADRATIC_CURVE_TO:{let[e,a,r,n]=i.slice(t,t+4);s.push(t=>t.quadraticCurveTo(e,a,r,n)),t+=4}break;case q.RESTORE:s.push(t=>t.restore());break;case q.SAVE:s.push(t=>t.save());break;case q.SCALE:S(2===s.length,"Scale command is only valid at the third position.");break;case q.TRANSFORM:{let[e,a,r,n,o,l]=i.slice(t,t+6);s.push(t=>t.transform(e,a,r,n,o,l)),t+=6}break;case q.TRANSLATE:{let[e,a]=i.slice(t,t+2);s.push(t=>t.translate(e,a)),t+=2}}return this.compiledGlyphs[e]=function(t,e){s[0](t),s[1](t),t.scale(e,-e);for(let e=2,i=s.length;e({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){C("Abstract method `_fetch` called.")}}class tF extends tD{async _fetch(t){let e=await Y(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):B(e)}}class tO{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,a){return"none"}destroy(t=!1){}}class tN extends tO{#eS;#eT;#eM;#ek;#eI;#eL;#v=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#ek=t,this.#eI=e}get #_(){return this.#eT||=new Map}get #eR(){return this.#eL||=new Map}get #eP(){if(!this.#eM){let t=this.#eI.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;let i=this.#eI.createElementNS(K,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#eM=this.#eI.createElementNS(K,"defs"),t.append(i),i.append(this.#eM),this.#eI.body.append(t)}return this.#eM}#eD(t){if(1===t.length){let e=t[0],i=Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;let s=i.join(",");return[s,s,s]}let[e,i,s]=t,a=Array(256),r=Array(256),n=Array(256);for(let t=0;t<256;t++)a[t]=e[t]/255,r[t]=i[t]/255,n[t]=s[t]/255;return[a.join(","),r.join(","),n.join(",")]}#eF(t){if(void 0===this.#eS){this.#eS="";let t=this.#eI.URL;t!==this.#eI.baseURI&&(Z(t)?E('#createUrl: ignore "data:"-URL for performance reasons.'):this.#eS=t.split("#",1)[0])}return`url(${this.#eS}#${t})`}addFilter(t){if(!t)return"none";let e=this.#_.get(t);if(e)return e;let[i,s,a]=this.#eD(t),r=1===t.length?i:`${i}${s}${a}`;if(e=this.#_.get(r))return this.#_.set(t,e),e;let n=`g_${this.#ek}_transfer_map_${this.#v++}`,o=this.#eF(n);this.#_.set(t,o),this.#_.set(r,o);let l=this.#eO(n);return this.#eN(i,s,a,l),o}addHCMFilter(t,e){let i=`${t}-${e}`,s="base",a=this.#eR.get(s);if(a?.key===i||(a?(a.filter?.remove(),a.key=i,a.url="none",a.filter=null):(a={key:i,url:"none",filter:null},this.#eR.set(s,a)),!t||!e))return a.url;let r=this.#eB(t);t=j.makeHexColor(...r);let n=this.#eB(e);if(e=j.makeHexColor(...n),this.#eP.style.color="","#000000"===t&&"#ffffff"===e||t===e)return a.url;let o=Array(256);for(let t=0;t<=255;t++){let e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}let l=o.join(","),h=`g_${this.#ek}_hcm_filter`,d=a.filter=this.#eO(h);this.#eN(l,l,l,d),this.#eH(d);let c=(t,e)=>{let i=r[t]/255,s=n[t]/255,a=Array(e+1);for(let t=0;t<=e;t++)a[t]=i+t/e*(s-i);return a.join(",")};return this.#eN(c(0,5),c(1,5),c(2,5),d),a.url=this.#eF(h),a.url}addAlphaFilter(t){let e=this.#_.get(t);if(e)return e;let[i]=this.#eD([t]),s=`alpha_${i}`;if(e=this.#_.get(s))return this.#_.set(t,e),e;let a=`g_${this.#ek}_alpha_map_${this.#v++}`,r=this.#eF(a);this.#_.set(t,r),this.#_.set(s,r);let n=this.#eO(a);return this.#ez(i,n),r}addLuminosityFilter(t){let e,i,s=this.#_.get(t||"luminosity");if(s)return s;if(t?([e]=this.#eD([t]),i=`luminosity_${e}`):i="luminosity",s=this.#_.get(i))return this.#_.set(t,s),s;let a=`g_${this.#ek}_luminosity_map_${this.#v++}`,r=this.#eF(a);this.#_.set(t,r),this.#_.set(i,r);let n=this.#eO(a);return this.#eU(n),t&&this.#ez(e,n),r}addHighlightHCMFilter(t,e,i,s,a){let r=`${e}-${i}-${s}-${a}`,n=this.#eR.get(t);if(n?.key===r||(n?(n.filter?.remove(),n.key=r,n.url="none",n.filter=null):(n={key:r,url:"none",filter:null},this.#eR.set(t,n)),!e||!i))return n.url;let[o,l]=[e,i].map(this.#eB.bind(this)),h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[s,a].map(this.#eB.bind(this));d{let s=Array(256),a=(d-h)/i,r=t/255,n=(e-t)/(255*i),o=0;for(let t=0;t<=i;t++){let e=Math.round(h+t*a),i=r+t*n;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},g=`g_${this.#ek}_hcm_${t}_filter`,m=n.filter=this.#eO(g);return this.#eH(m),this.#eN(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),n.url=this.#eF(g),n.url}destroy(t=!1){(!t||0===this.#eR.size)&&(this.#eM&&(this.#eM.parentNode.parentNode.remove(),this.#eM=null),this.#eT&&(this.#eT.clear(),this.#eT=null),this.#v=0)}#eU(t){let e=this.#eI.createElementNS(K,"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)}#eH(t){let e=this.#eI.createElementNS(K,"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)}#eO(t){let e=this.#eI.createElementNS(K,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#eP.append(e),e}#ej(t,e,i){let s=this.#eI.createElementNS(K,e);s.setAttribute("type","discrete"),s.setAttribute("tableValues",i),t.append(s)}#eN(t,e,i,s){let a=this.#eI.createElementNS(K,"feComponentTransfer");s.append(a),this.#ej(a,"feFuncR",t),this.#ej(a,"feFuncG",e),this.#ej(a,"feFuncB",i)}#ez(t,e){let i=this.#eI.createElementNS(K,"feComponentTransfer");e.append(i),this.#ej(i,"feFuncA",t)}#eB(t){return this.#eP.style.color=t,th(getComputedStyle(this.#eP).getPropertyValue("color"))}}class tB{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw Error("Font filename must be specified.");let e=`${this.baseUrl}${t}`;return this._fetch(e).catch(t=>{throw Error(`Unable to load font data at: ${e}`)})}async _fetch(t){C("Abstract method `_fetch` called.")}}class tH extends tB{async _fetch(t){return new Uint8Array(await Y(t,"arraybuffer"))}}if(o){var tz=Promise.withResolvers(),tU=null;(async()=>{let t,e;let i=await import("fs"),s=await import("http");return new Map(Object.entries({fs:i,http:s,https:await import("https"),url:await import("url"),canvas:t,path2d:e}))})().then(t=>{tU=t,tz.resolve()},t=>{E(`loadPackages: ${t}`),tU=new Map,tz.resolve()})}class tj{static get promise(){return tz.promise}static get(t){return tU?.get(t)}}async function t$(t){let e=tj.get("fs");return new Uint8Array(await e.promises.readFile(t))}class tG extends tO{}class tV extends tR{_createCanvas(t,e){return tj.get("canvas").createCanvas(t,e)}}class tW extends tD{async _fetch(t){return t$(t)}}class tq extends tB{async _fetch(t){return t$(t)}}let tK={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function tX(t,e){if(!e)return;let i=e[2]-e[0],s=e[3]-e[1],a=new Path2D;a.rect(e[0],e[1],i,s),t.clip(a)}class tY{getPattern(){C("Abstract method `getPattern` called.")}}class tQ extends tY{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;for(let i of("axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1)),this._colorStops))e.addColorStop(i[0],i[1]);return e}getPattern(t,e,i,s){let a;if(s===tK.STROKE||s===tK.FILL){let r=e.current.getClippedPathBoundingBox(s,td(t))||[0,0,0,0],n=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",n,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-r[0],-r[1]),i=j.transform(i,[1,0,0,1,r[0],r[1]]),h.transform(...e.baseTransform),this.matrix&&h.transform(...this.matrix),tX(h,this._bbox),h.fillStyle=this._createGradient(h),h.fill(),a=t.createPattern(l.canvas,"no-repeat");let d=new DOMMatrix(i);a.setTransform(d)}else tX(t,this._bbox),a=this._createGradient(t);return a}}function tJ(t,e,i,s,a,r,n,o){let l,h,d,c,u,p,g,m,f;let b=e.coords,A=e.colors,v=t.data,y=4*t.width;b[i+1]>b[s+1]&&(l=i,i=s,s=l,l=r,r=n,n=l),b[s+1]>b[a+1]&&(l=s,s=a,a=l,l=n,n=o,o=l),b[i+1]>b[s+1]&&(l=i,i=s,s=l,l=r,r=n,n=l);let _=(b[i]+e.offsetX)*e.scaleX,w=(b[i+1]+e.offsetY)*e.scaleY,x=(b[s]+e.offsetX)*e.scaleX,E=(b[s+1]+e.offsetY)*e.scaleY,C=(b[a]+e.offsetX)*e.scaleX,S=(b[a+1]+e.offsetY)*e.scaleY;if(w>=S)return;let T=A[r],M=A[r+1],k=A[r+2],I=A[n],L=A[n+1],R=A[n+2],P=A[o],D=A[o+1],F=A[o+2],O=Math.round(w),N=Math.round(S);for(let t=O;t<=N;t++){let e;if(tS?1:E===S?0:(E-t)/(E-S)),d=I-(I-P)*e,c=L-(L-D)*e,u=R-(R-F)*e}p=_-(_-C)*(e=tS?1:(w-t)/(w-S)),g=T-(T-P)*e,m=M-(M-D)*e,f=k-(k-F)*e;let i=Math.round(Math.min(h,p)),s=Math.round(Math.max(h,p)),a=y*t+4*i;for(let t=i;t<=s;t++)(e=(h-t)/(h-p))<0?e=0:e>1&&(e=1),v[a++]=d-(d-g)*e|0,v[a++]=c-(c-m)*e|0,v[a++]=u-(u-f)*e|0,v[a++]=255}}class tZ extends tY{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,i){let s=Math.floor(this._bounds[0]),a=Math.floor(this._bounds[1]),r=Math.ceil(this._bounds[2])-s,n=Math.ceil(this._bounds[3])-a,o=Math.min(Math.ceil(Math.abs(r*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(n*t[1]*1.1)),3e3),h=r/o,d=n/l,c={coords:this._coords,colors:this._colors,offsetX:-s,offsetY:-a,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){let t=f.data;for(let i=0,s=t.length;i=Math.ceil(p*b)?v=o:_=!0,E>=C?y=l:w=!0;let S=this.getSizeAndScale(v,this.ctx.canvas.width,b),T=this.getSizeAndScale(y,this.ctx.canvas.height,A),M=t.cachedCanvases.getCanvas("pattern",S.size,T.size),k=M.context,I=n.createCanvasGraphics(k);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,r),k.translate(-S.scale*h,-T.scale*d),I.transform(S.scale,0,0,T.scale,0,0),k.save(),this.clipBbox(I,h,d,c,u),I.baseTransform=td(I.ctx),I.executeOperatorList(i),I.endDrawing(),k.restore(),_||w){let e=M.canvas;_&&(v=o),w&&(y=l);let i=this.getSizeAndScale(v,this.ctx.canvas.width,b),s=this.getSizeAndScale(y,this.ctx.canvas.height,A),a=i.size,r=s.size,n=t.cachedCanvases.getCanvas("pattern-workaround",a,r),c=n.context,u=_?Math.floor(p/o):0,m=w?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=m;i++)c.drawImage(e,a*t,r*i,a,r,0,0,a,r);return{canvas:n.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:d}}return{canvas:M.canvas,scaleX:S.scale,scaleY:T.scale,offsetX:h,offsetY:d}}getSizeAndScale(t,e,i){let s=Math.max(t2.MAX_PATTERN_SIZE,e),a=Math.ceil(t*i);return a>=s?a=s:i=a/t,{scale:i,size:a}}clipBbox(t,e,i,s,a){let r=s-e,n=a-i;t.ctx.rect(e,i,r,n),t.current.updateRectMinMax(td(t.ctx),[e,i,s,a]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){let s=t.ctx,a=t.current;switch(e){case t1.COLORED:let r=this.ctx;s.fillStyle=r.fillStyle,s.strokeStyle=r.strokeStyle,a.fillColor=r.fillStyle,a.strokeColor=r.strokeStyle;break;case t1.UNCOLORED:let n=j.makeHexColor(i[0],i[1],i[2]);s.fillStyle=n,s.strokeStyle=n,a.fillColor=n,a.strokeColor=n;break;default:throw new F(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let a=i;s!==tK.SHADING&&(a=j.transform(a,e.baseTransform),this.matrix&&(a=j.transform(a,this.matrix)));let r=this.createPatternCanvas(e),n=new DOMMatrix(a);n=(n=n.translate(r.offsetX,r.offsetY)).scale(1/r.scaleX,1/r.scaleY);let o=t.createPattern(r.canvas,"repeat");return o.setTransform(n),o}}class t3{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,i){let s;return void 0!==this.cache[t]?(s=this.cache[t],this.canvasFactory.reset(s,e,i)):(s=this.canvasFactory.create(e,i),this.cache[t]=s),s}delete(t){delete this.cache[t]}clear(){for(let t in this.cache){let e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function t5(t,e,i,s,a,r,n,o,l,h){let[d,c,u,p,g,m]=td(t);if(0===c&&0===u){let f=Math.round(n*d+g),b=Math.round(o*p+m),A=Math.abs(Math.round((n+l)*d+g)-f)||1,v=Math.abs(Math.round((o+h)*p+m)-b)||1;return t.setTransform(Math.sign(d),0,0,Math.sign(p),f,b),t.drawImage(e,i,s,a,r,0,0,A,v),t.setTransform(d,c,u,p,g,m),[A,v]}if(0===d&&0===p){let f=Math.round(o*u+g),b=Math.round(n*c+m),A=Math.abs(Math.round((o+h)*u+g)-f)||1,v=Math.abs(Math.round((n+l)*c+m)-b)||1;return t.setTransform(0,Math.sign(c),Math.sign(u),0,f,b),t.drawImage(e,i,s,a,r,0,0,v,A),t.setTransform(d,c,u,p,g,m),[v,A]}return t.drawImage(e,i,s,a,r,n,o,l,h),[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}class t6{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=l,this.textMatrixScale=1,this.fontMatrix=h,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=m.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){let t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,i){[e,i]=j.applyTransform([e,i],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,i),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,i)}updateRectMinMax(t,e){let i=j.applyTransform(e,t),s=j.applyTransform(e.slice(2),t),a=j.applyTransform([e[0],e[3]],t),r=j.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,i[0],s[0],a[0],r[0]),this.minY=Math.min(this.minY,i[1],s[1],a[1],r[1]),this.maxX=Math.max(this.maxX,i[0],s[0],a[0],r[0]),this.maxY=Math.max(this.maxY,i[1],s[1],a[1],r[1])}updateScalingPathMinMax(t,e){j.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,i,s,a,r,n,o,l,h){let d=j.bezierBoundingBox(e,i,s,a,r,n,o,l,h);!h&&this.updateRectMinMax(t,d)}getPathBoundingBox(t=tK.FILL,e=null){let i=[this.minX,this.minY,this.maxX,this.maxY];if(t===tK.STROKE){e||C("Stroke bounding box must include transform.");let t=j.singularValueDecompose2dScale(e),s=t[0]*this.lineWidth/2,a=t[1]*this.lineWidth/2;i[0]-=s,i[1]-=a,i[2]+=s,i[3]+=a}return i}updateClipFromPath(){let t=j.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=tK.FILL,e=null){return j.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function t4(t,e){let i,s,a,r;if("undefined"!=typeof ImageData&&e instanceof ImageData){t.putImageData(e,0,0);return}let n=e.height,o=e.width,l=n%16,h=(n-l)/16,d=0===l?h:h+1,c=t.createImageData(o,16),u=0,p,g=e.data,m=c.data;if(e.kind===f.GRAYSCALE_1BPP){let e=g.byteLength,r=new Uint32Array(m.buffer,0,m.byteLength>>2),n=r.length,f=o+7>>3,b=z.isLittleEndian?0xff000000:255;for(i=0;if?o:8*t-7,a=-8&s,n=0,l=0;for(;i>=1}for(;p=h&&(r=o*(a=l)),p=0,s=r;s--;)m[p++]=g[u++],m[p++]=g[u++],m[p++]=g[u++],m[p++]=255;t.putImageData(c,0,16*i)}else throw Error(`bad image kind: ${e.kind}`)}function t8(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}let i=e.height,s=e.width,a=i%16,r=(i-a)/16,n=0===a?r:r+1,o=t.createImageData(s,16),l=0,h=e.data,d=o.data;for(let e=0;e>3,c=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s10&&"function"==typeof i,d=h?Date.now()+15:0,c=0,u=this.commonObjs,p=this.objs;for(;;){if(void 0!==s&&o===s.nextBreakPoint)return s.breakIt(o,i),o;if((a=n[o])!==y.dependency)this[a].apply(this,r[o]);else for(let t of r[o]){let e=t.startsWith("g_")?u:p;if(!e.has(t))return e.get(t,i),o}if(++o===l)return o;if(h&&++c>10){if(Date.now()>d)return i(),o;c=0}}}#e$(){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(){for(let t of(this.#e$(),this.cachedCanvases.clear(),this.cachedPatterns.clear(),this._cachedBitmapsMap.values())){for(let e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#eG()}#eG(){if(this.pageColors){let t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){let e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){let i,s;let a=t.width??t.displayWidth,r=t.height??t.displayHeight,n=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=a,h=r,d="prescale1";for(;n>2&&l>1||o>2&&h>1;){let e=l,a=h;n>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),n/=l/e),o>2&&h>1&&(a=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/a),(s=(i=this.cachedCanvases.getCanvas(d,e,a)).context).clearRect(0,0,e,a),s.drawImage(t,0,0,l,h,0,0,e,a),t=i.canvas,l=e,h=a,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){let e,i,s,a;let r=this.ctx,{width:n,height:o}=t,l=this.current.fillColor,h=this.current.patternFill,d=td(r);if((t.bitmap||t.data)&&t.count>1){let a=t.bitmap||t.data.buffer;i=JSON.stringify(h?d:[d.slice(0,4),l]),(e=this._cachedBitmapsMap.get(a))||(e=new Map,this._cachedBitmapsMap.set(a,e));let r=e.get(i);if(r&&!h)return{canvas:r,offsetX:Math.round(Math.min(d[0],d[2])+d[4]),offsetY:Math.round(Math.min(d[1],d[3])+d[5])};s=r}s||t8((a=this.cachedCanvases.getCanvas("maskCanvas",n,o)).context,t);let c=j.transform(d,[1/n,0,0,-1/o,0,0]);c=j.transform(c,[1,0,0,1,0,-o]);let[u,p,g,m]=j.getAxialAlignedBoundingBox([0,0,n,o],c),f=Math.round(g-u)||1,b=Math.round(m-p)||1,A=this.cachedCanvases.getCanvas("fillCanvas",f,b),v=A.context;v.translate(-u,-p),v.transform(...c),!s&&(s=(s=this._scaleImage(a.canvas,tc(v))).img,e&&h&&e.set(i,s)),v.imageSmoothingEnabled=et(td(v),t.interpolate),t5(v,s,0,0,s.width,s.height,0,0,n,o),v.globalCompositeOperation="source-in";let y=j.transform(tc(v),[1,0,0,1,-u,-p]);return v.fillStyle=h?l.getPattern(r,this,y,tK.FILL):l,v.fillRect(0,0,n,o),e&&!h&&(this.cachedCanvases.delete("fillCanvas"),e.set(i,A.canvas)),{canvas:A.canvas,offsetX:Math.round(u),offsetY:Math.round(p)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ee[t]}setLineJoin(t){this.ctx.lineJoin=ei[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){let i=this.ctx;void 0!==i.setLineDash&&(i.setLineDash(t),i.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(let[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i,this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw Error("beginSMaskMode called while already in smask mode");let t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx,this.ctx=s.context;let a=this.ctx;a.setTransform(...td(this.suspendedCtx)),t7(this.suspendedCtx,a),function(t,e){if(t._removeMirroring)throw Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,s,a,r,n){e.transform(t,i,s,a,r,n),this.__originalTransform(t,i,s,a,r,n)},t.setTransform=function(t,i,s,a,r,n){e.setTransform(t,i,s,a,r,n),this.__originalSetTransform(t,i,s,a,r,n)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,s,a,r,n){e.bezierCurveTo(t,i,s,a,r,n),this.__originalBezierCurveTo(t,i,s,a,r,n)},t.rect=function(t,i,s,a){e.rect(t,i,s,a),this.__originalRect(t,i,s,a)},t.closePath=function(){e.closePath(),this.__originalClosePath()},t.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}(a,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),t7(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];let e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,s){let a=s[0],r=s[1],n=s[2]-a,o=s[3]-r;0!==n&&0!==o&&(this.genericComposeSMask(e.context,i,n,o,e.subtype,e.backdrop,e.transferMap,a,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,s,a,r,n,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(r){let e=j.makeHexColor(...r);if(u<0||p<0||u+i>c.width||p+s>c.height){let t=this.cachedCanvases.getCanvas("maskExtension",i,s),a=t.context;a.drawImage(c,-u,-p),a.globalCompositeOperation="destination-atop",a.fillStyle=e,a.fillRect(0,0,i,s),a.globalCompositeOperation="source-over",c=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);let a=new Path2D;a.rect(u,p,i,s),t.clip(a),t.globalCompositeOperation="destination-atop",t.fillStyle=e,t.fillRect(u,p,i,s),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===a&&n?e.filter=this.filterFactory.addAlphaFilter(n):"Luminosity"===a&&(e.filter=this.filterFactory.addLuminosityFilter(n));let g=new Path2D;g.rect(o,l,i,s),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,s,o,l,i,s),e.restore()}save(){this.inSMaskMode?(t7(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),t7(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,i,s,a,r){this.ctx.transform(t,e,i,s,a,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){let s,a;let r=this.ctx,n=this.current,o=n.x,l=n.y,h=td(r),d=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],c=d?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(l=100),this.current.fontSizeScale=e/l,this.ctx.font=`${o} ${n} ${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,i,s,a,r){this.current.textMatrix=[t,e,i,s,a,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)}paintChar(t,e,i,s){let a;let r=this.ctx,n=this.current,o=n.font,l=n.textRenderingMode,h=n.fontSize/n.fontSizeScale,d=l&m.FILL_STROKE_MASK,c=!!(l&m.ADD_TO_PATH_FLAG),u=n.patternFill&&!o.missingFile;(o.disableFontFace||c||u)&&(a=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||u?(r.save(),r.translate(e,i),r.beginPath(),a(r,h),s&&r.setTransform(...s),(d===m.FILL||d===m.FILL_STROKE)&&r.fill(),(d===m.STROKE||d===m.FILL_STROKE)&&r.stroke(),r.restore()):((d===m.FILL||d===m.FILL_STROKE)&&r.fillText(t,e,i),(d===m.STROKE||d===m.FILL_STROKE)&&r.strokeText(t,e,i)),c&&(this.pendingTextPaths||=[]).push({transform:td(r),x:e,y:i,fontSize:h,addToPath:a})}get isFontSubpixelAAEnabled(){let{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);let e=t.getImageData(0,0,10,10).data,i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return M(this,"isFontSubpixelAAEnabled",i)}showText(t){let e;let i=this.current,s=i.font;if(s.isType3Font)return this.showType3Text(t);let a=i.fontSize;if(0===a)return;let r=this.ctx,n=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,d=i.textHScale*h,c=t.length,u=s.vertical,p=u?1:-1,g=s.defaultVMetrics,f=a*i.fontMatrix[0],b=i.textRenderingMode===m.FILL&&!s.disableFontFace&&!i.patternFill;if(r.save(),r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),h>0?r.scale(d,-1):r.scale(d,1),i.patternFill){r.save();let t=i.fillColor.getPattern(r,this,tc(r),tK.FILL);e=td(r),r.restore(),r.fillStyle=t}let A=i.lineWidth,v=i.textMatrixScale;if(0===v||0===A){let t=i.textRenderingMode&m.FILL_STROKE_MASK;(t===m.STROKE||t===m.FILL_STROKE)&&(A=this.getSinglePixelWidth())}else A/=v;if(1!==n&&(r.scale(n,n),A/=n),r.lineWidth=A,s.isInvalidPDFjsFont){let e=[],s=0;for(let i of t)e.push(i.unicode),s+=i.width;r.fillText(e.join(""),0,0),i.x+=s*f*d,r.restore(),this.compose();return}let y=0,_;for(_=0;_0){let t=1e3*r.measureText(v).width/a*n;if(xnew er(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})},s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=j.makeHexColor(t,e,i)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=j.makeHexColor(t,e,i),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=function(t){switch(t[0]){case"RadialAxial":return new tQ(t);case"Mesh":return new tZ(t);case"Dummy":return new t0}throw Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t)),this.cachedPatterns.set(t,i)),e&&(i.matrix=e),i}shadingFill(t){if(!this.contentVisible)return;let e=this.ctx;this.save(),e.fillStyle=this._getPattern(t).getPattern(e,this,tc(e),tK.SHADING);let i=tc(e);if(i){let{width:t,height:s}=e.canvas,[a,r,n,o]=j.getAxialAlignedBoundingBox([0,0,t,s],i);this.ctx.fillRect(a,r,n-a,o-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){C("Should not call beginInlineImage")}beginImageData(){C("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=td(this.ctx),e)){let t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i),this.current.updateRectMinMax(td(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);let e=this.ctx;t.isolated||x("TODO: Support non-isolated groups."),t.knockout&&E("Knockout groups not supported.");let i=td(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw Error("Bounding box is required.");let s=j.getAxialAlignedBoundingBox(t.bbox,td(e)),a=[0,0,e.canvas.width,e.canvas.height],r=Math.floor((s=j.intersect(s,a)||[0,0,0,0])[0]),n=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-r,1),l=Math.max(Math.ceil(s[3])-n,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);let d=this.cachedCanvases.getCanvas(h,o,l),c=d.context;c.translate(-r,-n),c.transform(...i),t.smask?this.smaskStack.push({canvas:d.canvas,context:c,offsetX:r,offsetY:n,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,n),e.save()),t7(e,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;let e=this.ctx,i=this.groupStack.pop();if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let t=td(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...t);let i=j.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,e,i,s,a){if(this.#e$(),t9(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){let s=e[2]-e[0],r=e[3]-e[1];if(a&&this.annotationCanvasMap){i=i.slice(),i[4]-=e[0],i[5]-=e[1],(e=e.slice())[0]=e[1]=0,e[2]=s,e[3]=r;let[a,n]=j.singularValueDecompose2dScale(td(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(r*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);let{canvas:d,context:c}=this.annotationCanvas;this.annotationCanvasMap.set(t,d),this.annotationCanvas.savedCtx=this.ctx,this.ctx=c,this.ctx.save(),this.ctx.setTransform(a,0,0,-n,0,r*n),t9(this.ctx)}else t9(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],s,r),this.ctx.clip(),this.ctx.beginPath()}this.current=new t6(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...i),this.transform(...s)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#eG(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;let e=t.count;(t=this.getObject(t.data,t)).count=e;let i=this.ctx,s=this.processingType3;if(s&&(void 0===s.compiled&&(s.compiled=function(t){let e,i,s;let{width:a,height:r}=t;if(a>1e3||r>1e3)return null;let n=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),o=a+1,l=new Uint8Array(o*(r+1)),h=a+7&-8,d=new Uint8Array(h*r),c=0;for(let e of t.data){let t=128;for(;t>0;)d[c++]=e&t?0:255,t>>=1}let u=0;for(0!==d[c=0]&&(l[0]=1,++u),i=1;i>2)+4*!!d[c+1]+8*!!d[c-h+1]]&&(l[s+i]=n[t],++u),c++;if(d[c-h]!==d[c]&&(l[s+i]=d[c]?2:4,++u),u>1e3)return null}for(c=h*(r-1),s=e*o,0!==d[c]&&(l[s]=8,++u),i=1;i1e3)return null;let p=new Int32Array([0,o,-1,0,-o,0,0,0,1]),g=new Path2D;for(e=0;u&&e<=r;e++){let t=e*o,i=t+a;for(;t>4,l[t]&=r>>2|r<<2),g.lineTo(t%o,t/o|0),!l[t]&&--u}while(s!==t);--e}return d=null,l=null,function(t){t.save(),t.scale(1/a,-1/r),t.translate(0,-r),t.fill(g),t.beginPath(),t.restore()}}(t)),s.compiled)){s.compiled(i);return}let a=this._createMaskCanvas(t),r=a.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(r,a.offsetX,a.offsetY),i.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,a,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);let n=this.ctx;n.save();let o=td(n);n.transform(e,i,s,a,0,0);let l=this._createMaskCanvas(t);n.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=r.length;ts?h/s:1,e=l>s?l/s:1}}this._cachedScaleForStroking[0]=t,this._cachedScaleForStroking[1]=e}return this._cachedScaleForStroking}rescaleAndStroke(t){let{ctx:e}=this,{lineWidth:i}=this.current,[s,a]=this.getScaleForStroking();if(e.lineWidth=i||1,1===s&&1===a){e.stroke();return}let r=e.getLineDash();if(t&&e.save(),e.scale(s,a),r.length>0){let t=Math.max(s,a);e.setLineDash(r.map(e=>e/t)),e.lineDashOffset/=t}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(let t in y)void 0!==er.prototype[t]&&(er.prototype[y[t]]=er.prototype[t]);class en{static #eV=null;static #eW="";static get workerPort(){return this.#eV}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw Error("Invalid `workerPort` type.");this.#eV=t}static get workerSrc(){return this.#eW}static set workerSrc(t){if("string"!=typeof t)throw Error("Invalid `workerSrc` type.");this.#eW=t}}let eo={DATA:1,ERROR:2},el={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function eh(t){switch(t instanceof Error||"object"==typeof t&&null!==t||C('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),t.name){case"AbortException":return new O(t.message);case"MissingPDFException":return new P(t.message);case"PasswordException":return new I(t.message,t.code);case"UnexpectedResponseException":return new D(t.message,t.status);case"UnknownErrorException":return new L(t.message,t.details);default:return new L(t.message,t.toString())}}class ed{#eq=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#eK.bind(this),{signal:this.#eq.signal})}#eK({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#eX(t);return}if(t.callback){let e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===eo.DATA)i.resolve(t.data);else if(t.callback===eo.ERROR)i.reject(eh(t.reason));else throw Error("Unexpected callback case");return}let e=this.actionHandler[t.action];if(!e)throw Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){let i=this.sourceName,s=t.sourceName,a=this.comObj;new Promise(function(i){i(e(t.data))}).then(function(e){a.postMessage({sourceName:i,targetName:s,callback:eo.DATA,callbackId:t.callbackId,data:e})},function(e){a.postMessage({sourceName:i,targetName:s,callback:eo.ERROR,callbackId:t.callbackId,reason:eh(e)})});return}if(t.streamId){this.#eY(t);return}e(t.data)}on(t,e){let i=this.actionHandler;if(i[t])throw Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){let s=this.callbackId++,a=Promise.withResolvers();this.callbackCapabilities[s]=a;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){a.reject(t)}return a.promise}sendWithStream(t,e,i,s){let a=this.streamId++,r=this.sourceName,n=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{let l=Promise.withResolvers();return this.streamControllers[a]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:r,targetName:n,action:t,streamId:a,data:e,desiredSize:i.desiredSize},s),l.promise},pull:t=>{let e=Promise.withResolvers();return this.streamControllers[a].pullCall=e,o.postMessage({sourceName:r,targetName:n,stream:el.PULL,streamId:a,desiredSize:t.desiredSize}),e.promise},cancel:t=>{S(t instanceof Error,"cancel must have a valid reason");let e=Promise.withResolvers();return this.streamControllers[a].cancelCall=e,this.streamControllers[a].isClosed=!0,o.postMessage({sourceName:r,targetName:n,stream:el.CANCEL,streamId:a,reason:eh(t)}),e.promise}},i)}#eY(t){let e=t.streamId,i=this.sourceName,s=t.sourceName,a=this.comObj,r=this,n=this.actionHandler[t.action],o={enqueue(t,r=1,n){if(this.isCancelled)return;let o=this.desiredSize;this.desiredSize-=r,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),a.postMessage({sourceName:i,targetName:s,stream:el.ENQUEUE,streamId:e,chunk:t},n)},close(){!this.isCancelled&&(this.isCancelled=!0,a.postMessage({sourceName:i,targetName:s,stream:el.CLOSE,streamId:e}),delete r.streamSinks[e])},error(t){S(t instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,a.postMessage({sourceName:i,targetName:s,stream:el.ERROR,streamId:e,reason:eh(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,new Promise(function(e){e(n(t.data,o))}).then(function(){a.postMessage({sourceName:i,targetName:s,stream:el.START_COMPLETE,streamId:e,success:!0})},function(t){a.postMessage({sourceName:i,targetName:s,stream:el.START_COMPLETE,streamId:e,reason:eh(t)})})}#eX(t){let e=t.streamId,i=this.sourceName,s=t.sourceName,a=this.comObj,r=this.streamControllers[e],n=this.streamSinks[e];switch(t.stream){case el.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(eh(t.reason));break;case el.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(eh(t.reason));break;case el.PULL:if(!n){a.postMessage({sourceName:i,targetName:s,stream:el.PULL_COMPLETE,streamId:e,success:!0});break}n.desiredSize<=0&&t.desiredSize>0&&n.sinkCapability.resolve(),n.desiredSize=t.desiredSize,new Promise(function(t){t(n.onPull?.())}).then(function(){a.postMessage({sourceName:i,targetName:s,stream:el.PULL_COMPLETE,streamId:e,success:!0})},function(t){a.postMessage({sourceName:i,targetName:s,stream:el.PULL_COMPLETE,streamId:e,reason:eh(t)})});break;case el.ENQUEUE:if(S(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case el.CLOSE:if(S(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#eQ(r,e);break;case el.ERROR:S(r,"error should have stream controller"),r.controller.error(eh(t.reason)),this.#eQ(r,e);break;case el.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(eh(t.reason)),this.#eQ(r,e);break;case el.CANCEL:if(!n)break;new Promise(function(e){e(n.onCancel?.(eh(t.reason)))}).then(function(){a.postMessage({sourceName:i,targetName:s,stream:el.CANCEL_COMPLETE,streamId:e,success:!0})},function(t){a.postMessage({sourceName:i,targetName:s,stream:el.CANCEL_COMPLETE,streamId:e,reason:eh(t)})}),n.sinkCapability.reject(eh(t.reason)),n.isCancelled=!0,delete this.streamSinks[e];break;default:throw Error("Unexpected stream case")}}async #eQ(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#eq?.abort(),this.#eq=null}}class ec{#eJ;#eZ;constructor({parsedData:t,rawData:e}){this.#eJ=t,this.#eZ=e}getRaw(){return this.#eZ}get(t){return this.#eJ.get(t)??null}getAll(){return H(this.#eJ)}has(t){return this.#eJ.has(t)}}let eu=Symbol("INTERNAL");class ep{#e0=!1;#e1=!1;#e2=!1;#e3=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:a}){this.#e0=!!(t&d.DISPLAY),this.#e1=!!(t&d.PRINT),this.name=e,this.intent=i,this.usage=s,this.rbGroups=a}get visible(){if(this.#e2)return this.#e3;if(!this.#e3)return!1;let{print:t,view:e}=this.usage;return this.#e0?e?.viewState!=="OFF":!this.#e1||t?.printState!=="OFF"}_setVisible(t,e,i=!1){t!==eu&&C("Internal method `_setVisible` called."),this.#e2=i,this.#e3=e}}class eg{#e5=null;#e6=new Map;#e4=null;#e8=null;constructor(t,e=d.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,null===t)return;for(let i of(this.name=t.name,this.creator=t.creator,this.#e8=t.order,t.groups))this.#e6.set(i.id,new ep(e,i));if("OFF"===t.baseState)for(let t of this.#e6.values())t._setVisible(eu,!1);for(let e of t.on)this.#e6.get(e)._setVisible(eu,!0);for(let e of t.off)this.#e6.get(e)._setVisible(eu,!1);this.#e4=this.getHash()}#e7(t){let e=t.length;if(e<2)return!0;let i=t[0];for(let s=1;s0?H(this.#e6):null}getGroup(t){return this.#e6.get(t)||null}getHash(){if(null!==this.#e5)return this.#e5;let t=new tS;for(let[e,i]of this.#e6)t.update(`${e}:${i.visible}`);return this.#e5=t.hexdigest()}}class em{constructor(t,{disableRange:e=!1,disableStream:i=!1}){S(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:s,initialData:a,progressiveDone:r,contentDispositionFilename:n}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=n,a?.length>0){let t=a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!i,this._isRangeSupported=!e,this._contentLength=s,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((t,e)=>{this._onReceiveData({begin:t,chunk:e})}),t.addProgressListener((t,e)=>{this._onProgress({loaded:t,total:e})}),t.addProgressiveReadListener(t=>{this._onReceiveData({chunk:t})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){let i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;void 0===t?this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i):S(this._rangeReaders.some(function(e){return e._begin===t&&(e._enqueue(i),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){let e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){S(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let t=this._queuedChunks;return this._queuedChunks=null,new ef(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;let i=new eb(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(i),i}cancelAllRequests(t){for(let e of(this._fullRequestReader?.cancel(t),this._rangeReaders.slice(0)))e.cancel(t);this._pdfDataRangeTransport.abort()}}class ef{constructor(t,e,i=!1,s=null){for(let a of(this._stream=t,this._done=i||!1,this._filename=tt(s)?s:null,this._queuedChunks=e||[],this._loaded=0,this._queuedChunks))this._loaded+=a.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};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){for(let t of(this._done=!0,this._requests))t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){!this._done&&(this._done=!0)}}class eb{constructor(t,e,i){this._stream=t,this._begin=e,this._end=i,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{for(let e of(this._requests.shift().resolve({value:t,done:!1}),this._requests))e.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){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){for(let t of(this._done=!0,this._requests))t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function eA(t,e){let i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(let t in e){let s=e[t];void 0!==s&&i.append(t,s)}return i}function ev({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){let a={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);return Number.isInteger(r)&&(a.suggestedLength=r,r<=2*i||s||!e||"bytes"!==t.get("Accept-Ranges")||"identity"!==(t.get("Content-Encoding")||"identity")||(a.allowRangeRequests=!0)),a}function ey(t){let e=t.get("Content-Disposition");if(e){let t=function(t){let e=!0,i=s("filename\\*","i").exec(t);if(i){let t=n(i=i[1]);return r(t=l(t=o(t=unescape(t))))}if(i=function(t){let e;let i=[],a=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(e=a.exec(t));){let[,t,s,a]=e;if((t=parseInt(t,10))in i){if(0===t)break;continue}i[t]=[s,a]}let r=[];for(let t=0;t{if(!ew(e.status))throw e_(e.status,s);this._reader=e.body.getReader(),this._headersCapability.resolve();let i=e.headers,{allowRangeRequests:a,suggestedLength:r}=ev({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=r||this._contentLength,this._filename=ey(i),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new O("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;let{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:eE(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class eT{constructor(t,e,i){this._stream=t,this._reader=null,this._loaded=0;let s=t.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController;let a=new Headers(t.headers);a.append("Range",`bytes=${e}-${i-1}`);let r=s.url;fetch(r,ex(a,this._withCredentials,this._abortController)).then(t=>{if(!ew(t.status))throw e_(t.status,r);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:eE(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class eM{constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=eA(this.isHttp,e),this.withCredentials=i||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,e,i){let s={begin:t,end:e};for(let t in i)s[t]=i[t];return this.request(s)}requestFull(t){return this.request(t)}request(t){let e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};for(let[t,i]of(e.open("GET",this.url),e.withCredentials=this.withCredentials,this.headers))e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),s.expectedStatus=206):s.expectedStatus=200,e.responseType="arraybuffer",t.onError&&(e.onerror=function(i){t.onError(e.status)}),e.onreadystatechange=this.onStateChange.bind(this,i),e.onprogress=this.onProgress.bind(this,i),s.onHeadersReceived=t.onHeadersReceived,s.onDone=t.onDone,s.onError=t.onError,s.onProgress=t.onProgress,e.send(null),i}onProgress(t,e){let i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){let i=this.pendingRequests[t];if(!i)return;let s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==s.readyState||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],0===s.status&&this.isHttp){i.onError?.(s.status);return}let a=s.status||200;if((200!==a||206!==i.expectedStatus)&&a!==i.expectedStatus){i.onError?.(s.status);return}let r=function(t){let e=t.response;return"string"!=typeof e?e:B(e).buffer}(s);if(206===a){let t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);i.onDone({begin:parseInt(e[1],10),chunk:r})}else r?i.onDone({begin:0,chunk:r}):i.onError?.(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){let e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class ek{constructor(t){this._source=t,this._manager=new eM(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){let e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return S(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new eI(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){let i=new eL(this._manager,t,e);return i.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(i),i}cancelAllRequests(t){for(let e of(this._fullRequestReader?.cancel(t),this._rangeRequestReaders.slice(0)))e.cancel(t)}}class eI{constructor(t,e){this._manager=t;let i={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url,this._fullRequestId=t.requestFull(i),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(){let t=this._fullRequestId,e=new Headers(this._manager.getRequestXhr(t).getAllResponseHeaders().trim().split(/[\r\n]+/).map(t=>{let[e,...i]=t.split(": ");return[e,i.join(": ")]})),{allowRangeRequests:i,suggestedLength:s}=ev({responseHeaders:e,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=s||this._contentLength,this._filename=ey(e),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(let t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){for(let e of(this._storedError=e_(t,this._url),this._headersCapability.reject(this._storedError),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(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){for(let e of(this._done=!0,this._headersCapability.reject(t),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 eL{constructor(t,e,i){this._manager=t;let s={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(e,i,s),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){let e=t.chunk;for(let t of(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0,this._requests))t.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){for(let e of(this._storedError=e_(t,this._url),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(null!==this._queuedChunk){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){for(let t of(this._done=!0,this._requests))t.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}let eR=/^[a-z][a-z0-9\-+.]+:/i;function eP(t,e,i){return"http:"===t.protocol?tj.get("http").request(t,{headers:e},i):tj.get("https").request(t,{headers:e},i)}class eD{constructor(t){this.source=t,this.url=function(t){return new URL(eR.test(t)?t:tj.get("url").pathToFileURL(t))}(t.url),this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol,this.isFsUrl="file:"===this.url.protocol,this.headers=eA(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return S(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new eH(this):new eN(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;let i=this.isFsUrl?new ez(this,t,e):new eB(this,t,e);return this._rangeRequestReaders.push(i),i}cancelAllRequests(t){for(let e of(this._fullRequestReader?.cancel(t),this._rangeRequestReaders.slice(0)))e.cancel(t)}}class eF{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;let e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,this._rangeChunkSize||this._disableRange||(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let t=this._readableStream.read();return null===t?(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",t=>{this._error(t)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new O("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class eO{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let t=this._readableStream.read();return null===t?(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",t=>{this._error(t)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class eN extends eF{constructor(t){super(t);let e=Object.fromEntries(t.headers);this._request=eP(this._url,e,e=>{if(404===e.statusCode){let t=new P(`Missing PDF "${this._url}".`);this._storedError=t,this._headersCapability.reject(t);return}this._headersCapability.resolve(),this._setReadableStream(e);let i=new Headers(this._readableStream.headers),{allowRangeRequests:s,suggestedLength:a}=ev({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s,this._contentLength=a||this._contentLength,this._filename=ey(i)}),this._request.on("error",t=>{this._storedError=t,this._headersCapability.reject(t)}),this._request.end()}}class eB extends eO{constructor(t,e,i){super(t);let s=Object.fromEntries(t.headers);s.Range=`bytes=${e}-${i-1}`,this._request=eP(this._url,s,t=>{if(404===t.statusCode){let t=new P(`Missing PDF "${this._url}".`);this._storedError=t;return}this._setReadableStream(t)}),this._request.on("error",t=>{this._storedError=t}),this._request.end()}}class eH extends eF{constructor(t){super(t);let e=tj.get("fs");e.promises.lstat(this._url).then(t=>{this._contentLength=t.size,this._setReadableStream(e.createReadStream(this._url)),this._headersCapability.resolve()},t=>{"ENOENT"===t.code&&(t=new P(`Missing PDF "${this._url}".`)),this._storedError=t,this._headersCapability.reject(t)})}}class ez extends eO{constructor(t,e,i){super(t);let s=tj.get("fs");this._setReadableStream(s.createReadStream(this._url,{start:e,end:i-1}))}}class eU{#e9=Promise.withResolvers();#tu=null;#it=!1;#ie=!!globalThis.FontInspector?.enabled;#ii=null;#is=null;#ia=0;#ir=0;#io=null;#il=null;#ih=0;#id=0;#ic=Object.create(null);#iu=[];#ip=null;#ig=[];#im=new WeakMap;#ib=null;static #iA=new Map;static #iv=new Map;static #iy=new WeakMap;static #i_=null;static #iw=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#ip=t;else if("object"==typeof t)this.#ip=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error('No "textContentSource" parameter specified.');this.#tu=this.#il=e,this.#id=i.scale*(globalThis.devicePixelRatio||1),this.#ih=i.rotation,this.#is={div:null,properties:null,ctx:null};let{pageWidth:s,pageHeight:a,pageX:r,pageY:n}=i.rawDims;this.#ib=[1,0,0,-1,-r,n+a],this.#ir=s,this.#ia=a,eU.#ix(),tu(e,i),this.#e9.promise.finally(()=>{eU.#iw.delete(this),this.#is=null,this.#ic=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:t,isFirefox:e}=z.platform;return M(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){let t=()=>{this.#io.read().then(({value:e,done:i})=>{if(i){this.#e9.resolve();return}this.#ii??=e.lang,Object.assign(this.#ic,e.styles),this.#iE(e.items),t()},this.#e9.reject)};return this.#io=this.#ip.getReader(),eU.#iw.add(this),t(),this.#e9.promise}update({viewport:t,onBefore:e=null}){let i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#ih&&(e?.(),this.#ih=s,tu(this.#il,{rotation:s})),i!==this.#id){e?.(),this.#id=i;let t={div:null,properties:null,ctx:eU.#iC(this.#ii)};for(let e of this.#ig)t.properties=this.#im.get(e),t.div=e,this.#iS(t)}}cancel(){let t=new O("TextLayer task cancelled.");this.#io?.cancel(t).catch(()=>{}),this.#io=null,this.#e9.reject(t)}get textDivs(){return this.#ig}get textContentItemsStr(){return this.#iu}#iE(t){if(this.#it)return;this.#is.ctx??=eU.#iC(this.#ii);let e=this.#ig,i=this.#iu;for(let s of t){if(e.length>1e5){E("Ignoring additional textDivs for performance reasons."),this.#it=!0;return}if(void 0===s.str){if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){let t=this.#tu;this.#tu=document.createElement("span"),this.#tu.classList.add("markedContent"),null!==s.id&&this.#tu.setAttribute("id",`${s.id}`),t.append(this.#tu)}else"endMarkedContent"===s.type&&(this.#tu=this.#tu.parentNode);continue}i.push(s.str),this.#iT(s)}}#iT(t){let e,i;let s=document.createElement("span"),a={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ig.push(s);let r=j.transform(this.#ib,t.transform),n=Math.atan2(r[1],r[0]),o=this.#ic[t.fontName];o.vertical&&(n+=Math.PI/2);let l=this.#ie&&o.fontSubstitution||o.fontFamily;l=eU.fontFamilyMap.get(l)||l;let h=Math.hypot(r[2],r[3]),d=h*eU.#iM(l,this.#ii);0===n?(e=r[4],i=r[5]-d):(e=r[4]+d*Math.sin(n),i=r[5]-d*Math.cos(n));let c="calc(var(--scale-factor)*",u=s.style;this.#tu===this.#il?(u.left=`${(100*e/this.#ir).toFixed(2)}%`,u.top=`${(100*i/this.#ia).toFixed(2)}%`):(u.left=`${c}${e.toFixed(2)}px)`,u.top=`${c}${i.toFixed(2)}px)`),u.fontSize=`${c}${(eU.#i_*h).toFixed(2)}px)`,u.fontFamily=l,a.fontSize=h,s.setAttribute("role","presentation"),s.textContent=t.str,s.dir=t.dir,this.#ie&&(s.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),0!==n&&(a.angle=180/Math.PI*n);let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}if(p&&(a.canvasWidth=o.vertical?t.height:t.width),this.#im.set(s,a),this.#is.div=s,this.#is.properties=a,this.#iS(this.#is),a.hasText&&this.#tu.append(s),a.hasEOL){let t=document.createElement("br");t.setAttribute("role","presentation"),this.#tu.append(t)}}#iS(t){let{div:e,properties:i,ctx:s}=t,{style:a}=e,r="";if(eU.#i_>1&&(r=`scale(${1/eU.#i_})`),0!==i.canvasWidth&&i.hasText){let{fontFamily:t}=a,{canvasWidth:n,fontSize:o}=i;eU.#ik(s,o*this.#id,t);let{width:l}=s.measureText(e.textContent);l>0&&(r=`scaleX(${n*this.#id/l}) ${r}`)}0!==i.angle&&(r=`rotate(${i.angle}deg) ${r}`),r.length>0&&(a.transform=r)}static cleanup(){if(!(this.#iw.size>0)){for(let{canvas:t}of(this.#iA.clear(),this.#iv.values()))t.remove();this.#iv.clear()}}static #iC(t=null){let e=this.#iv.get(t||="");if(!e){let i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#iv.set(t,e),this.#iy.set(e,{size:0,family:""})}return e}static #ik(t,e,i){let s=this.#iy.get(t);(e!==s.size||i!==s.family)&&(t.font=`${e}px ${i}`,s.size=e,s.family=i)}static #ix(){if(null!==this.#i_)return;let t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#i_=t.getBoundingClientRect().height,t.remove()}static #iM(t,e){let i=this.#iA.get(t);if(i)return i;let s=this.#iC(e);s.canvas.width=s.canvas.height=30,this.#ik(s,30,t);let a=s.measureText(""),r=a.fontBoundingBoxAscent,n=Math.abs(a.fontBoundingBoxDescent);if(r){let e=r/(r+n);return this.#iA.set(t,e),s.canvas.width=s.canvas.height=0,e}s.strokeStyle="red",s.clearRect(0,0,30,30),s.strokeText("g",0,0);let o=s.getImageData(0,0,30,30).data;n=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){n=Math.ceil(t/4/30);break}s.clearRect(0,0,30,30),s.strokeText("A",0,30),o=s.getImageData(0,0,30,30).data,r=0;for(let t=0,e=o.length;t0){r=30-Math.floor(t/4/30);break}s.canvas.width=s.canvas.height=0;let l=r?r/(r+n):.8;return this.#iA.set(t,l),l}}class ej{static textContent(t){let e=[],i={items:e,styles:Object.create(null)};return!function t(i){if(!i)return;let s=null,a=i.name;if("#text"===a)s=i.value;else{if(!ej.shouldBuildText(a))return;i?.attributes?.textContent?s=i.attributes.textContent:i.value&&(s=i.value)}if(null!==s&&e.push({str:s}),i.children)for(let e of i.children)t(e)}(t),i}static shouldBuildText(t){return"textarea"!==t&&"input"!==t&&"option"!==t&&"select"!==t}}let e$=o?tV:tP,eG=o?tW:tF,eV=o?tG:tN,eW=o?tq:tH;function eq(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});let e=new eX,{docId:i}=e,s=t.url?function(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(o&&"string"==typeof t)return t}throw Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,r=t.data?function(t){if(o&&void 0!==a&&t instanceof a)throw Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return B(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,n=t.httpHeaders||null,l=!0===t.withCredentials,h=t.password??null,d=t.range instanceof eY?t.range:null,c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536,u=t.worker instanceof e0?t.worker:null,p=t.verbosity,g="string"!=typeof t.docBaseUrl||Z(t.docBaseUrl)?null:t.docBaseUrl,m="string"==typeof t.cMapUrl?t.cMapUrl:null,f=!1!==t.cMapPacked,b=t.CMapReaderFactory||eG,A="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||eW,y=!0!==t.stopAtErrors,_=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,x=!1!==t.isEvalSupported,E="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!o,C="boolean"==typeof t.isChrome?t.isChrome:!z.platform.isFirefox&&"undefined"!=typeof window&&!!window?.chrome,S=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,T="boolean"==typeof t.disableFontFace?t.disableFontFace:o,M=!0===t.fontExtraProperties,k=!0===t.enableXfa,I=t.ownerDocument||globalThis.document,L=!0===t.disableRange,R=!0===t.disableStream,P=!0===t.disableAutoFetch,D=!0===t.pdfBug,F=t.CanvasFactory||e$,O=t.FilterFactory||eV,N=!0===t.enableHWA,H=d?d.length:t.length??NaN,U="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!o&&!T,j="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:b===tF&&v===tH&&m&&A&&ta(m,document.baseURI)&&ta(A,document.baseURI);t.canvasFactory&&tn("`canvasFactory`-instance option, please use `CanvasFactory` instead."),t.filterFactory&&tn("`filterFactory`-instance option, please use `FilterFactory` instead."),Number.isInteger(p)&&(w=p);let $={canvasFactory:new F({ownerDocument:I,enableHWA:N}),filterFactory:new O({docId:i,ownerDocument:I}),cMapReaderFactory:j?null:new b({baseUrl:m,isCompressed:f}),standardFontDataFactory:j?null:new v({baseUrl:A})};if(!u){let t={verbosity:p,port:en.workerPort};e._worker=u=t.port?e0.fromPort(t):new e0(t)}let G={docId:i,apiVersion:"4.8.69",data:r,password:h,disableAutoFetch:P,rangeChunkSize:c,length:H,docBaseUrl:g,enableXfa:k,evaluatorOptions:{maxImageSize:_,disableFontFace:T,ignoreErrors:y,isEvalSupported:x,isOffscreenCanvasSupported:E,isChrome:C,canvasMaxAreaInBytes:S,fontExtraProperties:M,useSystemFonts:U,cMapUrl:j?m:null,standardFontDataUrl:j?A:null}},V={disableFontFace:T,fontExtraProperties:M,ownerDocument:I,pdfBug:D,styleElement:null,loadingParams:{disableAutoFetch:P,enableXfa:k}};return u.promise.then(function(){let t;if(e.destroyed)throw Error("Loading aborted");if(u.destroyed)throw Error("Worker was destroyed");let a=u.messageHandler.sendWithPromise("GetDocRequest",G,r?[r.buffer]:null);if(d)t=new em(d,{disableRange:L,disableStream:R});else if(!r){let e;if(!s)throw Error("getDocument - no `url` parameter provided.");t=new(o?"undefined"!=typeof fetch&&"undefined"!=typeof Response&&"body"in Response.prototype&&ta(s)?eC:eD:ta(s)?eC:ek)({url:s,length:H,httpHeaders:n,withCredentials:l,rangeChunkSize:c,disableRange:L,disableStream:R})}return a.then(s=>{if(e.destroyed)throw Error("Loading aborted");if(u.destroyed)throw Error("Worker was destroyed");let a=new ed(i,s,u.port),r=new e1(a,e,t,V,$);e._transport=r,a.send("Ready",null)})}).catch(e._capability.reject),e}function eK(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class eX{static #ek=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${eX.#ek++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class eY{constructor(t,e,i=!1,s=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=s,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(let i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(let i of this._progressListeners)i(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(let e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){C("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class eQ{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 M(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"}={}){let{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}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 eJ{#iI=null;#iL=!1;constructor(t,e,i,s=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=s?new ts:null,this._pdfBug=s,this.commonObjs=i.commonObjs,this.objs=new e3,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:i=0,offsetY:s=0,dontFlip:a=!1}={}){return new Q({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:a})}getAnnotations({intent:t="display"}={}){let{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return M(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=c.ENABLE,transform:a=null,background:r=null,optionalContentConfigPromise:n=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:h=null,isEditing:u=!1}){this._stats?.time("Overall");let p=this._transport.getRenderingIntent(i,s,h,u),{renderingIntent:g,cacheKey:m}=p;this.#iL=!1,this.#iR(),n||=this._transport.getOptionalContentConfig(g);let f=this._intentStates.get(m);f||(f=Object.create(null),this._intentStates.set(m,f)),f.streamReaderCancelTimeout&&(clearTimeout(f.streamReaderCancelTimeout),f.streamReaderCancelTimeout=null);let b=!!(g&d.PRINT);f.displayReadyCapability||(f.displayReadyCapability=Promise.withResolvers(),f.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(p));let A=t=>{f.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#iL=!0),this.#iP(!b),t?(v.capability.reject(t),this._abortOperatorList({intentState:f,reason:t instanceof Error?t:Error(t)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new e6({callback:A,params:{canvasContext:t,viewport:e,transform:a,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:f.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(f.renderTasks||=new Set).add(v);let y=v.task;return Promise.all([f.displayReadyCapability.promise,n]).then(([t,e])=>{if(this.destroyed){A();return}if(this._stats?.time("Rendering"),!(e.renderingIntent&g))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e}),v.operatorListChanged()}).catch(A),y}getOperatorList({intent:t="display",annotationMode:e=c.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){let a;let r=this._transport.getRenderingIntent(t,e,i,s,!0),n=this._intentStates.get(r.cacheKey);return n||(n=Object.create(null),this._intentStates.set(r.cacheKey,n)),n.opListReadCapability||((a=Object.create(null)).operatorListChanged=function(){n.operatorList.lastChunk&&(n.opListReadCapability.resolve(n.operatorList),n.renderTasks.delete(a))},n.opListReadCapability=Promise.withResolvers(),(n.renderTasks||=new Set).add(a),n.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),n.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>ej.textContent(t));let e=this.streamTextContent(t);return new Promise(function(t,i){let s=e.getReader(),a={items:[],styles:Object.create(null),lang:null};!function e(){s.read().then(function({value:i,done:s}){if(s){t(a);return}a.lang??=i.lang,Object.assign(a.styles,i.styles),a.items.push(...i.items),e()},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let t=[];for(let e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(let i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#iL=!1,this.#iR(),Promise.all(t)}cleanup(t=!1){this.#iL=!0;let e=this.#iP(!1);return t&&e&&(this._stats&&=new ts),e}#iP(t=!1){if(this.#iR(),!this.#iL||this.destroyed)return!1;if(t)return this.#iI=setTimeout(()=>{this.#iI=null,this.#iP(!1)},5e3),!1;for(let{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#iL=!1,!0}#iR(){this.#iI&&(clearTimeout(this.#iI),this.#iI=null)}_startRenderPage(t,e){let i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,s=t.length;i{n.read().then(({value:t,done:e})=>{if(e){o.streamReader=null;return}!this._transport.destroyed&&(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){for(let t of(o.operatorList.lastChunk=!0,o.renderTasks))t.operatorListChanged();this.#iP(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else if(o.opListReadCapability)o.opListReadCapability.reject(t);else throw t}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof J){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new O(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(let[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class eZ{#iD=new Map;#iF=Promise.resolve();postMessage(t,e){let i={data:structuredClone(t,e?{transfer:e}:null)};this.#iF.then(()=>{for(let[t]of this.#iD)t.call(this,i)})}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){let{signal:a}=i;if(a.aborted){E("LoopbackPort - cannot use an `aborted` signal.");return}let r=()=>this.removeEventListener(t,e);s=()=>a.removeEventListener("abort",r),a.addEventListener("abort",r)}this.#iD.set(e,s)}removeEventListener(t,e){let i=this.#iD.get(e);i?.(),this.#iD.delete(e)}terminate(){for(let[,t]of this.#iD)t?.();this.#iD.clear()}}class e0{static #iO=0;static #iN=!1;static #iB;static{o&&(this.#iN=!0,en.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{let i;try{if(!(i=new URL(t)).origin||"null"===i.origin)return!1}catch{return!1}let s=new URL(e,i);return i.origin===s.origin},this._createCDNWrapper=t=>{let e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=w}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(e0.#iB?.has(e))throw Error("Cannot use more than one PDFWorker per port.");(e0.#iB||=new WeakMap).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return o?Promise.all([tj.promise,this._readyCapability.promise]):this._readyCapability.promise}#iH(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new ed("main","worker",t),this._messageHandler.on("ready",function(){}),this.#iH()}_initialize(){if(e0.#iN||e0.#iz){this._setupFakeWorker();return}let{workerSrc:t}=e0;try{e0._isSameOrigin(window.location.href,t)||(t=e0._createCDNWrapper(new URL(t,window.location).href));let e=new Worker(t,{type:"module"}),i=new ed("main","worker",e),s=()=>{a.abort(),i.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(Error("Worker was destroyed")):this._setupFakeWorker()},a=new AbortController;e.addEventListener("error",()=>{this._webWorker||s()},{signal:a.signal}),i.on("test",t=>{if(a.abort(),this.destroyed||!t){s();return}this._messageHandler=i,this._port=e,this._webWorker=e,this.#iH()}),i.on("ready",t=>{if(a.abort(),this.destroyed){s();return}try{r()}catch{this._setupFakeWorker()}});let r=()=>{let t=new Uint8Array;i.send("test",t,[t.buffer])};r();return}catch{x("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){e0.#iN||(E("Setting up fake worker."),e0.#iN=!0),e0._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(Error("Worker was destroyed"));return}let e=new eZ;this._port=e;let i=`fake${e0.#iO++}`,s=new ed(i+"_worker",i,e);t.setup(s,e),this._messageHandler=new ed(i,i+"_worker",e),this.#iH()}).catch(t=>{this._readyCapability.reject(Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),e0.#iB?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){if(!t?.port)throw Error("PDFWorker.fromPort - invalid method signature.");let e=this.#iB?.get(t.port);if(e){if(e._pendingDestroy)throw Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new e0(t)}static get workerSrc(){if(en.workerSrc)return en.workerSrc;throw Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get #iz(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return M(this,"_setupFakeWorkerGlobal",(async()=>this.#iz?this.#iz:(await import(this.workerSrc)).WorkerMessageHandler)())}}class e1{#iU=new Map;#ij=new Map;#i$=new Map;#iG=new Map;#iV=null;constructor(t,e,i,s,a){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new e3,this.fontLoader=new tI({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=a.canvasFactory,this.filterFactory=a.filterFactory,this.cMapReaderFactory=a.cMapReaderFactory,this.standardFontDataFactory=a.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=i,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#iW(t,e=null){let i=this.#iU.get(t);if(i)return i;let s=this.messageHandler.sendWithPromise(t,e);return this.#iU.set(t,s),s}get annotationStorage(){return M(this,"annotationStorage",new tM)}getRenderingIntent(t,e=c.ENABLE,i=null,s=!1,a=!1){let r=d.DISPLAY,n=tT;switch(t){case"any":r=d.ANY;break;case"display":break;case"print":r=d.PRINT;break;default:E(`getRenderingIntent - invalid intent: ${t}`)}let o=r&d.PRINT&&i instanceof tk?i:this.annotationStorage;switch(e){case c.DISABLE:r+=d.ANNOTATIONS_DISABLE;break;case c.ENABLE:break;case c.ENABLE_FORMS:r+=d.ANNOTATIONS_FORMS;break;case c.ENABLE_STORAGE:r+=d.ANNOTATIONS_STORAGE,n=o.serializable;break;default:E(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(r+=d.IS_EDITING),a&&(r+=d.OPLIST);let{ids:l,hash:h}=o.modifiedIds,u=[r,n.hash,h];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:n,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#iV?.reject(Error("Worker was destroyed during onPassword callback"));let t=[];for(let e of this.#ij.values())t.push(e._destroy());this.#ij.clear(),this.#i$.clear(),this.#iG.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#iU.clear(),this.filterFactory.destroy(),eU.cleanup(),this._networkStream?.cancelAllRequests(new O("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{S(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}},e.onPull=()=>{this._fullReader.read().then(function({value:t,done:i}){if(i){e.close();return}S(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t])}).catch(t=>{e.error(t)})},e.onCancel=t=>{this._fullReader.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this._fullReader.headersReady;let{isStreamingSupported:i,isRangeSupported:s,contentLength:a}=this._fullReader;return i&&s||(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}),{isStreamingSupported:i,isRangeSupported:s,contentLength:a}}),t.on("GetRangeReader",(t,e)=>{S(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let i=this._networkStream.getRangeReader(t.begin,t.end);if(!i){e.close();return}e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i){e.close();return}S(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t])}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("GetDoc",({pdfInfo:t})=>{this._numPages=t.numPages,this._htmlForXfa=t.htmlForXfa,delete t.htmlForXfa,e._capability.resolve(new eQ(t,this))}),t.on("DocException",function(t){let i;switch(t.name){case"PasswordException":i=new I(t.message,t.code);break;case"InvalidPDFException":i=new R(t.message);break;case"MissingPDFException":i=new P(t.message);break;case"UnexpectedResponseException":i=new D(t.message,t.status);break;case"UnknownErrorException":i=new L(t.message,t.details);break;default:C("DocException - expected a valid Error.")}e._capability.reject(i)}),t.on("PasswordRequest",t=>{if(this.#iV=Promise.withResolvers(),e.onPassword)try{e.onPassword(t=>{t instanceof Error?this.#iV.reject(t):this.#iV.resolve({password:t})},t.code)}catch(t){this.#iV.reject(t)}else this.#iV.reject(new I(t.message,t.code));return this.#iV.promise}),t.on("DataLoaded",t=>{e.onProgress?.({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{!this.destroyed&&this.#ij.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,s])=>{if(this.destroyed||this.commonObjs.has(e))return null;switch(i){case"Font":let{disableFontFace:a,fontExtraProperties:r,pdfBug:n}=this._params;if("error"in s){let t=s.error;E(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}let o=new tL(s,{disableFontFace:a,inspectFont:n&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null});this.fontLoader.bind(o).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!r&&o.data&&(o.data=null),this.commonObjs.resolve(e,o)});break;case"CopyLocalImage":let{imageRef:l}=s;for(let t of(S(l,"The imageRef must be defined."),this.#ij.values()))for(let[,i]of t.objs)if(i?.ref===l){if(!i.dataLen)return null;return this.commonObjs.resolve(e,structuredClone(i)),i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,s])=>{if(this.destroyed)return;let a=this.#ij.get(e);if(!a.objs.has(t)){if(0===a._intentStates.size){s?.bitmap?.close();return}switch(i){case"Image":a.objs.resolve(t,s),s?.dataLen>1e7&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(t,s);break;default:throw Error(`Got unknown object type ${i}`)}}}),t.on("DocProgress",t=>{!this.destroyed&&e.onProgress?.({loaded:t.loaded,total:t.total})}),t.on("FetchBuiltInCMap",async t=>{if(this.destroyed)throw Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}),t.on("FetchStandardFontData",async t=>{if(this.destroyed)throw Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&E("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(Error("Invalid page request."));let e=t-1,i=this.#i$.get(e);if(i)return i;let s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(i=>{if(this.destroyed)throw Error("Transport destroyed");i.refStr&&this.#iG.set(i.refStr,t);let s=new eJ(e,i,this,this._params.pdfBug);return this.#ij.set(e,s),s});return this.#i$.set(e,s),s}getPageIndex(t){return eK(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#iW("GetFieldObjects")}hasJSActions(){return this.#iW("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(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.#iW("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.#iW("GetOptionalContentConfig").then(e=>new eg(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let t="GetMetadata",e=this.#iU.get(t);if(e)return e;let i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new ec(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#iU.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){for(let t of(await this.messageHandler.sendWithPromise("Cleanup",null),this.#ij.values()))if(!t.cleanup())throw Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#iU.clear(),this.filterFactory.destroy(!0),eU.cleanup()}}cachedPageNumber(t){if(!eK(t))return null;let e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#iG.get(e)??null}}let e2=Symbol("INITIAL_DATA");class e3{#iq=Object.create(null);#iK(t){return this.#iq[t]||={...Promise.withResolvers(),data:e2}}get(t,e=null){if(e){let i=this.#iK(t);return i.promise.then(()=>e(i.data)),null}let i=this.#iq[t];if(!i||i.data===e2)throw Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){let e=this.#iq[t];return!!e&&e.data!==e2}resolve(t,e=null){let i=this.#iK(t);i.data=e,i.resolve()}clear(){for(let t in this.#iq){let{data:e}=this.#iq[t];e?.bitmap?.close()}this.#iq=Object.create(null)}*[Symbol.iterator](){for(let t in this.#iq){let{data:e}=this.#iq[t];e!==e2&&(yield[t,e])}}}class e5{#iX=null;constructor(t){this.#iX=t,this.onContinue=null}get promise(){return this.#iX.capability.promise}cancel(t=0){this.#iX.cancel(null,t)}get separateAnnots(){let{separateAnnots:t}=this.#iX.operatorList;if(!t)return!1;let{annotationCanvasMap:e}=this.#iX;return t.form||t.canvas&&e?.size>0}}class e6{#iY=null;static #iQ=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:a,operatorList:r,pageIndex:n,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=s,this.annotationCanvasMap=a,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=n,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new e5(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(e6.#iQ.has(this._canvas))throw Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");e6.#iQ.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:i,viewport:s,transform:a,background:r}=this.params;this.gfx=new er(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:a,viewport:s,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.#iY&&(window.cancelAnimationFrame(this.#iY),this.#iY=null),e6.#iQ.delete(this._canvas),this.callback(t||new J(`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.#iY=window.requestAnimationFrame(()=>{this.#iY=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(),e6.#iQ.delete(this._canvas),this.callback())))}}let e4="4.8.69",e8="3634dab10";function e7(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function e9(t){return Math.max(0,Math.min(255,255*t))}class it{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=e9(t),t,t]}static G_HTML([t]){let e=e7(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(e9)}static RGB_HTML(t){return`#${t.map(e7).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[e9(1-Math.min(1,t+s)),e9(1-Math.min(1,i+s)),e9(1-Math.min(1,e+s))]}static CMYK_HTML(t){let e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){let s=1-t,a=1-e,r=1-i,n=Math.min(s,a,r);return["CMYK",s,a,r,n]}}class ie{create(t,e,i=!1){if(t<=0||e<=0)throw Error("Invalid SVG dimensions");let s=this._createSVG("svg:svg");return s.setAttribute("version","1.1"),i||(s.setAttribute("width",`${t}px`),s.setAttribute("height",`${e}px`)),s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${t} ${e}`),s}createElement(t){if("string"!=typeof t)throw Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){C("Abstract method `_createSVG` called.")}}class ii extends ie{_createSVG(t){return document.createElementNS(K,t)}}class is{static setupStorage(t,e,i,s,a){let r=s.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==r.value&&(t.textContent=r.value),"print"===a)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===a)break;t.addEventListener("change",t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==r.value&&t.setAttribute("value",r.value),"print"===a)break;t.addEventListener("input",t=>{s.setValue(e,{value:t.target.value})})}break;case"select":if(null!==r.value)for(let e of(t.setAttribute("value",r.value),i.children))e.attributes.value===r.value?e.attributes.selected=!0:e.attributes.hasOwnProperty("selected")&&delete e.attributes.selected;t.addEventListener("input",t=>{let i=t.target.options,a=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:a})})}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:a}){let{attributes:r}=e,n=t instanceof HTMLAnchorElement;for(let[e,i]of("radio"===r.type&&(r.name=`${r.name}-${s}`),Object.entries(r)))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:n&&("href"===e||"newWindow"===e)||t.setAttribute(e,i)}n&&a.addLinkAttributes(t,r.href,r.newWindow),i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){let e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,a=t.intent||"display",r=document.createElement(s.name);s.attributes&&this.setAttributes({html:r,element:s,intent:a,linkService:i});let n="richText"!==a,o=t.div;if(o.append(r),t.viewport){let e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}n&&o.setAttribute("class","xfaLayer xfaFont");let l=[];if(0===s.children.length){if(s.value){let t=document.createTextNode(s.value);r.append(t),n&&ej.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}let h=[[s,-1,r]];for(;h.length>0;){let[t,s,r]=h.at(-1);if(s+1===t.children.length){h.pop();continue}let o=t.children[++h.at(-1)[1]];if(null===o)continue;let{name:d}=o;if("#text"===d){let t=document.createTextNode(o.value);l.push(t),r.append(t);continue}let c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(r.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:a,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){let t=document.createTextNode(o.value);n&&ej.shouldBuildText(d)&&l.push(t),c.append(t)}}for(let t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){let e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}let ia=new WeakSet;function ir(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class io{static create(t){switch(t.data.annotationType){case b.LINK:return new ih(t);case b.TEXT:return new id(t);case b.WIDGET:switch(t.data.fieldType){case"Tx":return new iu(t);case"Btn":if(t.data.radioButton)return new im(t);if(t.data.checkBox)return new ig(t);return new ib(t);case"Ch":return new iA(t);case"Sig":return new ip(t)}return new ic(t);case b.POPUP:return new iv(t);case b.FREETEXT:return new i_(t);case b.LINE:return new iw(t);case b.SQUARE:return new ix(t);case b.CIRCLE:return new iE(t);case b.POLYLINE:return new iC(t);case b.CARET:return new iT(t);case b.INK:return new iM(t);case b.POLYGON:return new iS(t);case b.HIGHLIGHT:return new ik(t);case b.UNDERLINE:return new iI(t);case b.SQUIGGLY:return new iL(t);case b.STRIKEOUT:return new iR(t);case b.STAMP:return new iP(t);case b.FILEATTACHMENT:return new iD(t);default:return new il(t)}}}class il{#iJ=null;#iZ=!1;#i0=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(i)),s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return il._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#iJ||={rect:this.data.rect.slice(0)};let{rect:e}=t;e&&this.#i1(e),this.#i0?.popup.updateEdited(t)}resetEdited(){this.#iJ&&(this.#i1(this.#iJ.rect),this.#i0?.popup.resetEdited(),this.#iJ=null)}#i1(t){let{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:a,pageHeight:r,pageX:n,pageY:o}}}}=this;i?.splice(0,4,...t);let{width:l,height:h}=ir(t);e.left=`${100*(t[0]-n)/a}%`,e.top=`${100*(r-t[3]+o)/r}%`,0===s?(e.width=`${100*l/a}%`,e.height=`${100*h/r}%`):this.setRotation(s)}_createContainer(t){let{data:e,parent:{page:i,viewport:s}}=this,a=document.createElement("section");a.setAttribute("data-annotation-id",e.id),this instanceof ic||(a.tabIndex=1e3);let{style:r}=a;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(a.title=e.alternativeText),e.noRotate&&a.classList.add("norotate"),!e.rect||this instanceof iv){let{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,a),a}let{width:n,height:o}=ir(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;let t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;switch(t>0||i>0?r.borderRadius=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`:this instanceof im&&(r.borderRadius=`calc(${n}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`),e.borderStyle.style){case A.SOLID:r.borderStyle="solid";break;case A.DASHED:r.borderStyle="dashed";break;case A.BEVELED:E("Unimplemented border style: beveled");break;case A.INSET:E("Unimplemented border style: inset");break;case A.UNDERLINE:r.borderBottomStyle="solid"}let s=e.borderColor||null;s?(this.#iZ=!0,r.borderColor=j.makeHexColor(0|s[0],0|s[1],0|s[2])):r.borderWidth=0}let l=j.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=s.rawDims;r.left=`${100*(l[0]-c)/h}%`,r.top=`${100*(l[1]-u)/d}%`;let{rotation:p}=e;return e.hasOwnCanvas||0===p?(r.width=`${100*n/h}%`,r.height=`${100*o/d}%`):this.setRotation(p,a),a}setRotation(t,e=this.container){let i,s;if(!this.data.rect)return;let{pageWidth:a,pageHeight:r}=this.parent.viewport.rawDims,{width:n,height:o}=ir(this.data.rect);t%180==0?(i=100*n/a,s=100*o/r):(i=100*o/a,s=100*n/r),e.style.width=`${i}%`,e.style.height=`${s}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){let t=(t,e,i)=>{let s=i.detail[t],a=s[0],r=s.slice(1);i.target.style[e]=it[`${a}_HTML`](r),this.annotationStorage.setValue(this.data.id,{[e]:it[`${a}_rgb`](r)})};return M(this,"_commonActions",{display:t=>{let{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{let{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{let e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){let i=this._commonActions;for(let s of Object.keys(e.detail)){let a=t[s]||i[s];a?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;let e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;let i=this._commonActions;for(let[s,a]of Object.entries(e)){let r=i[s];r&&(r({detail:{[s]:a},target:t}),delete e[s])}}_createQuadrilaterals(){let t;if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[i,s,a,r]=this.data.rect.map(t=>Math.fround(t));if(8===e.length){let[t,n,o,l]=e.subarray(2,6);if(a===t&&r===n&&i===o&&s===l)return}let{style:n}=this.container;if(this.#iZ){let{borderColor:e,borderWidth:i}=n;n.borderWidth=0,t=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}let o=a-i,l=r-s,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);let c=h.createElement("defs");d.append(c);let u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let s=2,a=e.length;s`)}this.#iZ&&(t.push("')"),n.backgroundImage=t.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){let{data:t}=this,e=this.#i0=new iv({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(){C("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){let i=[];if(this._fieldObjects){let s=this._fieldObjects[t];if(s)for(let{page:t,id:a,exportValues:r}of s){if(-1===t||a===e)continue;let s="string"==typeof r?r:null,n=document.querySelector(`[data-element-id="${a}"]`);if(n&&!ia.has(n)){E(`_getElementsByName - element not allowed: ${a}`);continue}i.push({id:a,exportValue:s,domElement:n})}return i}for(let s of document.getElementsByName(t)){let{exportValue:t}=s,a=s.getAttribute("data-element-id");a!==e&&ia.has(s)&&i.push({id:a,exportValue:t,domElement:s})}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(let e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class ih extends il{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){let{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),s=!0):t.action?(this._bindNamedAction(i,t.action),s=!0):t.attachment?(this.#i2(i,t.attachment,t.attachmentDest),s=!0):t.setOCGState?(this.#i3(i,t.setOCGState),s=!0):t.dest?(this._bindLink(i,t.dest),s=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),s=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),s=!0):this.isTooltipOnly&&!s&&(this._bindLink(i,""),s=!0)),this.container.classList.add("linkAnnotation"),s&&this.container.append(i),this.container}#i5(){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.#i5()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#i5()}#i2(t,e,i=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,i),!1),this.#i5()}#i3(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#i5()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");let i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let s of Object.keys(e.actions)){let a=i.get(s);a&&(t[a]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}}),!1))}t.onclick||(t.onclick=()=>!1),this.#i5()}_bindResetFormAction(t,e){let i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#i5(),!this._fieldObjects){E('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{i?.();let{fields:t,refs:s,include:a}=e,r=[];if(0!==t.length||0!==s.length){let e=new Set(s);for(let i of t)for(let{id:t}of this._fieldObjects[i]||[])e.add(t);for(let t of Object.values(this._fieldObjects))for(let i of t)e.has(i.id)===a&&r.push(i)}else for(let t of Object.values(this._fieldObjects))r.push(...t);let n=this.annotationStorage,o=[];for(let t of r){let{id:e}=t;switch(o.push(e),t.type){case"text":{let i=t.defaultValue||"";n.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{let i=t.defaultValue===t.exportValues;n.setValue(e,{value:i});break}case"combobox":case"listbox":{let i=t.defaultValue||"";n.setValue(e,{value:i});break}default:continue}let i=document.querySelector(`[data-element-id="${e}"]`);if(i){if(!ia.has(i)){E(`_bindResetFormAction - element not allowed: ${e}`);continue}i.dispatchEvent(new Event("resetform"))}}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class id extends il{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class ic extends il{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return z.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,a){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:a(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}a&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:a(t)}})})}_setEventListeners(t,e,i,s){for(let[a,r]of i)("Action"===r||this.data.actions?.[r])&&(("Focus"===r||"Blur"===r)&&(e||={focused:!1}),this._setEventListener(t,e,a,r,s),"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){let e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":j.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){let e;let{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,a=t.style,r=t=>Math.round(10*t)/10;if(this.data.multiLine){let t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),i=Math.round(t/(1.35*s))||1;e=Math.min(s,r(t/i/1.35))}else e=Math.min(s,r(Math.abs(this.data.rect[3]-this.data.rect[1]-2)/1.35));a.fontSize=`calc(${e}px * var(--scale-factor))`,a.color=j.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(a.textAlign=["left","center","right"][this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class iu extends ic{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){let a=this.annotationStorage;for(let r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=i),a.setValue(r.id,{[s]:i})}render(){let t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){let s=t.getValue(e,{value:this.data.fieldValue}),a=s.value||"",r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&a.length>r&&(a=a.slice(0,r));let n=s.formattedValue||this.data.textContent?.join("\n")||null;n&&this.data.comb&&(n=n.replaceAll(/\s+/g,""));let o={userValue:a,formattedValue:n,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?((i=document.createElement("textarea")).textContent=n??a,this.data.doNotScroll&&(i.style.overflowY="hidden")):((i=document.createElement("input")).type="text",i.setAttribute("value",n??a),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),ia.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=1e3,this._setRequired(i,this.data.required),r&&(i.maxLength=r),i.addEventListener("input",s=>{t.setValue(e,{value:s.target.value}),this.setPropertyOnSiblings(i,"value",s.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{let e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let l=t=>{let{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;let{target:e}=t;o.userValue&&(e.value=o.userValue),o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target),this._dispatchEventFromSandbox({value(i){o.userValue=i.detail.value??"",t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){let{formattedValue:s}=i.detail;o.formattedValue=s,null!=s&&i.target!==document.activeElement&&(i.target.value=s),t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{let{charLimit:s}=i.detail,{target:a}=i;if(0===s){a.removeAttribute("maxLength");return}a.setAttribute("maxLength",s);let r=o.userValue;r&&!(r.length<=s)&&(a.value=o.userValue=r=r.slice(0,s),t.setValue(e,{value:r}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:a.selectionStart,selEnd:a.selectionEnd}}))}},i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;let{value:s}=t.target;o.lastCommittedValue!==s&&(o.lastCommittedValue=s,o.userValue=s,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});let s=l;l=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);let{value:i}=t.target;o.userValue=i,o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),s(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;let{data:i,target:s}=t,{value:a,selectionStart:r,selectionEnd:n}=s,l=r,h=n;switch(t.inputType){case"deleteWordBackward":{let t=a.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{let t=a.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===n&&(l-=1);break;case"deleteContentForward":r===n&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(l&&i.addEventListener("blur",l),this.data.comb){let t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else(i=document.createElement("div")).textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class ip extends ic{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class ig extends ic{constructor(t){super(t,{isRenderable:t.renderForms})}render(){let t=this.annotationStorage,e=this.data,i=e.id,s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof s&&(s="Off"!==s,t.setValue(i,{value:s})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let a=document.createElement("input");return ia.add(a),a.setAttribute("data-element-id",i),a.disabled=e.readOnly,this._setRequired(a,this.data.required),a.type="checkbox",a.name=e.fieldName,s&&a.setAttribute("checked",!0),a.setAttribute("exportValue",e.exportValue),a.tabIndex=1e3,a.addEventListener("change",s=>{let{name:a,checked:r}=s.target;for(let s of this._getElementsByName(a,i)){let i=r&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i),t.setValue(s.id,{value:i})}t.setValue(i,{value:r})}),a.addEventListener("resetform",t=>{let i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(a.addEventListener("updatefromsandbox",e=>{this._dispatchEventFromSandbox({value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}},e)}),this._setEventListeners(a,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class im extends ic{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let t=this.annotationStorage,e=this.data,i=e.id,s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s&&(s=s!==e.buttonValue,t.setValue(i,{value:s})),s)for(let s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});let a=document.createElement("input");if(ia.add(a),a.setAttribute("data-element-id",i),a.disabled=e.readOnly,this._setRequired(a,this.data.required),a.type="radio",a.name=e.fieldName,s&&a.setAttribute("checked",!0),a.tabIndex=1e3,a.addEventListener("change",e=>{let{name:s,checked:a}=e.target;for(let e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:a})}),a.addEventListener("resetform",t=>{let i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){let s=e.buttonValue;a.addEventListener("updatefromsandbox",e=>{this._dispatchEventFromSandbox({value:e=>{let a=s===e.detail.value;for(let s of this._getElementsByName(e.target.name)){let e=a&&s.id===i;s.domElement&&(s.domElement.checked=e),t.setValue(s.id,{value:e})}}},e)}),this._setEventListeners(a,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class ib extends ih{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){let t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");let e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}}class iA extends ic{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");ia.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=1e3;let a=this.data.combo&&this.data.options.length>0;for(let t of(!this.data.combo&&(s.size=this.data.options.length,this.data.multiSelect&&(s.multiple=!0)),s.addEventListener("resetform",t=>{let e=this.data.defaultFieldValue;for(let t of s.options)t.selected=t.value===e}),this.data.options)){let e=document.createElement("option");e.textContent=t.displayValue,e.value=t.exportValue,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),a=!1),s.append(e)}let r=null;if(a){let t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),s.prepend(t),r=()=>{t.remove(),s.removeEventListener("input",r),r=null},s.addEventListener("input",r)}let n=t=>{let e=t?"value":"textContent",{options:i,multiple:a}=s;return a?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]},o=n(!1),l=t=>{let e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(s.addEventListener("updatefromsandbox",i=>{this._dispatchEventFromSandbox({value(i){r?.();let a=i.detail.value,l=new Set(Array.isArray(a)?a:[a]);for(let t of s.options)t.selected=l.has(t.value);t.setValue(e,{value:n(!0)}),o=n(!1)},multipleSelection(t){s.multiple=!0},remove(i){let a=s.options,r=i.detail.remove;a[r].selected=!1,s.remove(r),a.length>0&&-1===Array.prototype.findIndex.call(a,t=>t.selected)&&(a[0].selected=!0),t.setValue(e,{value:n(!0),items:l(i)}),o=n(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]}),o=n(!1)},insert(i){let{index:a,displayValue:r,exportValue:h}=i.detail.insert,d=s.children[a],c=document.createElement("option");c.textContent=r,c.value=h,d?d.before(c):s.append(c),t.setValue(e,{value:n(!0),items:l(i)}),o=n(!1)},items(i){let{items:a}=i.detail;for(;0!==s.length;)s.remove(0);for(let t of a){let{displayValue:e,exportValue:i}=t,a=document.createElement("option");a.textContent=e,a.value=i,s.append(a)}s.options.length>0&&(s.options[0].selected=!0),t.setValue(e,{value:n(!0),items:l(i)}),o=n(!1)},indices(i){let s=new Set(i.detail.indices);for(let t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:n(!0)}),o=n(!1)},editable(t){t.target.disabled=!t.detail.editable}},i)}),s.addEventListener("input",i=>{let s=n(!0),a=n(!1);t.setValue(e,{value:s}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:a,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)):s.addEventListener("input",function(i){t.setValue(e,{value:n(!0)})}),this.data.combo&&this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class iv extends il{constructor(t){let{data:e,elements:i}=t;super(t,{isRenderable:il._hasPopupData(e)}),this.elements=i,this.popup=null}render(){this.container.classList.add("popupAnnotation");let t=this.popup=new iy({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(let i of this.elements)i.popup=t,i.container.ariaHasPopup="dialog",e.push(i.data.id),i.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(t=>`${W}${t}`).join(",")),this.container}}class iy{#i6=this.#i4.bind(this);#i8=this.#i7.bind(this);#i9=this.#st.bind(this);#se=this.#si.bind(this);#ss=null;#tu=null;#sa=null;#sr=null;#sn=null;#so=null;#sl=null;#sh=!1;#sd=null;#S=null;#sc=null;#su=null;#sp=null;#iJ=null;#sg=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:a,contentsObj:r,richText:n,parent:o,rect:l,parentRect:h,open:d}){for(let d of(this.#tu=t,this.#sp=s,this.#sa=r,this.#su=n,this.#so=o,this.#ss=e,this.#sc=l,this.#sl=h,this.#sn=i,this.#sr=to.toDateObject(a),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),this.trigger))d.addEventListener("click",this.#se),d.addEventListener("mouseenter",this.#i9),d.addEventListener("mouseleave",this.#i8),d.classList.add("popupTriggerArea");for(let t of i)t.container?.addEventListener("keydown",this.#i6);this.#tu.hidden=!0,d&&this.#si()}render(){if(this.#sd)return;let t=this.#sd=document.createElement("div");if(t.className="popup",this.#ss){let e=t.style.outlineColor=j.makeHexColor(...this.#ss);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`:t.style.backgroundColor=j.makeHexColor(...this.#ss.map(t=>Math.floor(.7*(255-t)+t)))}let e=document.createElement("span");e.className="header";let i=document.createElement("h1");if(e.append(i),{dir:i.dir,str:i.textContent}=this.#sp,t.append(e),this.#sr){let t=document.createElement("span");t.classList.add("popupDate"),t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#sr.valueOf()})),e.append(t)}let s=this.#sm;if(s)is.render({xfaHtml:s,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{let e=this._formatContents(this.#sa);t.append(e)}this.#tu.append(t)}get #sm(){let t=this.#su,e=this.#sa;return t?.str&&(!e?.str||e.str===t.str)&&this.#su.html||null}get #sf(){return this.#sm?.attributes?.style?.fontSize||0}get #sb(){return this.#sm?.attributes?.style?.color||null}#sA(t){let e=[],i={style:{color:this.#sb,fontSize:this.#sf?`calc(${this.#sf}px * var(--scale-factor))`:""}};for(let s of t.split("\n"))e.push({name:"span",value:s,attributes:i});return{str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}}}_formatContents({str:t,dir:e}){let i=document.createElement("p");i.classList.add("popupContent"),i.dir=e;let s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#sS()}),!i.popupRef&&this.hasPopupData?this._createPopup():t.classList.add("popupTriggerArea"),e.append(t),e}getElementsToTriggerPopup(){return this.#sC}addHighlightArea(){this.container.classList.add("highlightArea")}#sS(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class iF{#sT=null;#sM=null;#sk=new Map;#sI=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:a,viewport:r,structTreeLayer:n}){this.div=t,this.#sT=e,this.#sM=i,this.#sI=n||null,this.page=a,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#sk.size>0}async #sL(t,e){let i=t.firstChild||t,s=i.id=`${W}${e}`,a=await this.#sI?.getAriaAttributes(s);if(a)for(let[t,e]of a)i.setAttribute(t,e);this.div.append(t),this.#sT?.moveElementInDOM(this.div,t,i,!1)}async render(t){let{annotations:e}=t,i=this.div;tu(i,this.viewport);let s=new Map,a={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new ii,annotationStorage:t.annotationStorage||new tM,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(let t of e){if(t.noHTML)continue;let e=t.annotationType===b.POPUP;if(e){let e=s.get(t.id);if(!e)continue;a.elements=e}else{let{width:e,height:i}=ir(t.rect);if(e<=0||i<=0)continue}a.data=t;let i=io.create(a);if(!i.isRenderable)continue;if(!e&&t.popupRef){let e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}let r=i.render();t.hidden&&(r.style.visibility="hidden"),await this.#sL(r,t.id),i._isEditable&&(this.#sk.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}this.#sR()}update({viewport:t}){let e=this.div;this.viewport=t,tu(e,{rotation:t.rotation}),this.#sR(),e.hidden=!1}#sR(){if(!this.#sM)return;let t=this.div;for(let[e,i]of this.#sM){let s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";let{firstChild:a}=s;a?"CANVAS"===a.nodeName?a.replaceWith(i):a.classList.contains("annotationContent")?a.after(i):a.before(i):s.append(i)}this.#sM.clear()}getEditableAnnotations(){return Array.from(this.#sk.values())}getEditableAnnotation(t){return this.#sk.get(t)}}let iO=/\r\n?|\n/g;class iN extends tE{#ss;#sP="";#sD=`${this.id}-editor`;#sF=null;#sf;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=iN.prototype,e=t=>t.isEmpty(),i=tw.TRANSLATE_SMALL,s=tw.TRANSLATE_BIG;return M(this,"_keyboardManager",new ty([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}]]))}static _type="freetext";static _editorType=u.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#ss=t.color||iN._defaultColor||tE._defaultLineColor,this.#sf=t.fontSize||iN._defaultFontSize}static initialize(t,e){tE.initialize(t,e);let i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case p.FREETEXT_SIZE:iN._defaultFontSize=e;break;case p.FREETEXT_COLOR:iN._defaultColor=e}}updateParams(t,e){switch(t){case p.FREETEXT_SIZE:this.#sO(e);break;case p.FREETEXT_COLOR:this.#sN(e)}}static get defaultPropertiesToUpdate(){return[[p.FREETEXT_SIZE,iN._defaultFontSize],[p.FREETEXT_COLOR,iN._defaultColor||tE._defaultLineColor]]}get propertiesToUpdate(){return[[p.FREETEXT_SIZE,this.#sf],[p.FREETEXT_COLOR,this.#ss]]}#sO(t){let e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`,this.translate(0,-(t-this.#sf)*this.parentScale),this.#sf=t,this.#sB()},i=this.#sf;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#sN(t){let e=t=>{this.#ss=this.editorDiv.style.color=t},i=this.#ss;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){let t=this.parentScale;return[-iN._internalPadding*t,-(iN._internalPadding+this.#sf)*t]}rebuild(){if(this.parent)super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(u.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#sF=new AbortController;let t=this._uiManager.combinedSignal(this.#sF);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.#sD),this._isDraggable=!0,this.#sF?.abort(),this.#sF=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(){!this.width&&(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#sH(){let t=[];this.editorDiv.normalize();let e=null;for(let i of this.editorDiv.childNodes)(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName)&&(t.push(iN.#sz(i)),e=i);return t.join("\n")}#sB(){let t;let[e,i]=this.parentDimensions;if(this.isAttachedToDOM)t=this.div.getBoundingClientRect();else{let{currentLayer:e,div:i}=this,s=i.style.display,a=i.classList.contains("hidden");i.classList.remove("hidden"),i.style.display="hidden",e.div.append(this.div),t=i.getBoundingClientRect(),i.remove(),i.style.display=s,i.classList.toggle("hidden",a)}this.rotation%180==this.parentRotation%180?(this.width=t.width/e,this.height=t.height/i):(this.width=t.height/e,this.height=t.width/i),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let t=this.#sP,e=this.#sP=this.#sH().trimEnd();if(t===e)return;let i=t=>{if(this.#sP=t,!t){this.remove();return}this.#sU(),this._uiManager.rebuild(this),this.#sB()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#sB()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){iN._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(){let t,e;if(this.div)return this.div;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#sD),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#sf}px * var(--scale-factor))`,i.color=this.#ss,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),tf(this,this.div,["dblclick","keydown"]),this.width){let[i,s]=this.parentDimensions;if(this.annotationElementId){let a,r;let{position:n}=this._initialData,[o,l]=this.getInitialTranslation();[o,l]=this.pageTranslationToScreen(o,l);let[h,d]=this.pageDimensions,[c,u]=this.pageTranslation;switch(this.rotation){case 0:a=t+(n[0]-c)/h,r=e+this.height-(n[1]-u)/d;break;case 90:a=t+(n[0]-c)/h,r=e-(n[1]-u)/d,[o,l]=[l,-o];break;case 180:a=t-this.width+(n[0]-c)/h,r=e-(n[1]-u)/d,[o,l]=[-o,-l];break;case 270:a=t+(n[0]-c-this.height*d)/h,r=e+(n[1]-u-this.width*h)/d,[o,l]=[-l,o]}this.setAt(a*i,r*s,o,l)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#sU(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static #sz(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(iO,"")}editorDivPaste(t){let e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();let s=iN.#sj(e.getData("text")||"").replaceAll(iO,"\n");if(!s)return;let a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();let r=a.getRangeAt(0);if(!s.includes("\n")){r.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),a.collapseToStart();return}let{startContainer:n,startOffset:o}=r,l=[],h=[];if(n.nodeType===Node.TEXT_NODE){let t=n.parentElement;if(h.push(n.nodeValue.slice(o).replaceAll(iO,"")),t!==this.editorDiv){let e=l;for(let i of this.editorDiv.childNodes){if(i===t){e=h;continue}e.push(iN.#sz(i))}}l.push(n.nodeValue.slice(0,o).replaceAll(iO,""))}else if(n===this.editorDiv){let t=l,e=0;for(let i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(iN.#sz(i))}this.#sP=`${l.join("\n")}${s}${h.join("\n")}`,this.#sU();let d=new Range,c=l.reduce((t,e)=>t+e.length,0);for(let{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){let e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}a.removeAllRanges(),a.addRange(d)}#sU(){if(this.editorDiv.replaceChildren(),this.#sP)for(let t of this.#sP.split("\n")){let e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#s$(){return this.#sP.replaceAll("\xa0"," ")}static #sj(t){return t.replaceAll(" ","\xa0")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof i_){let{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:a,rotation:r,id:n,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:d}}}=t;if(!l||0===l.length)return null;s=t={annotationType:u.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:d-1,rect:a.slice(0),rotation:r,id:n,deleted:!1,popupRef:o}}let a=await super.deserialize(t,e,i);return a.#sf=t.fontSize,a.#ss=j.makeHexColor(...t.color),a.#sP=iN.#sj(t.value),a.annotationElementId=t.id||null,a._initialData=s,a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let e=iN._internalPadding*this.parentScale,i=this.getRect(e,e),s=tE._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#ss),a={annotationType:u.FREETEXT,color:s,fontSize:this.#sf,value:this.#s$(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?a:this.annotationElementId&&!this.#sG(a)?null:(a.id=this.annotationElementId,a)}#sG(t){let{value:e,fontSize:i,color:s,pageIndex:a}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==s[e])||t.pageIndex!==a}renderAnnotationElement(t){let e=super.renderAnnotationElement(t);if(this.deleted)return e;let{style:i}=e;for(let t of(i.fontSize=`calc(${this.#sf}px * var(--scale-factor))`,i.color=this.#ss,e.replaceChildren(),this.#sP.split("\n"))){let i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}let s=iN._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(s,s),popupContent:this.#sP}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class iB{toSVGPath(){C("Abstract method `toSVGPath` must be implemented.")}get box(){C("Abstract getter `box` must be implemented.")}serialize(t,e){C("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){C("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){C("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}class iH{#sV;#sW=[];#sq;#sK;#sX=[];#sY=new Float64Array(18);#sQ;#sJ;#sZ;#s0;#s1;#s2;#s3=[];static #s5=8;static #s6=2;static #s4=iH.#s5+iH.#s6;constructor({x:t,y:e},i,s,a,r,n=0){this.#sV=i,this.#s2=a*s,this.#sK=r,this.#sY.set([NaN,NaN,NaN,NaN,t,e],6),this.#sq=n,this.#s0=iH.#s5*s,this.#sZ=iH.#s4*s,this.#s1=s,this.#s3.push(t,e)}isEmpty(){return isNaN(this.#sY[8])}#s8(){let t=this.#sY.subarray(4,6),e=this.#sY.subarray(16,18),[i,s,a,r]=this.#sV;return[(this.#sQ+(t[0]-e[0])/2-i)/a,(this.#sJ+(t[1]-e[1])/2-s)/r,(this.#sQ+(e[0]-t[0])/2-i)/a,(this.#sJ+(e[1]-t[1])/2-s)/r]}add({x:t,y:e}){this.#sQ=t,this.#sJ=e;let[i,s,a,r]=this.#sV,[n,o,l,h]=this.#sY.subarray(8,12),d=t-l,c=e-h,u=Math.hypot(d,c);if(u=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#at(i),i.join(" ")}#s7(){let[t,e,i,s]=this.#sV,[a,r,n,o]=this.#s8();return`M${(this.#sY[2]-t)/i} ${(this.#sY[3]-e)/s} L${(this.#sY[4]-t)/i} ${(this.#sY[5]-e)/s} L${a} ${r} L${n} ${o} L${(this.#sY[16]-t)/i} ${(this.#sY[17]-e)/s} L${(this.#sY[14]-t)/i} ${(this.#sY[15]-e)/s} Z`}#at(t){let e=this.#sW;t.push(`L${e[4]} ${e[5]} Z`)}#s9(t){let[e,i,s,a]=this.#sV,r=this.#sY.subarray(4,6),n=this.#sY.subarray(16,18),[o,l,h,d]=this.#s8();t.push(`L${(r[0]-e)/s} ${(r[1]-i)/a} L${o} ${l} L${h} ${d} L${(n[0]-e)/s} ${(n[1]-i)/a}`)}newFreeDrawOutline(t,e,i,s,a,r){return new iz(t,e,i,s,a,r)}getOutlines(){let t=this.#sX,e=this.#sW,i=this.#sY,[s,a,r,n]=this.#sV,o=new Float64Array((this.#s3?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2){if(isNaN(e[t+i])){l[h]=l[h+1]=NaN,h+=2;continue}l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2}return this.#as(l,h),this.newFreeDrawOutline(l,o,this.#sV,this.#s1,this.#sq,this.#sK)}#ae(t){let e=this.#sY,[i,s,a,r]=this.#sV,[n,o,l,h]=this.#s8(),d=new Float64Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-i)/a,(e[3]-s)/r,NaN,NaN,NaN,NaN,(e[4]-i)/a,(e[5]-s)/r,NaN,NaN,NaN,NaN,n,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/a,(e[17]-s)/r,NaN,NaN,NaN,NaN,(e[14]-i)/a,(e[15]-s)/r],0),this.newFreeDrawOutline(d,t,this.#sV,this.#s1,this.#sq,this.#sK)}#as(t,e){let i=this.#sW;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+=6}#ai(t,e){let i=this.#sY.subarray(4,6),s=this.#sY.subarray(16,18),[a,r,n,o]=this.#sV,[l,h,d,c]=this.#s8();return t.set([NaN,NaN,NaN,NaN,(i[0]-a)/n,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(s[0]-a)/n,(s[1]-r)/o],e),e+=24}}class iz extends iB{#sV;#aa=null;#sq;#sK;#s3;#s1;#ar;constructor(t,e,i,s,a,r){super(),this.#ar=t,this.#s3=e,this.#sV=i,this.#s1=s,this.#sq=a,this.#sK=r,this.#an(r);let{x:n,y:o,width:l,height:h}=this.#aa;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]);let t=[];for(let e of this.#ah)e[3]?(t.push(...this.#ac(e)),this.#au(e)):(this.#ap(e),t.push(...this.#ac(e)));return this.#ag(t)}#ag(t){let e;let i=[],s=new Set;for(let e of t){let[t,s,a]=e;i.push([t,s,e],[t,a,e])}i.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,e=i.length;t0;){let t=s.values().next().value,[i,r,n,o,l]=t;s.delete(t);let h=i,d=r;for(e=[i,n],a.push(e);;){let t;if(s.has(o))t=o;else if(s.has(l))t=l;else break;s.delete(t),[i,r,n,o,l]=t,h!==i&&(e.push(h,d,i,d===r?r:n),h=i),d=d===r?n:r}e.push(h,d)}return new ij(a,this.#sV)}#am(t){let e=this.#ad,i=0,s=e.length-1;for(;i<=s;){let a=i+s>>1,r=e[a][0];if(r===t)return a;r=0;s--){let[i,a]=this.#ad[s];if(i!==t)break;if(i===t&&a===e){this.#ad.splice(s,1);return}}}#ac(t){let[e,i,s]=t,a=[[e,i,s]],r=this.#am(s);for(let t=0;t=i){if(o>s)a[t][1]=s;else{if(1===r)return[];a.splice(t,1),t--,r--}continue}a[t][2]=i,o>s&&a.push([e,s,o])}}}return a}}class ij extends iB{#sV;#af;constructor(t,e){super(),this.#af=t,this.#sV=e}toSVGPath(){let t=[];for(let e of this.#af){let[i,s]=e;t.push(`M${i} ${s}`);for(let a=2;a-1?(this.#az=!0,this.#aW(t),this.#aq()):this.#aP&&(this.#aL=t.anchorNode,this.#aR=t.anchorOffset,this.#aO=t.focusNode,this.#aN=t.focusOffset,this.#aK(),this.#aq(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#az?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#s2,methodOfCreation:this.#aV}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#aK(){let t=new iU(this.#aP,.001);this.#aH=t.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#aH.box;let e=new iU(this.#aP,.0025,.001,"ltr"===this._uiManager.direction);this.#aF=e.getOutlines();let{lastPoint:i}=this.#aF.box;this.#aU=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#aW({highlightOutlines:t,highlightId:e,clipPathId:i}){if(this.#aH=t,this.#aF=t.getNewOutline(this.#s2/2+1.5,.0025),e>=0)this.#v=e,this.#aD=i,this.parent.drawLayer.finalizeLine(e,t),this.#a$=this.parent.drawLayer.drawOutline(this.#aF);else if(this.parent){let e=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#v,t),this.parent.drawLayer.updateBox(this.#v,iW.#aX(this.#aH.box,(e-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#a$,this.#aF),this.parent.drawLayer.updateBox(this.#a$,iW.#aX(this.#aF.box,e))}let{x:s,y:a,width:r,height:n}=t.box;switch(this.rotation){case 0:this.x=s,this.y=a,this.width=r,this.height=n;break;case 90:{let[t,e]=this.parentDimensions;this.x=a,this.y=1-s,this.width=r*e/t,this.height=n*t/e;break}case 180:this.x=1-s,this.y=1-a,this.width=r,this.height=n;break;case 270:{let[t,e]=this.parentDimensions;this.x=1-a,this.y=s,this.width=r*e/t,this.height=n*t/e}}let{lastPoint:o}=this.#aF.box;this.#aU=[(o[0]-s)/r,(o[1]-a)/n]}static initialize(t,e){tE.initialize(t,e),iW._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case p.HIGHLIGHT_DEFAULT_COLOR:iW._defaultColor=e;break;case p.HIGHLIGHT_THICKNESS:iW._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#aU}updateParams(t,e){switch(t){case p.HIGHLIGHT_COLOR:this.#sN(e);break;case p.HIGHLIGHT_THICKNESS:this.#aY(e)}}static get defaultPropertiesToUpdate(){return[[p.HIGHLIGHT_DEFAULT_COLOR,iW._defaultColor],[p.HIGHLIGHT_THICKNESS,iW._defaultThickness]]}get propertiesToUpdate(){return[[p.HIGHLIGHT_COLOR,this.color||iW._defaultColor],[p.HIGHLIGHT_THICKNESS,this.#s2||iW._defaultThickness],[p.HIGHLIGHT_FREE,this.#az]]}#sN(t){let e=(t,e)=>{this.color=t,this.parent?.drawLayer.changeColor(this.#v,t),this.#a?.updateColor(t),this.#aj=e,this.parent?.drawLayer.changeOpacity(this.#v,e)},i=this.color,s=this.#aj;this.addCommands({cmd:e.bind(this,t,iW._defaultOpacity),undo:e.bind(this,i,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#aY(t){let e=this.#s2,i=t=>{this.#s2=t,this.#aQ(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){let t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#a=new iV({editor:this}),t.addColorPicker(this.#a)),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.#aJ())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#aJ())}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#aZ(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){if(this.parent)super.rebuild(),null!==this.div&&(this.#aq(),this.isAttachedToDOM||this.parent.add(this))}setParent(t){let e=!1;this.parent&&!t?this.#aZ():t&&(this.#aq(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#aQ(t){if(!this.#az)return;this.#aW({highlightOutlines:this.#aH.getNewOutline(t/2)}),this.fixAndSetPosition();let[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#aZ(){null!==this.#v&&this.parent&&(this.parent.drawLayer.remove(this.#v),this.#v=null,this.parent.drawLayer.remove(this.#a$),this.#a$=null)}#aq(t=this.parent){null===this.#v&&({id:this.#v,clipPathId:this.#aD}=t.drawLayer.draw(this.#aH,this.color,this.#aj),this.#a$=t.drawLayer.drawOutline(this.#aF),this.#aB&&(this.#aB.style.clipPath=this.#aD))}static #aX({x:t,y:e,width:i,height:s},a){switch(a){case 90:return{x:1-e-s,y:t,width:s,height:i};case 180:return{x:1-t-i,y:1-e-s,width:i,height:s};case 270:return{x:e,y:1-t-i,width:s,height:i}}return{x:t,y:e,width:i,height:s}}rotate(t){let e;let{drawLayer:i}=this.parent;this.#az?(t=(t-this.rotation+360)%360,e=iW.#aX(this.#aH.box,t)):e=iW.#aX(this,t),i.rotate(this.#v,t),i.rotate(this.#a$,t),i.updateBox(this.#v,e),i.updateBox(this.#a$,iW.#aX(this.#aF.box,t))}render(){if(this.div)return this.div;let t=super.render();this.#aG&&(t.setAttribute("aria-label",this.#aG),t.setAttribute("role","mark")),this.#az?t.classList.add("free"):this.div.addEventListener("keydown",this.#a0.bind(this),{signal:this._uiManager._signal});let e=this.#aB=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#aD;let[i,s]=this.parentDimensions;return this.setDims(this.width*i,this.height*s),tf(this,this.#aB,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent.drawLayer.addClass(this.#a$,"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(this.#a$,"hovered")}#a0(t){iW._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#a1(!0);break;case 1:case 3:this.#a1(!1)}}#a1(t){if(!this.#aL)return;let e=window.getSelection();t?e.setPosition(this.#aL,this.#aR):e.setPosition(this.#aO,this.#aN)}select(){super.select(),this.#a$&&(this.parent?.drawLayer.removeClass(this.#a$,"hovered"),this.parent?.drawLayer.addClass(this.#a$,"selected"))}unselect(){super.unselect(),this.#a$&&(this.parent?.drawLayer.removeClass(this.#a$,"selected"),this.#az||this.#a1(!1))}get _mustFixPosition(){return!this.#az}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#v,t),this.parent.drawLayer.show(this.#a$,t))}#aJ(){return this.#az?this.rotation:0}#a2(){if(this.#az)return null;let[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,a=this.#aP,r=new Float32Array(8*a.length),n=0;for(let{x:o,y:l,width:h,height:d}of a){let a=o*t+i,c=(1-l-d)*e+s;r[n]=r[n+4]=a,r[n+1]=r[n+3]=c,r[n+2]=r[n+6]=a+h*t,r[n+5]=r[n+7]=c+d*e,n+=8}return r}#a3(t){return this.#aH.serialize(t,this.#aJ())}static startHighlighting(t,e,{target:i,x:s,y:a}){let{x:r,y:n,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#a5(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",t=>{t.preventDefault(),t.stopPropagation()},{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",tr,{signal:d}),i.addEventListener("pointermove",this.#a6.bind(this,t),{signal:d}),this._freeHighlight=new i$({x:s,y:a},[r,n,o,l],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static #a6(t,e){this._freeHighlight.add(e)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static #a5(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof ik){let{data:{quadPoints:e,rect:i,rotation:a,id:r,color:n,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:u.HIGHLIGHT,color:Array.from(n),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:a,id:r,deleted:!1,popupRef:l}}else if(t instanceof iM){let{data:{inkLists:e,rect:i,rotation:a,id:r,color:n,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:u.HIGHLIGHT,color:Array.from(n),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:a,id:r,deleted:!1,popupRef:l}}let{color:a,quadPoints:r,inkLists:n,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=j.makeHexColor(...a),l.#aj=o||1,n&&(l.#s2=t.thickness),l.annotationElementId=t.id||null,l._initialData=s;let[h,d]=l.pageDimensions,[c,p]=l.pageTranslation;if(r){let t=l.#aP=[];for(let e=0;et!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class iq extends tE{#a4=0;#a8=0;#a7=null;#a9=new Path2D;#rt=!1;#re=null;#ri=!1;#rs=!1;#ra=null;#rr=null;#rn=0;#ro=0;#rl=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _type="ink";static _editorType=u.INK;constructor(t){super({...t,name:"inkEditor"}),this.color=t.color||null,this.thickness=t.thickness||null,this.opacity=t.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(t,e){tE.initialize(t,e)}static updateDefaultParams(t,e){switch(t){case p.INK_THICKNESS:iq._defaultThickness=e;break;case p.INK_COLOR:iq._defaultColor=e;break;case p.INK_OPACITY:iq._defaultOpacity=e/100}}updateParams(t,e){switch(t){case p.INK_THICKNESS:this.#aY(e);break;case p.INK_COLOR:this.#sN(e);break;case p.INK_OPACITY:this.#rh(e)}}static get defaultPropertiesToUpdate(){return[[p.INK_THICKNESS,iq._defaultThickness],[p.INK_COLOR,iq._defaultColor||tE._defaultLineColor],[p.INK_OPACITY,Math.round(100*iq._defaultOpacity)]]}get propertiesToUpdate(){return[[p.INK_THICKNESS,this.thickness||iq._defaultThickness],[p.INK_COLOR,this.color||iq._defaultColor||tE._defaultLineColor],[p.INK_OPACITY,Math.round(100*(this.opacity??iq._defaultOpacity))]]}#aY(t){let e=t=>{this.thickness=t,this.#rd()},i=this.thickness;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#sN(t){let e=t=>{this.color=t,this.#rc()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#rh(t){let e=t=>{this.opacity=t,this.#rc()};t/=100;let i=this.opacity;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:p.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){if(this.parent)super.rebuild(),null!==this.div&&(this.canvas||(this.#ru(),this.#rp()),this.isAttachedToDOM||(this.parent.add(this),this.#rg()),this.#rd())}remove(){null!==this.canvas&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#a7&&(clearTimeout(this.#a7),this.#a7=null),this.#ra?.disconnect(),this.#ra=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){let[t,e]=this.parentDimensions,i=this.width*t,s=this.height*e;this.setDimensions(i,s)}enableEditMode(){!this.#rt&&null!==this.canvas&&(super.enableEditMode(),this._isDraggable=!1,this.#rm())}disableEditMode(){this.isInEditMode()&&null!==this.canvas&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.#rf())}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#rb(){let{parentRotation:t,parentDimensions:[e,i]}=this;switch(t){case 90:return[0,i,i,e];case 180:return[e,i,e,i];case 270:return[e,0,i,e];default:return[0,0,e,i]}}#rA(){let{ctx:t,color:e,opacity:i,thickness:s,parentScale:a,scaleFactor:r}=this;t.lineWidth=s*a/r,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${e}${Math.round(Math.min(255,Math.max(1,255*i))).toString(16).padStart(2,"0")}`}#rv(t,e){this.canvas.addEventListener("contextmenu",tr,{signal:this._uiManager._signal}),this.#rf(),this.#re=new AbortController;let i=this._uiManager.combinedSignal(this.#re);this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:i}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:i}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:i}),this.isEditing=!0,this.#rs||(this.#rs=!0,this.#rg(),this.thickness||=iq._defaultThickness,this.color||=iq._defaultColor||tE._defaultLineColor,this.opacity??=iq._defaultOpacity),this.currentPath.push([t,e]),this.#ri=!1,this.#rA(),this.#rl=()=>{this.#ry(),this.#rl&&window.requestAnimationFrame(this.#rl)},window.requestAnimationFrame(this.#rl)}#r_(t,e){let[i,s]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===i&&e===s)return;let a=this.currentPath,r=this.#a9;if(a.push([t,e]),this.#ri=!0,a.length<=2){r.moveTo(...a[0]),r.lineTo(t,e);return}3===a.length&&(this.#a9=r=new Path2D,r.moveTo(...a[0])),this.#rw(r,...a.at(-3),...a.at(-2),t,e)}#rx(){if(0===this.currentPath.length)return;let t=this.currentPath.at(-1);this.#a9.lineTo(...t)}#rE(t,e){let i;if(this.#rl=null,t=Math.min(Math.max(t,0),this.canvas.width),e=Math.min(Math.max(e,0),this.canvas.height),this.#r_(t,e),this.#rx(),1!==this.currentPath.length)i=this.#rC();else{let s=[t,e];i=[[s,s.slice(),s.slice(),s]]}let s=this.#a9,a=this.currentPath;this.currentPath=[],this.#a9=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(a),this.paths.push(i),this.bezierPath2D.push(s),this._uiManager.rebuild(this)},undo:()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),0===this.paths.length?this.remove():(this.canvas||(this.#ru(),this.#rp()),this.#rd())},mustExec:!0})}#ry(){if(!this.#ri)return;this.#ri=!1,this.thickness,this.parentScale;let t=this.currentPath.slice(-3);t.map(t=>t[0]),t.map(t=>t[1]);let{ctx:e}=this;for(let t of(e.save(),e.clearRect(0,0,this.canvas.width,this.canvas.height),this.bezierPath2D))e.stroke(t);e.stroke(this.#a9),e.restore()}#rw(t,e,i,s,a,r,n){let o=(e+s)/2,l=(i+a)/2,h=(s+r)/2,d=(a+n)/2;t.bezierCurveTo(o+2*(s-o)/3,l+2*(a-l)/3,h+2*(s-h)/3,d+2*(a-d)/3,h,d)}#rC(){let t;let e=this.currentPath;if(e.length<=2)return[[e[0],e[0],e.at(-1),e.at(-1)]];let i=[],[s,a]=e[0];for(t=1;t{this.#a7=null,this.canvas.removeEventListener("contextmenu",tr)},10),this.#rE(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#ru(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#rp(){this.#ra=new ResizeObserver(t=>{let e=t[0].contentRect;e.width&&e.height&&this.setDimensions(e.width,e.height)}),this.#ra.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#ra?.disconnect(),this.#ra=null},{once:!0})}get isResizable(){return!this.isEmpty()&&this.#rt}render(){let t,e;if(this.div)return this.div;this.width&&(t=this.x,e=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[i,s,a,r]=this.#rb();if(this.setAt(i,s,0,0),this.setDims(a,r),this.#ru(),this.width){let[i,s]=this.parentDimensions;this.setAspectRatio(this.width*i,this.height*s),this.setAt(t*i,e*s,this.width*i,this.height*s),this.#rs=!0,this.#rg(),this.setDims(this.width*i,this.height*s),this.#rc(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#rp(),this.div}#rg(){if(!this.#rs)return;let[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*e),this.#rS()}setDimensions(t,e){let i=Math.round(t),s=Math.round(e);if(this.#rn===i&&this.#ro===s)return;this.#rn=i,this.#ro=s,this.canvas.style.visibility="hidden";let[a,r]=this.parentDimensions;this.width=t/a,this.height=e/r,this.fixAndSetPosition(),this.#rt&&this.#rM(t,e),this.#rg(),this.#rc(),this.canvas.style.visibility="visible",this.fixDims()}#rM(t,e){let i=this.#rk(),s=(t-i)/this.#a8,a=(e-i)/this.#a4;this.scaleFactor=Math.min(s,a)}#rS(){let t=this.#rk()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static #rI(t){let e=new Path2D;for(let i=0,s=t.length;i`image/${t}`))}static get supportedTypesStr(){return M(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){let e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#rV(t,e=!1){if(!t){this.remove();return}this.#rF=t.bitmap,e||(this.#rO=t.id,this.#r$=t.isSvg),t.file&&(this.#rz=t.file.name),this.#ru()}#rW(){if(this.#rN=null,this._uiManager.enableWaiting(!1),this.#rU){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#rF){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#rF){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;let{mlManager:i}=this._uiManager;if(!i)throw Error("No ML.");if(!await i.isEnabledFor("altText"))throw Error("ML isn't enabled for alt text.");let{data:s,width:a,height:r}=t||this.copyCanvas(null,null,!0).imageData,n=await i.guess({name:"altText",request:{data:s,width:a,height:r,channels:s.length/(a*r)}});if(!n)throw Error("No response from the AI service.");if(n.error)throw Error("Error from the AI service.");if(n.cancel)return null;if(!n.output)throw Error("No valid response from the AI service.");let o=n.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#rq(){if(this.#rO){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#rO).then(t=>this.#rV(t,!0)).finally(()=>this.#rW());return}if(this.#rB){let t=this.#rB;this.#rB=null,this._uiManager.enableWaiting(!0),this.#rN=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#rV(t)).finally(()=>this.#rW());return}if(this.#rH){let t=this.#rH;this.#rH=null,this._uiManager.enableWaiting(!0),this.#rN=this._uiManager.imageManager.getFromFile(t).then(t=>this.#rV(t)).finally(()=>this.#rW());return}let t=document.createElement("input");t.type="file",t.accept=iK.supportedTypesStr;let e=this._uiManager._signal;this.#rN=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);let e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#rV(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#rW()),t.click()}remove(){this.#rO&&(this.#rF=null,this._uiManager.imageManager.deleteId(this.#rO),this.#rU?.remove(),this.#rU=null,this.#ra?.disconnect(),this.#ra=null,this.#rj&&(clearTimeout(this.#rj),this.#rj=null)),super.remove()}rebuild(){if(!this.parent){this.#rO&&this.#rq();return}super.rebuild(),null!==this.div&&(this.#rO&&null===this.#rU&&this.#rq(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#rN||this.#rF||this.#rB||this.#rH||this.#rO)}get isResizable(){return!0}render(){let t,e;if(this.div)return this.div;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#rF?this.#ru():this.#rq(),this.width&&!this.annotationElementId){let[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#ru(){let{div:t}=this,{width:e,height:i}=this.#rF,[s,a]=this.pageDimensions;if(this.width)e=this.width*s,i=this.height*a;else if(e>.75*s||i>.75*a){let t=Math.min(.75*s/e,.75*a/i);e*=t,i*=t}let[r,n]=this.parentDimensions;this.setDims(e*r/s,i*n/a),this._uiManager.enableWaiting(!1);let o=this.#rU=document.createElement("canvas");o.setAttribute("role","img"),this.addContainer(o),this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#rK(e,i),this.#rp(),this.#rG||(this.parent.addUndoableEditor(this),this.#rG=!0),this._reportTelemetry({action:"inserted_image"}),this.#rz&&o.setAttribute("aria-label",this.#rz)}copyCanvas(t,e,i=!1){t||(t=224);let{width:s,height:a}=this.#rF,r=new tp,n=this.#rF,o=s,l=a,h=null;if(e){if(s>e||a>e){let t=Math.min(e/s,e/a);o=Math.floor(s*t),l=Math.floor(a*t)}let t=(h=document.createElement("canvas")).width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#r$||(n=this.#rX(t,i));let d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(c="#8f8f9d",u="#42414d");let p=15*r.sx,g=15*r.sy,m=new OffscreenCanvas(2*p,2*g),f=m.getContext("2d");f.fillStyle=c,f.fillRect(0,0,2*p,2*g),f.fillStyle=u,f.fillRect(0,0,p,g),f.fillRect(p,g,p,g),d.fillStyle=d.createPattern(m,"repeat"),d.fillRect(0,0,t,i),d.drawImage(n,0,0,n.width,n.height,0,0,t,i)}let d=null;if(i){let e,i;if(r.symmetric&&n.widtht||a>t){let r=Math.min(t/s,t/a);e=Math.floor(s*r),i=Math.floor(a*r),this.#r$||(n=this.#rX(e,i))}let o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(n,0,0,n.width,n.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#rY(t,e){let[i,s]=this.parentDimensions;this.width=t/i,this.height=e/s,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,null!==this.#rj&&clearTimeout(this.#rj),this.#rj=setTimeout(()=>{this.#rj=null,this.#rK(t,e)},200)}#rX(t,e){let{width:i,height:s}=this.#rF,a=i,r=s,n=this.#rF;for(;a>2*t||r>2*e;){let i=a,s=r;a>2*t&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));let o=new OffscreenCanvas(a,r);o.getContext("2d").drawImage(n,0,0,i,s,0,0,a,r),n=o.transferToImageBitmap()}return n}#rK(t,e){let i=new tp,s=Math.ceil(t*i.sx),a=Math.ceil(e*i.sy),r=this.#rU;if(!r||r.width===s&&r.height===a)return;r.width=s,r.height=a;let n=this.#r$?this.#rF:this.#rX(s,a),o=r.getContext("2d");o.filter=this._uiManager.hcmFilter,o.drawImage(n,0,0,n.width,n.height,0,0,s,a)}getImageForAltText(){return this.#rU}#rQ(t){if(t){if(this.#r$){let t=this._uiManager.imageManager.getSvgUrl(this.#rO);if(t)return t}let t=document.createElement("canvas");return{width:t.width,height:t.height}=this.#rF,t.getContext("2d").drawImage(this.#rF,0,0),t.toDataURL()}if(this.#r$){let[t,e]=this.pageDimensions,i=Math.round(this.width*t*X.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*X.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(i,s);return a.getContext("2d").drawImage(this.#rF,0,0,this.#rF.width,this.#rF.height,0,0,i,s),a.transferToImageBitmap()}return structuredClone(this.#rF)}#rp(){this._uiManager._signal&&(this.#ra=new ResizeObserver(t=>{let e=t[0].contentRect;e.width&&e.height&&this.#rY(e.width,e.height)}),this.#ra.observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{this.#ra?.disconnect(),this.#ra=null},{once:!0}))}static async deserialize(t,e,i){let s=null;if(t instanceof iP){let{data:{rect:a,rotation:r,id:n,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:d}}}=t,c=h.querySelector("canvas"),p=i.imageManager.getFromCanvas(h.id,c);c.remove();let g=(await e._structTree.getAriaAttributes(`${W}${n}`))?.get("aria-label")||"";s=t={annotationType:u.STAMP,bitmapId:p.id,bitmap:p.bitmap,pageIndex:d-1,rect:a.slice(0),rotation:r,id:n,deleted:!1,accessibilityData:{decorative:!1,altText:g},isSvg:!1,structParent:o,popupRef:l}}let a=await super.deserialize(t,e,i),{rect:r,bitmap:n,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:d}=t;l&&i.imageManager.isValidId(l)?(a.#rO=l,n&&(a.#rF=n)):a.#rB=o,a.#r$=h;let[c,p]=a.pageDimensions;return a.width=(r[2]-r[0])/c,a.height=(r[3]-r[1])/p,a.annotationElementId=t.id||null,d&&(a.altTextData=d),a._initialData=s,a.#rG=!!s,a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let i={annotationType:u.STAMP,bitmapId:this.#rO,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#r$,structTreeParentId:this._structTreeParentId};if(t)return i.bitmapUrl=this.#rQ(!0),i.accessibilityData=this.serializeAltText(!0),i;let{decorative:s,altText:a}=this.serializeAltText(!1);if(!s&&a&&(i.accessibilityData={type:"Figure",alt:a}),this.annotationElementId){let t=this.#sG(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,null===e)return i;e.stamps||=new Map;let r=this.#r$?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#rO)){if(this.#r$){let t=e.stamps.get(this.#rO);r>t.area&&(t.area=r,t.serialized.bitmap.close(),t.serialized.bitmap=this.#rQ(!1))}}else e.stamps.set(this.#rO,{area:r,serialized:i}),i.bitmap=this.#rQ(!1);return i}#sG(t){let{rect:e,pageIndex:i,accessibilityData:{altText:s}}=this._initialData,a=t.rect.every((t,i)=>1>Math.abs(t-e[i])),r=t.pageIndex===i,n=(t.accessibilityData?.alt||"")===s;return{isSame:a&&r&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class iX{#sT;#rJ=!1;#rZ=null;#r0=null;#r1=null;#r2=new Map;#r3=!1;#r5=!1;#r6=!1;#r4=null;#r8=null;#m;static _initialized=!1;static #z=new Map([iN,iq,iK,iW].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:a,annotationLayer:r,drawLayer:n,textLayer:o,viewport:l,l10n:h}){let d=[...iX.#z.values()];if(!iX._initialized)for(let e of(iX._initialized=!0,d))e.initialize(h,t);t.registerEditorTypes(d),this.#m=t,this.pageIndex=e,this.div=i,this.#sT=a,this.#rZ=r,this.viewport=l,this.#r4=o,this.drawLayer=n,this._structTree=s,this.#m.addLayer(this)}get isEmpty(){return 0===this.#r2.size}get isInvisible(){return this.isEmpty&&this.#m.getMode()===u.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){switch(this.#r7(),t){case u.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case u.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case u.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:e}=this.div;for(let i of iX.#z.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#r4?.div}addInkEditorIfNeeded(t){if(this.#m.getMode()===u.INK){if(!t){for(let t of this.#r2.values())if(t.isEmpty()){t.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#rZ?.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);let t=new Set;for(let e of this.#r2.values())e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#m.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));if(this.#rZ)for(let e of this.#rZ.getEditableAnnotations()){if(e.hide(),this.#m.isDeletedAnnotationElement(e.data.id)||t.has(e.data.id))continue;let i=await this.deserialize(e);i&&(this.addOrRebuild(i),i.enableEditing())}}disable(){this.#r6=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let t=new Map,e=new Map;for(let i of this.#r2.values())if(i.disableEditing(),i.annotationElementId){if(null!==i.serialize()){t.set(i.annotationElementId,i);continue}e.set(i.annotationElementId,i),this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#rZ)for(let i of this.#rZ.getEditableAnnotations()){let{id:s}=i.data;if(this.#m.isDeletedAnnotationElement(s))continue;let a=e.get(s);if(a){a.resetAnnotationElement(i),a.show(!1),i.show();continue}(a=t.get(s))&&(this.#m.addChangedExistingAnnotation(a),a.renderAnnotationElement(i)&&a.show(!1)),i.show()}this.#r7(),this.isEmpty&&(this.div.hidden=!0);let{classList:i}=this.div;for(let t of iX.#z.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#r6=!1}getEditableAnnotation(t){return this.#rZ?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#m.getActive()!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#r4?.div&&!this.#r8){this.#r8=new AbortController;let t=this.#m.combinedSignal(this.#r8);this.#r4.div.addEventListener("pointerdown",this.#r9.bind(this),{signal:t}),this.#r4.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#r4?.div&&this.#r8&&(this.#r8.abort(),this.#r8=null,this.#r4.div.classList.remove("highlighting"))}#r9(t){this.#m.unselectAll();let{target:e}=t;if(e===this.#r4.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#r4.div.contains(e)){let{isMac:e}=z.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",!0,!0),this.#r4.div.classList.add("free"),this.toggleDrawing(),iW.startHighlighting(this,"ltr"===this.#m.direction,{target:this.#r4.div,x:t.x,y:t.y}),this.#r4.div.addEventListener("pointerup",()=>{this.#r4.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#m._signal}),t.preventDefault()}}enableClick(){if(this.#r0)return;this.#r0=new AbortController;let t=this.#m.combinedSignal(this.#r0);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){this.#r0?.abort(),this.#r0=null}attach(t){this.#r2.set(t.id,t);let{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#r2.delete(t.id),this.#sT?.removePointerInTextLayer(t.contentDiv),!this.#r6&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#m.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#r5||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#m.addDeletedAnnotationElement(t.annotationElementId),tE.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#m.addEditor(t),this.attach(t),!t.isAttachedToDOM){let e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#m.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;let{activeElement:e}=document;t.div.contains(e)&&!this.#r1&&(t._focusEventsAllowed=!1,this.#r1=setTimeout(()=>{this.#r1=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#m._signal}),e.focus())},0)),t._structTreeParentId=this.#sT?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#m.getId()}get #nt(){return iX.#z.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#ne(t){let e=this.#nt;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#nt?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#m.updateToolbar(t),this.#m.updateMode(t);let{offsetX:i,offsetY:s}=this.#ni(),a=this.getNextId(),r=this.#ne({parent:this,id:a,x:i,y:s,uiManager:this.#m,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await iX.#z.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m)||null}createAndAddNewEditor(t,e,i={}){let s=this.getNextId(),a=this.#ne({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...i});return a&&this.add(a),a}#ni(){let{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),a=Math.max(0,t),r=Math.max(0,e),n=Math.min(window.innerWidth,t+i),o=Math.min(window.innerHeight,e+s),l=(a+n)/2-t,h=(r+o)/2-e,[d,c]=this.viewport.rotation%180==0?[l,h]:[h,l];return{offsetX:d,offsetY:c}}addNewEditor(){this.createAndAddNewEditor(this.#ni(),!0)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){let{isMac:e}=z.platform;if(0===t.button&&(!t.ctrlKey||!e)&&t.target===this.div&&this.#r3){if(this.#r3=!1,!this.#rJ){this.#rJ=!0;return}if(this.#m.getMode()===u.STAMP){this.#m.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#m.getMode()===u.HIGHLIGHT&&this.enableTextSelection(),this.#r3){this.#r3=!1;return}let{isMac:e}=z.platform;if(0!==t.button||t.ctrlKey&&e||t.target!==this.div)return;this.#r3=!0;let i=this.#m.getActive();this.#rJ=!i||i.isEmpty()}findNewParent(t,e,i){let s=this.#m.findParent(e,i);return null!==s&&s!==this&&(s.changeParent(t),!0)}destroy(){for(let t of(this.#m.getActive()?.parent===this&&(this.#m.commitOrRemove(),this.#m.setActiveEditor(null)),this.#r1&&(clearTimeout(this.#r1),this.#r1=null),this.#r2.values()))this.#sT?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#r2.clear(),this.#m.removeLayer(this)}#r7(){for(let t of(this.#r5=!0,this.#r2.values()))t.isEmpty()&&t.remove();this.#r5=!1}render({viewport:t}){for(let e of(this.viewport=t,tu(this.div,t),this.#m.getEditors(this.pageIndex)))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#m.commitOrRemove(),this.#r7();let e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,tu(this.div,{rotation:i}),e!==i)for(let t of this.#r2.values())t.rotate(i);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class iY{#so=null;#v=0;#ns=new Map;#na=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#so){this.#so=t;return}if(this.#so!==t){if(this.#ns.size>0)for(let e of this.#ns.values())e.remove(),t.append(e);this.#so=t}}static get _svgFactory(){return M(this,"_svgFactory",new ii)}static #nr(t,{x:e=0,y:i=0,width:s=1,height:a=1}={}){let{style:r}=t;r.top=`${100*i}%`,r.left=`${100*e}%`,r.width=`${100*s}%`,r.height=`${100*a}%`}#nn(t){let e=iY._svgFactory.create(1,1,!0);return this.#so.append(e),e.setAttribute("aria-hidden",!0),iY.#nr(e,t),e}#no(t,e){let i=iY._svgFactory.createElement("clipPath");t.append(i);let s=`clip_${e}`;i.setAttribute("id",s),i.setAttribute("clipPathUnits","objectBoundingBox");let a=iY._svgFactory.createElement("use");return i.append(a),a.setAttribute("href",`#${e}`),a.classList.add("clip"),s}draw(t,e,i,s=!1){let a=this.#v++,r=this.#nn(t.box);r.classList.add(...t.classNamesForDrawing);let n=iY._svgFactory.createElement("defs");r.append(n);let o=iY._svgFactory.createElement("path");n.append(o);let l=`path_p${this.pageIndex}_${a}`;o.setAttribute("id",l),o.setAttribute("d",t.toSVGPath()),s&&this.#na.set(a,o);let h=this.#no(n,l),d=iY._svgFactory.createElement("use");return r.append(d),r.setAttribute("fill",e),r.setAttribute("fill-opacity",i),d.setAttribute("href",`#${l}`),this.#ns.set(a,r),{id:a,clipPathId:`url(#${h})`}}drawOutline(t){let e;let i=this.#v++,s=this.#nn(t.box);s.classList.add(...t.classNamesForOutlining);let a=iY._svgFactory.createElement("defs");s.append(a);let r=iY._svgFactory.createElement("path");a.append(r);let n=`path_p${this.pageIndex}_${i}`;if(r.setAttribute("id",n),r.setAttribute("d",t.toSVGPath()),r.setAttribute("vector-effect","non-scaling-stroke"),t.mustRemoveSelfIntersections){let t=iY._svgFactory.createElement("mask");a.append(t),e=`mask_p${this.pageIndex}_${i}`,t.setAttribute("id",e),t.setAttribute("maskUnits","objectBoundingBox");let s=iY._svgFactory.createElement("rect");t.append(s),s.setAttribute("width","1"),s.setAttribute("height","1"),s.setAttribute("fill","white");let r=iY._svgFactory.createElement("use");t.append(r),r.setAttribute("href",`#${n}`),r.setAttribute("stroke","none"),r.setAttribute("fill","black"),r.setAttribute("fill-rule","nonzero"),r.classList.add("mask")}let o=iY._svgFactory.createElement("use");s.append(o),o.setAttribute("href",`#${n}`),e&&o.setAttribute("mask",`url(#${e})`);let l=o.cloneNode();return s.append(l),o.classList.add("mainOutline"),l.classList.add("secondaryOutline"),this.#ns.set(i,s),i}finalizeLine(t,e){let i=this.#na.get(t);this.#na.delete(t),this.updateBox(t,e.box),i.setAttribute("d",e.toSVGPath())}updateLine(t,e){this.#ns.get(t).firstChild.firstChild.setAttribute("d",e.toSVGPath())}updatePath(t,e){this.#na.get(t).setAttribute("d",e.toSVGPath())}updateBox(t,e){iY.#nr(this.#ns.get(t),e)}show(t,e){this.#ns.get(t).classList.toggle("hidden",!e)}rotate(t,e){this.#ns.get(t).setAttribute("data-main-rotation",e)}changeColor(t,e){this.#ns.get(t).setAttribute("fill",e)}changeOpacity(t,e){this.#ns.get(t).setAttribute("fill-opacity",e)}addClass(t,e){this.#ns.get(t).classList.add(e)}removeClass(t,e){this.#ns.get(t).classList.remove(e)}getSVGRoot(t){return this.#ns.get(t)}remove(t){this.#na.delete(t),null!==this.#so&&(this.#ns.get(t).remove(),this.#ns.delete(t))}destroy(){for(let t of(this.#so=null,this.#ns.values()))t.remove();this.#ns.clear(),this.#na.clear()}}n.AbortException,n.AnnotationEditorLayer,n.AnnotationEditorParamsType,n.AnnotationEditorType,n.AnnotationEditorUIManager;var iQ=n.AnnotationLayer,iJ=n.AnnotationMode;n.ColorPicker,n.DOMSVGFactory,n.DrawLayer,n.FeatureTest;var iZ=n.GlobalWorkerOptions;n.ImageKind,n.InvalidPDFException,n.MissingPDFException,n.OPS,n.OutputScale;var i0=n.PDFDataRangeTransport;n.PDFDateString,n.PDFWorker,n.PasswordResponses,n.PermissionFlag,n.PixelsPerInch,n.RenderingCancelledException;var i1=n.TextLayer;n.UnexpectedResponseException,n.Util,n.VerbosityLevel,n.XfaLayer,n.build,n.createValidAbsoluteUrl,n.fetchData;var i2=n.getDocument;n.getFilenameFromUrl,n.getPdfFilenameFromUrl,n.getXfaPageViewport,n.isDataScheme,n.isPdfFile,n.noContextMenu,n.normalizeUnicode,n.setLayerDimensions,n.shadow,n.version}}]);