1// [email protected] downloaded from https://ga.jspm.io/npm:[email protected]/build/pdf.mjs 2 3var t={};(()=>{t.d=(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:true,get:s[i]})}})();(()=>{t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)})();var e=globalThis.pdfjsLib={};t.d(e,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>c,AnnotationEditorType:()=>h,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>o,AnnotationType:()=>g,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>p,InvalidPDFException:()=>InvalidPDFException,MathClamp:()=>MathClamp,OPS:()=>b,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>A,PermissionFlag:()=>d,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,ResponseException:()=>ResponseException,SignatureExtractor:()=>SignatureExtractor,SupportedImageMimeTypes:()=>C,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,Util:()=>Util,VerbosityLevel:()=>m,XfaLayer:()=>XfaLayer,build:()=>st,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getUuid:()=>getUuid,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,isValidExplicitDest:()=>Z,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>et});const s=typeof process==="object"&&process+""==="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser");const i=[1,0,0,1,0,0];const n=[.001,0,0,.001,0,0];const a=1.35;const r={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256};const o={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3};const l="pdfjs_internal_editor_";const h={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,SIGNATURE:101};const c={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41};const d={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048};const u={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4};const p={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3};const g={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26};const f={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5};const m={ERRORS:0,WARNINGS:1,INFOS:5};const b={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93};const A={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let w=m.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(w=t)}function getVerbosityLevel(){return w}function info(t){w>=m.INFOS&&console.log(`Info: ${t}`)}function warn(t){w>=m.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return true;default:return false}}function createValidAbsoluteUrl(t,e=null,s=null){if(!t)return null;if(s&&typeof t==="string"){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=stringToUTF8String(t)}catch{}}const i=e?URL.parse(t,e):URL.parse(t);return _isValidProtocol(i)?i:null}function shadow(t,e,s,i=false){Object.defineProperty(t,e,{value:s,enumerable:!i,configurable:true,writable:false});return s}const v=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends v{constructor(t,e){super(t,"PasswordException");
3this.code=e}}class UnknownErrorException extends v{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends v{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends v{constructor(t,e,s){super(t,"ResponseException");this.status=e;this.missing=s}}class FormatError extends v{constructor(t){super(t,"FormatError")}}class AbortException extends v{constructor(t){super(t,"AbortException")}}function bytesToString(t){typeof t==="object"&&t?.length!==void 0||unreachable("Invalid argument for bytesToString");const e=t.length;const s=8192;if(e<s)return String.fromCharCode.apply(null,t);const i=[];for(let n=0;n<e;n+=s){const a=Math.min(n+s,e);const r=t.subarray(n,a);i.push(String.fromCharCode.apply(null,r))}return i.join("")}function stringToBytes(t){typeof t!=="string"&&unreachable("Invalid argument for stringToBytes");const e=t.length;const s=new Uint8Array(e);for(let i=0;i<e;++i)s[i]=t.charCodeAt(i)&255;return s}function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,t&255)}function objectFromMap(t){const e=Object.create(null);for(const[s,i]of t)e[s]=i;return e}function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;const e=new Uint32Array(t.buffer,0,1);return e[0]===1}function isEvalSupported(){try{new Function("");return true}catch{return false}}class util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",isLittleEndian())}static get isEvalSupported(){return shadow(this,"isEvalSupported",isEvalSupported())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas!=="undefined")}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported",typeof ImageDecoder!=="undefined")}static get platform(){if(typeof navigator!=="undefined"&&typeof navigator?.platform==="string"&&typeof navigator?.userAgent==="string"){const{platform:t,userAgent:e}=navigator;return shadow(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}return shadow(this,"platform",{isAndroid:false,isLinux:false,isMac:false,isWindows:false,isFirefox:false})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const y=Array.from(Array(256).keys(),(t=>t.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,s){return`#${y[t]}${y[e]}${y[s]}`}static scaleMinMax(t,e){let s;if(t[0]){if(t[0]<0){s=e[0];e[0]=e[2];e[2]=s}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){s=e[1];e[1]=e[3];e[3]=s}e[1]*=t[3];e[3]*=t[3]}else{s=e[0];e[0]=e[1];e[1]=s;s=e[2];e[2]=e[3];e[3]=s;if(t[1]<0){s=e[1];e[1]=e[3];e[3]=s}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){s=e[0];e[0]=e[2];e[2]=s}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4];const i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2];const i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s;const n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e);const i=this.applyTransform(t.slice(2,4),e);const n=this.applyTransform([t[0],t[3]],e);const a=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],a[0]),Math.min(s[1],i[1],n[1],a[1]),Math.max(s[0],i[0],n[0],a[0]),Math.max(s[1],i[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]];const s=t[0]*e[0]+t[1]*e[2];const i=t[0]*e[1]+t[1]*e[3];const n=t[2]*e[0]+t[3]*e[2];const a=t[2]*e[1]+t[3]*e[3];const r=(s+a)/2;const o=Math.sqrt((s+a)**2-4*(s*a-n*i))/2;const l=r+o||1;const h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2]));const i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3]));const a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[s,n,i,a]}static#t(t,e,s,i,n,a,r,o,l,h){if(l<=0||l>=1)return;const c=1-l;const d=l*l;const u=d*l;const p=c*(c*(c*t+3*l*e)+3*d*s)+u*i;const g=c*(c*(c*n+3*l*a)+3*d*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,s,i,n,a,r,o,l,h,c,d){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,s,i,n,a,r,o,-c/h,d);return}const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u);const g=2*l;this.#t(t,e,s,i,n,a,r,o,(-h+p)/g,d);this.#t(t,e,s,i,n,a,r,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,s,i,n,a,r,o,l){if(l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,r),Math.min(e,o),Math.max(t,r),Math.max(e,o)];this.#e(t,s,n,r,e,i,a,o,3*(3*(s-n)-t+r),6*(t-2*s+n),3*(s-t),l);this.#e(t,s,n,r,e,i,a,o,3*(3*(i-a)-e+o),6*(e-2*i+a),3*(i-e),l);return l}}function stringToUTF8String(t){return decodeURIComponent(escape(t))}let E=null;let _=null;function normalizeUnicode(t){if(!E){E=/([\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;_=new Map([["ï¬
","ſt"]])}return t.replaceAll(E,((t,e,s)=>e?e.normalize("NFKC"):_.get(s)))}function getUuid(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}const x="pdfjs_internal_id_";function _isValidExplicitDest(t,e,s){if(!Array.isArray(s)||s.length<2)return false;const[i,n,...a]=s;
3if(!t(i)&&!Number.isInteger(i))return false;if(!e(n))return false;const r=a.length;let o=true;switch(n.name){case"XYZ":if(r<2||r>3)return false;break;case"Fit":case"FitB":return r===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return false;break;case"FitR":if(r!==4)return false;o=false;break;default:return false}for(const t of a)if(!(typeof t==="number"||o&&t===null))return false;return true}function MathClamp(t,e,s){return Math.min(Math.max(t,e),s)}function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}function fromBase64Util(t){return Uint8Array.fromBase64?Uint8Array.fromBase64(t):stringToBytes(atob(t))}typeof Promise.try!=="function"&&(Promise.try=function(t,...e){return new Promise((s=>{s(t(...e))}))});const S="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);switch(e){case"arraybuffer":return s.arrayBuffer();case"blob":return s.blob();case"json":return s.json()}return s.text()}return new Promise(((s,i)=>{const n=new XMLHttpRequest;n.open("GET",t,true);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(n.status!==200&&n.status!==0)i(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":s(n.response);return}s(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:a=0,dontFlip:r=false}){this.viewBox=t;this.userUnit=e;this.scale=s;this.rotation=i;this.offsetX=n;this.offsetY=a;s*=e;const o=(t[2]+t[0])/2;const l=(t[3]+t[1])/2;let h,c,d,u;i%=360;i<0&&(i+=360);switch(i){case 180:h=-1;c=0;d=0;u=1;break;case 90:h=0;c=1;d=1;u=0;break;case 270:h=0;c=-1;d=-1;u=0;break;case 0:h=1;c=0;d=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){d=-d;u=-u}let p,g;let f,m;if(h===0){p=Math.abs(l-t[1])*s+n;g=Math.abs(o-t[0])*s+a;f=(t[3]-t[1])*s;m=(t[2]-t[0])*s}else{p=Math.abs(o-t[0])*s+n;g=Math.abs(l-t[1])*s+a;f=(t[2]-t[0])*s;m=(t[3]-t[1])*s}this.transform=[h*s,c*s,d*s,u*s,p-h*s*o-d*s*l,g-c*s*o-u*s*l];this.width=f;this.height=m}get rawDims(){const t=this.viewBox;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=false}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform);const s=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends v{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let s=0;while(s<e&&t[s].trim()==="")s++;return t.substring(s,s+5).toLowerCase()==="data:"}function isPdfFile(t){return typeof t==="string"&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t){[t]=t.split(/[#?]/,1);return t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if(typeof t!=="string")return e;if(isDataScheme(t)){warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const s=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;const i=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;const n=s.exec(t);let a=i.exec(n[1])||i.exec(n[2])||i.exec(n[3]);if(a){a=a[0];if(a.includes("%"))try{a=i.exec(decodeURIComponent(a))[0]}catch{}}return a||e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`);this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.started[t],end:Date.now()});delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms\n`);return t.join("")}}function isValidFetchUrl(t,e){const s=e?URL.parse(t,e):URL.parse(t);return s?.protocol==="http:"||s?.protocol==="https:"}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}class PDFDateString{static#s;static toDateObject(t){if(!t||typeof t!=="string")return null;this.#s||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#s.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;c=c>=0&&c<=59?c:0;if(l==="-"){a+=h;r+=c}else if(l==="+"){a-=h;r-=c}return new Date(Date.UTC(s,i,n,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:s=0}){const{width:i,height:n}=t.attributes.style;const a=[0,0,parseInt(i),parseInt(n)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:s})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(e&16711680)>>16,(e&65280)>>8,e&255]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const s of t.keys()){e.style.color=s;const i=window.getComputedStyle(e).color;t.set(s,getRGB(i))}e.remove()}function getCurrentTransform(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform();return[e,s,i,n,a,r]}function getCurrentTransformInverse(t){const{a:e,b:s,c:i,d:n,e:a,f:r}=t.getTransform().invertSelf();return[e,s,i,n,a,r]}function setLayerDimensions(t,e,s=false,i=true){if(e instanceof PageViewport){const{pageWidth:i,pageHeight:n}=e.rawDims;const{style:a}=t;const r=util_FeatureTest.isCSSRoundSupported;const o=`var(--total-scale-factor) * ${i}px`,l=`var(--total-scale-factor) * ${n}px`;const h=r?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,c=r?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;if(s&&e.rotation%180!==0){a.width=c;a.height=h}else{a.width=h;a.height=c}}i&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;this.sx=t;this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,s,i){let n=Infinity,a=Infinity,r=Infinity;s>0&&(n=Math.sqrt(s/(t*e)));if(i!==-1){a=i/t;r=i/e}const o=Math.min(n,a,r);if(this.sx>o||this.sy>o){this.sx=o;this.sy=o;return true}return false}static get pixelRatio(){return globalThis.devicePixelRatio||1}}
3const C=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class EditorToolbar{#i=null;#n=null;#a;#r=null;#o=null;#l=null;static#h=null;constructor(t){this.#a=t;EditorToolbar.#h||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#i=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#c,{signal:e});const s=this.#r=document.createElement("div");s.className="buttons";t.append(s);const i=this.#a.toolbarPosition;if(i){const{style:e}=t;const s=this.#a._uiManager.direction==="ltr"?1-i[0]:i[0];e.insetInlineEnd=100*s+"%";e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}this.#d();return t}get div(){return this.#i}static#c(t){t.stopPropagation()}#u(t){this.#a._focusEventsAllowed=false;stopEvent(t)}#p(t){this.#a._focusEventsAllowed=true;stopEvent(t)}#g(t){const e=this.#a._uiManager._signal;t.addEventListener("focusin",this.#u.bind(this),{capture:true,signal:e});t.addEventListener("focusout",this.#p.bind(this),{capture:true,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#i.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#i.classList.remove("hidden");this.#o?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#a;const s=document.createElement("button");s.className="delete";s.tabIndex=0;s.setAttribute("data-l10n-id",EditorToolbar.#h[t]);this.#g(s);s.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#r.append(s)}get#f(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#g(e);this.#r.prepend(e,this.#f);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#g(e);this.#r.prepend(e,this.#f)}async addEditSignatureButton(t){const e=this.#l=await t.renderEditButton(this.#a);this.#g(e);this.#r.prepend(e,this.#f)}updateEditSignatureButton(t){this.#l&&(this.#l.title=t)}remove(){this.#i.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#r=null;#i=null;#m;constructor(t){this.#m=t}#b(){const t=this.#i=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#m._signal});const e=this.#r=document.createElement("div");e.className="buttons";t.append(e);this.#A();return t}#w(t,e){let s=0;let i=0;for(const n of t){const t=n.y+n.height;if(t<s)continue;const a=n.x+(e?n.width:0);if(t>s){i=a;s=t}else e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#w(e,s);const{style:a}=this.#i||=this.#b();t.append(this.#i);a.insetInlineEnd=100*i+"%";a.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#i.remove()}#A(){const t=document.createElement("button");t.className="highlightButton";t.tabIndex=0;t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e);e.className="visuallyHidden";e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#m._signal;t.addEventListener("contextmenu",noContextMenu,{signal:s});t.addEventListener("click",(()=>{this.#m.highlightSelection("floating_button")}),{signal:s});this.#r.append(t)}}function bindEvents(t,e,s){for(const i of s)e.addEventListener(i,t[i].bind(t))}class IdManager{#v=0;get id(){return`${l}${this.#v++}`}}class ImageManager{#y=getUuid();#v=0;#E=null;static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';const e=new OffscreenCanvas(1,3);const s=e.getContext("2d",{willReadFrequently:true});const i=new Image;i.src=t;const n=i.decode().then((()=>{s.drawImage(i,0,0,1,1,0,0,1,3);return new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0}));return shadow(this,"_isSVGFittingCanvas",n)}async#_(t,e){this.#E||=new Map;let s=this.#E.get(t);if(s===null)return null;if(s?.bitmap){s.refCounter+=1;return s}try{s||={bitmap:null,id:`image_${this.#y}_${this.#v++}`,refCounter:0,isSvg:false};let t;if(typeof e==="string"){s.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=s.file=e:e instanceof Blob&&(t=e);if(t.type==="image/svg+xml"){const e=ImageManager._isSVGFittingCanvas;const i=new FileReader;const n=new Image;const a=new Promise(((t,a)=>{n.onload=()=>{s.bitmap=n;s.isSvg=true;t()};i.onload=async()=>{const t=s.svgUrl=i.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=i.onerror=a}));i.readAsDataURL(t);await a}else s.bitmap=await createImageBitmap(t);s.refCounter=1}catch(t){warn(t);s=null}this.#E.set(t,s);s&&this.#E.set(s.id,s);return s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#_(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#_(t,t)}async getFromBlob(t,e){const s=await e;return this.#_(t,s)}async getFromId(t){this.#E||=new Map;const e=this.#E.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#E||=new Map;let s=this.#E.get(t);if(s?.bitmap){s.refCounter+=1;return s}const i=new OffscreenCanvas(e.width,e.height);const n=i.getContext("2d");n.drawImage(e,0,0);s={bitmap:i.transferToImageBitmap(),id:`image_${this.#y}_${this.#v++}`,refCounter:1,isSvg:false};
3this.#E.set(t,s);this.#E.set(s.id,s);return s}getSvgUrl(t){const e=this.#E.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#E||=new Map;const e=this.#E.get(t);if(!e)return;e.refCounter-=1;if(e.refCounter!==0)return;const{bitmap:s}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(s.width,s.height);const i=t.getContext("bitmaprenderer");i.transferFromImageBitmap(s);e.blobPromise=t.convertToBlob()}s.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#y}_`)}}class CommandManager{#x=[];#S=false;#C;#T=-1;constructor(t=128){this.#C=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:a=false,keepUndo:r=false}){i&&t();if(this.#S)return;const o={cmd:t,undo:e,post:s,type:n};if(this.#T===-1){this.#x.length>0&&(this.#x.length=0);this.#T=0;this.#x.push(o);return}if(a&&this.#x[this.#T].type===n){r&&(o.undo=this.#x[this.#T].undo);this.#x[this.#T]=o;return}const l=this.#T+1;if(l===this.#C)this.#x.splice(0,1);else{this.#T=l;l<this.#x.length&&this.#x.splice(l)}this.#x.push(o)}undo(){if(this.#T===-1)return;this.#S=true;const{undo:t,post:e}=this.#x[this.#T];t();e?.();this.#S=false;this.#T-=1}redo(){if(this.#T<this.#x.length-1){this.#T+=1;this.#S=true;const{cmd:t,post:e}=this.#x[this.#T];t();e?.();this.#S=false}}hasSomethingToUndo(){return this.#T!==-1}hasSomethingToRedo(){return this.#T<this.#x.length-1}cleanType(t){if(this.#T!==-1){for(let e=this.#T;e>=0;e--)if(this.#x[e].type!==t){this.#x.splice(e+1,this.#T-e);this.#T=e;return}this.#x.length=0;this.#T=-1}}destroy(){this.#x=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[s,i,n={}]of t)for(const t of s){const s=t.startsWith("mac+");if(e&&s){this.callbacks.set(t.slice(4),{callback:i,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!s){this.callbacks.set(t,{callback:i,options:n});this.allKeys.add(t.split("+").at(-1))}}}#M(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#M(e));if(!s)return;const{callback:i,options:{bubbles:n=false,args:a=[],checker:r=null}}=s;if(!r||r(t,e)){i.bind(t,...a,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);getColorValues(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,s]of this._colors)if(s.every(((t,s)=>t===e[s])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#D=new AbortController;#P=null;#I=new Map;#k=new Map;#R=null;#L=null;#F=null;#O=new CommandManager;#N=null;#B=null;#U=0;#H=new Set;#z=null;#G=null;#V=new Set;_editorUndoBar=null;#$=false;#W=false;#j=false;#q=null;#X=null;#K=null;#Y=null;#Q=false;#J=null;#Z=new IdManager;#tt=false;#et=false;#st=null;#it=null;#nt=null;#at=null;#rt=null;#ot=h.NONE;#lt=new Set;#ht=null;#ct=null;#dt=null;#ut=null;#pt={isEditing:false,isEmpty:true,hasSomethingToUndo:false,hasSomethingToRedo:false,hasSelectedEditor:false,hasSelectedText:false};#gt=[0,0];#ft=null;#mt=null;#bt=null;#At=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype;const arrowChecker=t=>t.#mt.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&t.hasSomethingToControl();const textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return t!=="text"&&t!=="number"}return true};const e=this.TRANSLATE_SMALL;const s=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#mt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#mt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:arrowChecker}]]))}constructor(t,e,s,i,n,a,r,o,l,h,c,d,u,p){const g=this._signal=this.#D.signal;this.#mt=t;this.#bt=e;this.#R=s;this.#ct=i;this._eventBus=n;n._on("editingaction",this.onEditingAction.bind(this),{signal:g});n._on("pagechanging",this.onPageChanging.bind(this),{signal:g});n._on("scalechanging",this.onScaleChanging.bind(this),{signal:g});n._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g});n._on("setpreference",this.onSetPreference.bind(this),{signal:g});n._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:g});this.#wt();this.#vt();this.#yt();this.#L=a.annotationStorage;this.#q=a.filterFactory;this.#dt=r;this.#Y=o||null;this.#$=l;this.#W=h;this.#j=c;this.#rt=d||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=false;this._editorUndoBar=u||null;this._supportsPinchToZoom=p!==false}destroy(){this.#At?.resolve();this.#At=null;this.#D?.abort();this.#D=null;this._signal=null;
3for(const t of this.#k.values())t.destroy();this.#k.clear();this.#I.clear();this.#V.clear();this.#at?.clear();this.#P=null;this.#lt.clear();this.#O.destroy();this.#R?.destroy();this.#ct?.destroy();this.#J?.hide();this.#J=null;this.#nt?.destroy();this.#nt=null;if(this.#X){clearTimeout(this.#X);this.#X=null}if(this.#ft){clearTimeout(this.#ft);this.#ft=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#rt}get useNewAltTextFlow(){return this.#W}get useNewAltTextWhenAddingImage(){return this.#j}get hcmFilter(){return shadow(this,"hcmFilter",this.#dt?this.#q.addHCMFilter(this.#dt.foreground,this.#dt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#mt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#Y?new Map(this.#Y.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(true)}else this.disableUserSelect(false);this.#B=t}setMainHighlightColorPicker(t){this.#nt=t}editAltText(t,e=false){this.#R?.editAltText(this,t,e)}getSignature(t){this.#ct?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#ct}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:true,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":this.#j=e;break}}onPageChanging({pageNumber:t}){this.#U=t-1}focusMainContainer(){this.#mt.focus()}findParent(t,e){for(const s of this.#k.values()){const{x:i,y:n,width:a,height:r}=s.div.getBoundingClientRect();if(t>=i&&t<=i+a&&e>=n&&e<=n+r)return s}return null}disableUserSelect(t=false){this.#bt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#V.add(t)}removeShouldRescale(t){this.#V.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#V)t.onScaleChanging();this.#B?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Et({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#_t(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a}=e;const r=e.toString();const o=this.#Et(e);const l=o.closest(".textLayer");const c=this.getSelectionBoxes(l);if(!c)return;e.empty();const d=this.#_t(l);const u=this.#ot===h.NONE;const callback=()=>{d?.createAndAddNewEditor({x:0,y:0},false,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:a,text:r});u&&this.showAllEditors("highlight",true,true)};u?this.switchToMode(h.HIGHLIGHT,callback):callback()}#xt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Et(t);const s=e.closest(".textLayer");const i=this.getSelectionBoxes(s);if(i){this.#J||=new HighlightToolbar(this);this.#J.show(s,i,this.direction==="ltr")}}addToAnnotationStorage(t){t.isEmpty()||!this.#L||this.#L.has(t.id)||this.#L.setValue(t.id,t)}#St(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ht){this.#J?.hide();this.#ht=null;this.#Ct({hasSelectedText:false})}return}const{anchorNode:e}=t;if(e===this.#ht)return;const s=this.#Et(t);const i=s.closest(".textLayer");if(i){this.#J?.hide();this.#ht=e;this.#Ct({hasSelectedText:true});if(this.#ot===h.HIGHLIGHT||this.#ot===h.NONE){this.#ot===h.HIGHLIGHT&&this.showAllEditors("highlight",true,true);this.#Q=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#ot===h.HIGHLIGHT?this.#_t(i):null;t?.toggleDrawing();const e=new AbortController;const s=this.combinedSignal(e);const pointerup=s=>{if(s.type!=="pointerup"||s.button===0){e.abort();t?.toggleDrawing(true);s.type==="pointerup"&&this.#Tt("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ht){this.#J?.hide();this.#ht=null;this.#Ct({hasSelectedText:false})}}#Tt(t=""){this.#ot===h.HIGHLIGHT?this.highlightSelection(t):this.#$&&this.#xt(
3)}#wt(){document.addEventListener("selectionchange",this.#St.bind(this),{signal:this._signal})}#Mt(){if(this.#K)return;this.#K=new AbortController;const t=this.combinedSignal(this.#K);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Dt(){this.#K?.abort();this.#K=null}blur(){this.isShiftKeyDown=false;if(this.#Q){this.#Q=false;this.#Tt("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#lt)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=false;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=true}),{once:true,signal:this._signal});e.focus()}#yt(){if(this.#st)return;this.#st=new AbortController;const t=this.combinedSignal(this.#st);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Pt(){this.#st?.abort();this.#st=null}#It(){if(this.#N)return;this.#N=new AbortController;const t=this.combinedSignal(this.#N);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})}#kt(){this.#N?.abort();this.#N=null}#vt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#yt();this.#It()}removeEditListeners(){this.#Pt();this.#kt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#G)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#G)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#lt){const s=t.serialize(true);s&&e.push(s)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#G)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const t=[];for(const e of s){const s=await i.deserialize(e);if(!s)return;t.push(s)}const cmd=()=>{for(const e of t)this.#Rt(e);this.#Lt(t)};const undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd:cmd,undo:undo,mustExec:true})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||t.key!=="Shift"||(this.isShiftKeyDown=true);this.#ot===h.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&t.key==="Shift"){this.isShiftKeyDown=false;if(this.#Q){this.#Q=false;this.#Tt("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#Ct(t){const e=Object.entries(t).some((([t,e])=>this.#pt[t]!==e));if(e){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#pt,t)});this.#ot===h.HIGHLIGHT&&t.hasSelectedEditor===false&&this.#Ft([[c.HIGHLIGHT_FREE,true]])}}#Ft(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Mt();this.#It();this.#Ct({isEditing:this.#ot!==h.NONE,isEmpty:this.#Ot(),hasSomethingToUndo:this.#O.hasSomethingToUndo(),hasSomethingToRedo:this.#O.hasSomethingToRedo(),hasSelectedEditor:false})}else{this.#Dt();this.#kt();this.#Ct({isEditing:false});this.disableUserSelect(false)}}registerEditorTypes(t){if(!this.#G){this.#G=t;for(const t of this.#G)this.#Ft(t.defaultPropertiesToUpdate)}}getId(){return this.#Z.id}get currentLayer(){return this.#k.get(this.#U)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#U}addLayer(t){this.#k.set(t.pageIndex,t);this.#tt?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,s=false){if(this.#ot!==t){if(this.#At){await this.#At.promise;if(!this.#At)return}this.#At=Promise.withResolvers();this.#ot=t;if(t!==h.NONE){t===h.SIGNATURE&&await(this.#ct?.loadSignatures());this.setEditingState(true);await this.#Nt();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#I.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#At.resolve()}else{s&&this.addNewEditorFromKeyboard();this.#At.resolve()}}else{this.setEditingState(false);this.#Bt();this._editorUndoBar?.hide();this.#At.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#ot&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#G){switch(t){case c.CREATE:this.currentLayer.addNewEditor(e);return;case c.HIGHLIGHT_DEFAULT_COLOR:this.#nt?.updateColor(e);break;case c.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ut||=new Map).set(t,e);this.showAllEditors("highlight",e);break}for(const s of this.#lt)s.updateParams(t,e);for(const s of this.#G)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=false){for(const s of this.#I.values())s.editorType===t&&s.show(e);const i=this.#ut?.get(c.HIGHLIGHT_SHOW_ALL)??true;i!==e&&this.#Ft([[c.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=false){if(this.#et!==t){this.#et=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Nt(){if(!this.#tt){this.#tt=true;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#I.values())t.enable()}}#Bt(){this.unselectAll();if(this.#tt){this.#tt=false;for(const t of this.#k.values())t.disable();for(const t of this.#I.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#I.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#I.get(t)}addEditor(t){this.#I.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#X&&clearTimeout(this.#X);this.#X=setTimeout((()=>{this.focusMainContainer();this.#X=null}),0)}this.#I.delete(t.id);t.annotationElementId&&this.#at?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#L?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=true}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=false}#Rt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}
3}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Ft(t.propertiesToUpdate)}}get#Ut(){let t=null;for(t of this.#lt);return t}updateUI(t){this.#Ut===t&&this.#Ft(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Ft(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#lt.has(t)){this.#lt.delete(t);t.unselect();this.#Ct({hasSelectedEditor:this.hasSelection})}else{this.#lt.add(t);t.select();this.#Ft(t.propertiesToUpdate);this.#Ct({hasSelectedEditor:true})}}setSelected(t){this.#B?.commitOrRemove();for(const e of this.#lt)e!==t&&e.unselect();this.#lt.clear();this.#lt.add(t);t.select();this.#Ft(t.propertiesToUpdate);this.#Ct({hasSelectedEditor:true})}isSelected(t){return this.#lt.has(t)}get firstSelectedEditor(){return this.#lt.values().next().value}unselect(t){t.unselect();this.#lt.delete(t);this.#Ct({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#lt.size!==0}get isEnterHandled(){return this.#lt.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#O.undo();this.#Ct({hasSomethingToUndo:this.#O.hasSomethingToUndo(),hasSomethingToRedo:true,isEmpty:this.#Ot()});this._editorUndoBar?.hide()}redo(){this.#O.redo();this.#Ct({hasSomethingToUndo:true,hasSomethingToRedo:this.#O.hasSomethingToRedo(),isEmpty:this.#Ot()})}addCommands(t){this.#O.add(t);this.#Ct({hasSomethingToUndo:true,hasSomethingToRedo:false,isEmpty:this.#Ot()})}cleanUndoStack(t){this.#O.cleanType(t)}#Ot(){if(this.#I.size===0)return true;if(this.#I.size===1)for(const t of this.#I.values())return t.isEmpty();return false}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(true);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#lt];const cmd=()=>{this._editorUndoBar?.show(undo,e.length===1?e[0].editorType:e.length);for(const t of e)t.remove()};const undo=()=>{for(const t of e)this.#Rt(t)};this.addCommands({cmd:cmd,undo:undo,mustExec:true})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#Lt(t){for(const t of this.#lt)t.unselect();this.#lt.clear();for(const e of t)if(!e.isEmpty()){this.#lt.add(e);e.select()}this.#Ct({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#lt)t.commit();this.#Lt(this.#I.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#ot!==h.NONE)return}if(!this.#B?.commitOrRemove()&&this.hasSelection){for(const t of this.#lt)t.unselect();this.#lt.clear();this.#Ct({hasSelectedEditor:false})}}translateSelectedEditors(t,e,s=false){s||this.commitOrRemove();if(!this.hasSelection)return;this.#gt[0]+=t;this.#gt[1]+=e;const[i,n]=this.#gt;const a=[...this.#lt];const r=1e3;this.#ft&&clearTimeout(this.#ft);this.#ft=setTimeout((()=>{this.#ft=null;this.#gt[0]=this.#gt[1]=0;this.addCommands({cmd:()=>{for(const t of a)if(this.#I.has(t.id)){t.translateInPage(i,n);t.translationDone()}},undo:()=>{for(const t of a)if(this.#I.has(t.id)){t.translateInPage(-i,-n);t.translationDone()}},mustExec:false})}),r);for(const s of a){s.translateInPage(t,e);s.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(true);this.#z=new Map;for(const t of this.#lt)this.#z.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#z)return false;this.disableUserSelect(false);const t=this.#z;this.#z=null;let e=false;for(const[{x:s,y:i,pageIndex:n},a]of t){a.newX=s;a.newY=i;a.newPageIndex=n;e||=s!==a.savedX||i!==a.savedY||n!==a.savedPageIndex}if(!e)return false;const move=(t,e,s,i)=>{if(this.#I.has(t.id)){const n=this.#k.get(i);if(n)t._setParentAndPosition(n,e,s);else{t.pageIndex=i;t.x=e;t.y=s}}};this.addCommands({cmd:()=>{for(const[e,{newX:s,newY:i,newPageIndex:n}]of t)move(e,s,i,n)},undo:()=>{for(const[e,{savedX:s,savedY:i,savedPageIndex:n}]of t)move(e,s,i,n)},mustExec:true});return true}dragSelectedEditors(t,e){if(this.#z)for(const s of this.#z.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#lt.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#ot}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let s=0,i=e.rangeCount;s<i;s++)if(!t.contains(e.getRangeAt(s).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-i)/a,y:1-(t+r-s)/n,width:o/a,height:r/n});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-s)/n,y:1-(e+o-i)/a,width:r/n,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-i)/a,y:(t-s)/n,width:o/a,height:r/n});break;default:r=(t,e,r,o)=>({x:(t-s)/n,y:(e-i)/a,width:r/n,height:o/a});break}const o=[];for(let t=0,s=e.rangeCount;t<s;t++){const s=e.getRangeAt(t);if(!s.collapsed)for(const{x:t,y:e,width:i,height:n}of s.getClientRects())i!==0&&n!==0&&o.push(r(t,e,i,n))}return o.length===0?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#F||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#F?.delete(t)}renderAnnotationElement(t){const e=this.#F?.get(t.data.id);if(!e)return;const s=this.#L.getRawValue(e);s&&(this.#ot!==h.NONE||s.hasBeenModified)&&s.renderAnnotationElement(t)}setMissingCanvas(t,e,s){const i=this.#at?.get(t);if(i){i.setCanvas(e,s);this.#at.delete(t)}}addMissingCanvas(t,e){(this.#at||=new Map).set(t,e)}}class AltText{#o=null;#Ht=false;#zt=null;#Gt=null;#Vt=null;#$t=null;#Wt=false;#jt=null;#a=null;#qt=null;#Xt=null;#Kt=false;static#Yt=null;static _l10n=null;constructor(t){this.#a=t;this.#Kt=t._uiManager.useNewAltTextFlow;AltText.#Yt||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){AltText._l10n??=t}async render(){const t=this.#zt=document.createElement("button");t.className="altText";t.tabIndex="0";
3const e=this.#Gt=document.createElement("span");t.append(e);if(this.#Kt){t.classList.add("new");t.setAttribute("data-l10n-id",AltText.#Yt.missing);e.setAttribute("data-l10n-id",AltText.#Yt["missing-label"])}else{t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button");e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label")}const s=this.#a._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:s});t.addEventListener("pointerdown",(t=>t.stopPropagation()),{signal:s});const onClick=t=>{t.preventDefault();this.#a._uiManager.editAltText(this.#a);this.#Kt&&this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Qt}})};t.addEventListener("click",onClick,{capture:true,signal:s});t.addEventListener("keydown",(e=>{if(e.target===t&&e.key==="Enter"){this.#Wt=true;onClick(e)}}),{signal:s});await this.#Jt();return t}get#Qt(){return(this.#o?"added":this.#o===null&&this.guessedText&&"review")||"missing"}finish(){if(this.#zt){this.#zt.focus({focusVisible:this.#Wt});this.#Wt=false}}isEmpty(){return this.#Kt?this.#o===null:!this.#o&&!this.#Ht}hasData(){return this.#Kt?this.#o!==null||!!this.#qt:this.isEmpty()}get guessedText(){return this.#qt}async setGuessedText(t){if(this.#o===null){this.#qt=t;this.#Xt=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Jt()}}toggleAltTextBadge(t=false){if(this.#Kt&&!this.#o){if(!this.#jt){const t=this.#jt=document.createElement("div");t.className="noAltTextBadge";this.#a.div.append(t)}this.#jt.classList.toggle("hidden",!t)}else{this.#jt?.remove();this.#jt=null}}serialize(t){let e=this.#o;t||this.#qt!==e||(e=this.#Xt);return{altText:e,decorative:this.#Ht,guessedText:this.#qt,textWithDisclaimer:this.#Xt}}get data(){return{altText:this.#o,decorative:this.#Ht}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=false}){if(s){this.#qt=s;this.#Xt=i}if(this.#o!==t||this.#Ht!==e){if(!n){this.#o=t;this.#Ht=e}this.#Jt()}}toggle(t=false){if(this.#zt){if(!t&&this.#$t){clearTimeout(this.#$t);this.#$t=null}this.#zt.disabled=!t}}shown(){this.#a._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Qt}})}destroy(){this.#zt?.remove();this.#zt=null;this.#Gt=null;this.#Vt=null;this.#jt?.remove();this.#jt=null}async#Jt(){const t=this.#zt;if(!t)return;if(this.#Kt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#Yt[this.#Qt]);this.#Gt?.setAttribute("data-l10n-id",AltText.#Yt[`${this.#Qt}-label`]);if(!this.#o){this.#Vt?.remove();return}}else{if(!this.#o&&!this.#Ht){t.classList.remove("done");this.#Vt?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Vt;if(!e){this.#Vt=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#a.id}`;const s=100;const i=this.#a._uiManager._signal;i.addEventListener("abort",(()=>{clearTimeout(this.#$t);this.#$t=null}),{once:true});t.addEventListener("mouseenter",(()=>{this.#$t=setTimeout((()=>{this.#$t=null;this.#Vt.classList.add("show");this.#a._reportTelemetry({action:"alt_text_tooltip"})}),s)}),{signal:i});t.addEventListener("mouseleave",(()=>{if(this.#$t){clearTimeout(this.#$t);this.#$t=null}this.#Vt?.classList.remove("show")}),{signal:i})}if(this.#Ht)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const s=this.#a.getElementForAltText();s?.setAttribute("aria-describedby",e.id)}}class TouchManager{#mt;#Zt=false;#te=null;#ee;#se;#ie;#ne;#ae=null;#re;#oe=null;#le;#he=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:a=null,signal:r}){this.#mt=t;this.#te=s;this.#ee=e;this.#se=i;this.#ie=n;this.#ne=a;this.#le=new AbortController;this.#re=AbortSignal.any([r,this.#le.signal]);t.addEventListener("touchstart",this.#ce.bind(this),{passive:false,signal:this.#re})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#ce(t){if(this.#ee?.())return;if(t.touches.length===1){if(this.#ae)return;const t=this.#ae=new AbortController;const e=AbortSignal.any([this.#re,t.signal]);const s=this.#mt;const i={capture:true,signal:e,passive:false};const cancelPointerDown=t=>{if(t.pointerType==="touch"){this.#ae?.abort();this.#ae=null}};s.addEventListener("pointerdown",(t=>{if(t.pointerType==="touch"){stopEvent(t);cancelPointerDown(t)}}),i);s.addEventListener("pointerup",cancelPointerDown,i);s.addEventListener("pointercancel",cancelPointerDown,i);return}if(!this.#he){this.#he=new AbortController;const t=AbortSignal.any([this.#re,this.#he.signal]);const e=this.#mt;const s={signal:t,capture:false,passive:false};e.addEventListener("touchmove",this.#de.bind(this),s);const i=this.#ue.bind(this);e.addEventListener("touchend",i,s);e.addEventListener("touchcancel",i,s);s.capture=true;e.addEventListener("pointerdown",stopEvent,s);e.addEventListener("pointermove",stopEvent,s);e.addEventListener("pointercancel",stopEvent,s);e.addEventListener("pointerup",stopEvent,s);this.#se?.()}stopEvent(t);if(t.touches.length!==2||this.#te?.()){this.#oe=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);this.#oe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#de(t){if(!this.#oe||t.touches.length!==2)return;stopEvent(t);let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e;const{screenX:a,screenY:r}=s;const o=this.#oe;const{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o;const u=c-l;const p=d-h;const g=a-i;const f=r-n;const m=Math.hypot(g,f)||1;const b=Math.hypot(u,p)||1;if(!this.#Zt&&Math.abs(b-m)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=i;o.touch0Y=n;o.touch1X=a;o.touch1Y=r;if(!this.#Zt){this.#Zt=true;return}const A=[(i+a)/2,(n+r)/2];this.#ie?.(A,b,m)}#ue(t){if(!(t.touches.length>=2)){this.#he.abort();this.#he=null;this.#ne?.();if(this.#oe){stopEvent(t);this.#oe=null;this.#Zt=false}}}destroy(){this.#le?.abort();this.#le=null;this.#ae?.abort();this.#ae=null}}class AnnotationEditor{#pe=null;#ge=null;#o=null;#fe=false;#me=null;#be="";#Ae=false;#we=null;#ve=null;#ye=null;#Ee=null;#_e="";#xe=false;#Se=null;#Ce=false;#Te=false;#Me=false;#De=null;#Pe=0;#Ie=0;#ke=null;#Re=null;_isCopy=false;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=true;_uiManager=null;_focusEventsAllowed=true;static _l10n=null;static _l10nResizer=null;#Le=false;#Fe=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard;const e=AnnotationEditorUIManager.TRANSLATE_SMALL;const s=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=false;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[s,i];this.pageTranslation=[n,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=false;this.deleted=false}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return false}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=true;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(AnnotationEditor._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return false}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#Le}set _isDraggable(t){this.#Le=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return true}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2);this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2);this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2;this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}
3setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#Fe}setParent(t){if(t!==null){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Oe();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#xe?this.#xe=false:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,a]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i);this.x=(t+s)/n;this.y=(e+i)/a;this.fixAndSetPosition()}_moveAfterPaste(t,e){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i);this._onTranslated()}#Ne([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i);this.x+=s/t;this.y+=i/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ne(this.parentDimensions,t,e)}translateInPage(t,e){this.#Se||=[this.x,this.y,this.width,this.height];this.#Ne(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Se||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;this.x+=t/i;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=s;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Se&&(this.#Se[0]!==this.x||this.#Se[1]!==this.y)}get _hasBeenResized(){return!!this.#Se&&(this.#Se[2]!==this.width||this.#Se[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions;const{_borderLineWidth:s}=AnnotationEditor;const i=s/t;const n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return true}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:a,width:r,height:o}=this;r*=s;o*=i;n*=s;a*=i;if(this._mustFixPosition)switch(t){case 0:n=MathClamp(n,0,s-r);a=MathClamp(a,0,i-o);break;case 90:n=MathClamp(n,0,s-o);a=MathClamp(a,r,i);break;case 180:n=MathClamp(n,r,s);a=MathClamp(a,o,i);break;case 270:n=MathClamp(n,o,s);a=MathClamp(a,0,i-r);break}this.x=n/=s;this.y=a/=i;const[l,h]=this.getBaseTranslation();n+=l;a+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#Be(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Be(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Be(t,e,360-this.parentRotation)}#Ue(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions;const{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`;this.#Ae||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div;const{height:e,width:s}=t;const i=s.endsWith("%");const n=!this.#Ae&&e.endsWith("%");if(i&&n)return;const[a,r]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/a).toFixed(2)}%`);this.#Ae||n||(t.height=`${(100*parseFloat(e)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#He(){if(this.#we)return;this.#we=document.createElement("div");this.#we.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];const e=this._uiManager._signal;for(const s of t){const t=document.createElement("div");this.#we.append(t);t.classList.add("resizer",s);t.setAttribute("data-resizer-name",s);t.addEventListener("pointerdown",this.#ze.bind(this,s),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#we)}#ze(t,e){e.preventDefault();const{isMac:s}=util_FeatureTest.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#o?.toggle(false);const i=this._isDraggable;this._isDraggable=false;this.#ve=[e.screenX,e.screenY];const n=new AbortController;const a=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(false);window.addEventListener("pointermove",this.#Ge.bind(this,t),{passive:true,capture:true,signal:a});window.addEventListener("touchmove",stopEvent,{passive:false,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#ye={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor;const o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(true);this.#o?.toggle(true);this._isDraggable=i;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#Ve()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#$e(t,e,s,i){this.width=s;this.height=i;this.x=t;this.y=e;const[n,a]=this.parentDimensions;this.setDims(n*s,a*i);this.fixAndSetPosition();this._onResized()}_onResized(){}#Ve(){if(!this.#ye)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#ye;this.#ye=null;const n=this.x;const a=this.y;const r=this.width;const o=this.height;n===t&&a===e&&r===s&&o===i||this.addCommands({cmd:this.#$e.bind(this,n,a,r,o),undo:this.#$e.bind(this,t,e,s,i),mustExec:true})}static _round(t){return Math.round(t*1e4)/1e4}#Ge(t,e){const[s,i]=this.parentDimensions;const n=this.x;const a=this.y;const r=this.width;const o=this.height;const l=AnnotationEditor.MIN_SIZE/s;const h=AnnotationEditor.MIN_SIZE/i;const c=this.#Ue(this.rotation);const transf=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e];const d=this.#Ue(360-this.rotation);const invTransf=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e];let u;let p;let g=false;let f=false;switch(t){case"topLeft":g=true;u=(t,e)=>
3[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=true;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":f=true;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=true;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=true;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":f=true;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2];break}const m=u(r,o);const b=p(r,o);let A=transf(...b);const w=AnnotationEditor._round(n+A[0]);const v=AnnotationEditor._round(a+A[1]);let y=1;let E=1;let _,x;if(e.fromKeyboard)({deltaX:_,deltaY:x}=e);else{const{screenX:t,screenY:s}=e;const[i,n]=this.#ve;[_,x]=this.screenToPageTranslation(t-i,s-n);this.#ve[0]=t;this.#ve[1]=s}[_,x]=invTransf(_/s,x/i);if(g){const t=Math.hypot(r,o);y=E=Math.max(Math.min(Math.hypot(b[0]-m[0]-_,b[1]-m[1]-x)/t,1/r,1/o),l/r,h/o)}else f?y=Math.max(l,Math.min(1,Math.abs(b[0]-m[0]-_)))/r:E=Math.max(h,Math.min(1,Math.abs(b[1]-m[1]-x)))/o;const S=AnnotationEditor._round(r*y);const C=AnnotationEditor._round(o*E);A=transf(...p(S,C));const T=w-A[0];const M=v-A[1];this.#Se||=[this.x,this.y,this.width,this.height];this.width=S;this.height=C;this.x=T;this.y=M;this.setDims(s*S,i*C);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#Te)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#pe){this.#o.data=this.#pe;this.#pe=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()??false}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360);t.className=this.name;t.setAttribute("id",this.id);t.tabIndex=this.#fe?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#We();const[e,s]=this.parentDimensions;if(this.parentRotation%180!==0){t.style.maxWidth=`${(100*s/e).toFixed(2)}%`;t.style.maxHeight=`${(100*e/s).toFixed(2)}%`}const[i,n]=this.getInitialTranslation();this.translate(i,n);bindEvents(this,t,["keydown","pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Re||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#je.bind(this),onPinching:this.#qe.bind(this),onPinchEnd:this.#Xe.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return t}#je(){this.#ye={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(false);this.parent.togglePointerEvents(false)}#qe(t,e,s){const i=.7;let n=i*(s/e)+1-i;if(n===1)return;const a=this.#Ue(this.rotation);const transf=(t,e)=>[a[0]*t+a[2]*e,a[1]*t+a[3]*e];const[r,o]=this.parentDimensions;const l=this.x;const h=this.y;const c=this.width;const d=this.height;const u=AnnotationEditor.MIN_SIZE/r;const p=AnnotationEditor.MIN_SIZE/o;n=Math.max(Math.min(n,1/c,1/d),u/c,p/d);const g=AnnotationEditor._round(c*n);const f=AnnotationEditor._round(d*n);if(g===c&&f===d)return;this.#Se||=[l,h,c,d];const m=transf(c/2,d/2);const b=AnnotationEditor._round(l+m[0]);const A=AnnotationEditor._round(h+m[1]);const w=transf(g/2,f/2);this.x=b-w[0];this.y=A-w[1];this.width=g;this.height=f;this.setDims(r*g,o*f);this.fixAndSetPosition();this._onResizing()}#Xe(){this.#o?.toggle(true);this.parent.togglePointerEvents(true);this.#Ve()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(t.button!==0||t.ctrlKey&&e)t.preventDefault();else{this.#xe=true;this._isDraggable?this.#Ke(t):this.#Ye(t)}
3}get isSelected(){return this._uiManager.isSelected(this)}#Ye(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#Ke(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=false;const i=new AbortController;const n=this._uiManager.combinedSignal(i);const a={capture:true,passive:false,signal:n};const cancelDrag=t=>{i.abort();this.#me=null;this.#xe=false;this._uiManager.endDragSession()||this.#Ye(t);s&&this._onStopDragging()};if(e){this.#Pe=t.clientX;this.#Ie=t.clientY;this.#me=t.pointerId;this.#be=t.pointerType;window.addEventListener("pointermove",(t=>{if(!s){s=true;this._onStartDragging()}const{clientX:e,clientY:i,pointerId:n}=t;if(n!==this.#me){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Pe,i-this.#Ie);this.#Pe=e;this.#Ie=i;this._uiManager.dragSelectedEditors(a,r)}),a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#be&&(this.#Re||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),a)}const pointerUpCallback=t=>{this.#me&&this.#me!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#De&&clearTimeout(this.#De);this.#De=setTimeout((()=>{this.#De=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,s){t.changeParent(this);this.x=e;this.y=s;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale;const[n,a]=this.pageDimensions;const[r,o]=this.pageTranslation;const l=t/i;const h=e/i;const c=this.x*n;const d=this.y*a;const u=this.width*n;const p=this.height*a;switch(s){case 0:return[c+l+r,a-d-h-p+o,c+l+u+r,a-d-h+o];case 90:return[c+h+r,a-d+l+o,c+h+p+r,a-d+l+u+o];case 180:return[c-l-u+r,a-d+h+o,c-l+r,a-d+h+p+o];case 270:return[c-h-p+r,a-d-l-u+o,c-h+r,a-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,a]=t;const r=n-s;const o=a-i;switch(this.rotation){case 0:return[s,e-a,r,o];case 90:return[s,e-i,o,r];case 180:return[n,e-i,r,o];case 270:return[n,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return false}enableEditMode(){this.#Te=true}disableEditMode(){this.#Te=false}isInEditMode(){return this.#Te}shouldGetKeyboardEvents(){return this.#Me}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions();const{innerHeight:n,innerWidth:a}=window;return e<a&&i>0&&t<n&&s>0}#We(){if(this.#Ee||!this.div)return;this.#Ee=new AbortController;const t=this._uiManager.combinedSignal(this.#Ee);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#We()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:true,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=false,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation;i.#pe=t.accessibilityData;i._isCopy=t.isCopy||false;const[n,a]=i.pageDimensions;const[r,o,l,h]=i.getRectInCurrentCoords(t.rect,a);i.x=r/n;i.y=o/a;i.width=l/n;i.height=h/a;return i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){this.#Ee?.abort();this.#Ee=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#De){clearTimeout(this.#De);this.#De=null}this.#Oe();this.removeEditToolbar();if(this.#ke){for(const t of this.#ke.values())clearTimeout(t);this.#ke=null}this.parent=null;this.#Re?.destroy();this.#Re=null}get isResizable(){return false}makeResizable(){if(this.isResizable){this.#He();this.#we.classList.remove("hidden")}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this);this.#ye={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#we.children;if(!this.#ge){this.#ge=Array.from(e);const t=this.#Qe.bind(this);const s=this.#Je.bind(this);const i=this._uiManager._signal;for(const e of this.#ge){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:i});e.addEventListener("blur",s,{signal:i});e.addEventListener("focus",this.#Ze.bind(this,n),{signal:i});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const s=this.#ge[0];let i=0;for(const t of e){if(t===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#ge.length/4);if(n!==i){if(n<i)for(let t=0;t<i-n;t++)this.#we.append(this.#we.firstChild);else if(n>i)for(let t=0;t<n-i;t++)this.#we.firstChild.before(this.#we.lastChild);let t=0;for(const s of e){const e=this.#ge[t++];const i=e.getAttribute("data-resizer-name");s.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[i])}}this.#ts(0);this.#Me=true;this.#we.firstChild.focus({focusVisible:true});t.preventDefault();t.stopImmediatePropagation()}#Qe(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#Je(t){this.#Me&&t.relatedTarget?.parentNode!==this.#we&&this.#Oe()}#Ze(t){this.#_e=this.#Me?t:""}#ts(t){if(this.#ge)for(const e of this.#ge)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Me&&this.#Ge(this.#_e,{deltaX:t,deltaY:e,fromKeyboard:true})}#Oe(){this.#Me=false;this.#ts(-1);this.#Ve()}_stopResizingWithKeyboard(){this.#Oe();this.div.focus()}select(){this.makeResizable();this.div?.classList.add("selectedEditor");if(this._editToolbar){this._editToolbar?.show();this.#o?.toggleAltTextBadge(false)}else this.addEditToolbar().then((()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#we?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:true});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(true)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Ce}set isEditing(t){this.#Ce=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#Ae=true;const s=t/e;const{style:i}=this.div;i.aspectRatio=s;i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return true}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=false){if(e){this.#ke||=new Map;const{action:e}=t;let s=this.#ke.get(e);s&&clearTimeout(s);s=setTimeout((()=>{this._reportTelemetry(t);this.#ke.delete(e);this.#ke.size===0&&(this.#ke=null)}),AnnotationEditor._telemetryTimeout);this.#ke.set(e,s)}else{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.#fe=false}disable(){this.div&&(this.div.tabIndex=-1);this.#fe=true}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");
3if(e){if(e.nodeName==="CANVAS"){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=true}serialize(){return this.serializeDeleted()}}const T=3285377520;const M=4294901760;const D=65535;class MurmurHash3_64{constructor(t){this.h1=t?t&4294967295:T;this.h2=t?t&4294967295:T}update(t){let e,s;if(typeof t==="string"){e=new Uint8Array(t.length*2);s=0;for(let i=0,n=t.length;i<n;i++){const n=t.charCodeAt(i);if(n<=255)e[s++]=n;else{e[s++]=n>>>8;e[s++]=n&255}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();s=e.byteLength}const i=s>>2;const n=s-i*4;const a=new Uint32Array(e.buffer,0,i);let r=0,o=0;let l=this.h1,h=this.h2;const c=3432918353,d=461845907;const u=c&D,p=d&D;for(let t=0;t<i;t++)if(t&1){r=a[t];r=r*c&M|r*u&D;r=r<<15|r>>>17;r=r*d&M|r*p&D;l^=r;l=l<<13|l>>>19;l=l*5+3864292196}else{o=a[t];o=o*c&M|o*u&D;o=o<<15|o>>>17;o=o*d&M|o*p&D;h^=o;h=h<<13|h>>>19;h=h*5+3864292196}r=0;switch(n){case 3:r^=e[i*4+2]<<16;case 2:r^=e[i*4+1]<<8;case 1:r^=e[i*4];r=r*c&M|r*u&D;r=r<<15|r>>>17;r=r*d&M|r*p&D;i&1?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=t*3981806797&M|t*36045&D;e=e*4283543511&M|(2950163797*(e<<16|t>>>16)&M)>>>16;t^=e>>>1;t=t*444984403&M|t*60499&D;e=e*3301882366&M|(3120437893*(e<<16|t>>>16)&M)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const P=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#es=false;#ss=null;#is=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const s=this.#is.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#is.get(t)}remove(t){this.#is.delete(t);this.#is.size===0&&this.resetModified();if(typeof this.onAnnotationEditor==="function"){for(const t of this.#is.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#is.get(t);let i=false;if(s!==void 0){for(const[t,n]of Object.entries(e))if(s[t]!==n){i=true;s[t]=n}}else{i=true;this.#is.set(t,e)}i&&this.#ns();e instanceof AnnotationEditor&&typeof this.onAnnotationEditor==="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#is.has(t)}getAll(){return this.#is.size>0?objectFromMap(this.#is):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#is.size}#ns(){if(!this.#es){this.#es=true;typeof this.onSetModified==="function"&&this.onSetModified()}}resetModified(){if(this.#es){this.#es=false;typeof this.onResetModified==="function"&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(this.#is.size===0)return P;const t=new Map,e=new MurmurHash3_64,s=[];const i=Object.create(null);let n=false;for(const[s,a]of this.#is){const r=a instanceof AnnotationEditor?a.serialize(false,i):a;if(r){t.set(s,r);e.update(`${s}:${JSON.stringify(r)}`);n||=!!r.bitmap}}if(n)for(const e of t.values())e.bitmap&&s.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:P}get editorStats(){let t=null;const e=new Map;for(const s of this.#is.values()){if(!(s instanceof AnnotationEditor))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor);t||=Object.create(null);const a=t[n]||=new Map;for(const[t,e]of Object.entries(i)){if(t==="type")continue;let s=a.get(t);if(!s){s=new Map;a.set(t,s)}const i=s.get(e)??0;s.set(e,i+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#ss=null}get modifiedIds(){if(this.#ss)return this.#ss;const t=[];for(const e of this.#is.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.pu
3sh(e.annotationElementId);return this.#ss={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#as;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable;const n=structuredClone(e,i?{transfer:i}:null);this.#as={map:n,hash:s,transfer:i}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#as}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#rs=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#rs.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:s}){if(t&&!this.#rs.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:i,style:n}=t;const a=new FontFace(e,i,n);this.addNativeFontFace(a);try{await a.load();this.#rs.add(e);s?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=true;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(s){warn(`Failed to load font '${e.family}': '${s}'.`);t.disableFontFace=true;throw s}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)}))}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return shadow(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",s||util_FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){function completeRequest(){assert(!s.done,"completeRequest() cannot be called twice.");s.done=true;while(e.length>0&&e[0].done){const t=e.shift();setTimeout(t.callback,0)}}const{loadingRequests:e}=this;const s={done:false,complete:completeRequest,callback:t};e.push(s);return s}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return shadow(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|t.charCodeAt(e+3)&255}function spliceString(t,e,s,i){const n=t.substring(0,e);const a=t.substring(e+s);return n+i+a}let s,i;const n=this._document.createElement("canvas");n.width=1;n.height=1;const a=n.getContext("2d");let r=0;function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);const s=a.getImageData(0,0,1,1);s.data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;const h=976;l=spliceString(l,h,o.length,o);const c=16;const d=1482184792;let u=int32(l,c);for(s=0,i=o.length-3;s<i;s+=4)u=u-d+int32(o,s)|0;s<o.length&&(u=u-d+int32(o+"XXX",s)|0);l=spliceString(l,c,4,string32(u));const p=`url(data:font/opentype;base64,${btoa(l)});`;const g=`@font-face {font-family:"${o}";src:${p}}`;this.insertRule(g);const f=this._document.createElement("div");f.style.visibility="hidden";f.style.width=f.style.height="10px";f.style.position="absolute";f.style.top=f.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;f.append(t)}this._document.body.append(f);isFontReady(o,(()=>{f.remove();e.complete()}
3))}}class FontFaceObject{constructor(t,e=null){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this._inspectFont=e}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${toBase64Util(this.data)});`;let e;if(this.cssFontInfo){let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(i||"");this.fontExtraProperties||t.delete(s);return this.compiledGlyphs[e]=n}}const I={DATA:1,ERROR:2};const k={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof PasswordException||t instanceof ResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||typeof t==="object"&&t!==null||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"ResponseException":return new ResponseException(t.message,t.status,t.missing);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#os=new AbortController;constructor(t,e,s){this.sourceName=t;this.targetName=e;this.comObj=s;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);s.addEventListener("message",this.#ls.bind(this),{signal:this.#os.signal})}#ls({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#hs(t);return}if(t.callback){const e=t.callbackId;const s=this.callbackCapabilities[e];if(!s)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===I.DATA)s.resolve(t.data);else{if(t.callback!==I.ERROR)throw new Error("Unexpected callback case");s.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:s,targetName:i,callback:I.DATA,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:s,targetName:i,callback:I.ERROR,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#cs(t):e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++;const n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:s=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:s,startCall:l,pullCall:null,cancelCall:null,isClosed:false};o.postMessage({sourceName:a,targetName:r,action:t,streamId:n,data:e,desiredSize:s.desiredSize},i);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;
3o.postMessage({sourceName:a,targetName:r,stream:k.PULL,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=true;o.postMessage({sourceName:a,targetName:r,stream:k.CANCEL,streamId:n,reason:wrapReason(t)});return e.promise}},s)}#cs(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj;const a=this,r=this.actionHandler[t.action];const o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:s,targetName:i,stream:k.ENQUEUE,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=true;n.postMessage({sourceName:s,targetName:i,stream:k.CLOSE,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=true;n.postMessage({sourceName:s,targetName:i,stream:k.ERROR,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:false,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then((function(){n.postMessage({sourceName:s,targetName:i,stream:k.START_COMPLETE,streamId:e,success:true})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:k.START_COMPLETE,streamId:e,reason:wrapReason(t)})}))}#hs(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj;const a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case k.START_COMPLETE:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case k.PULL_COMPLETE:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case k.PULL:if(!r){n.postMessage({sourceName:s,targetName:i,stream:k.PULL_COMPLETE,streamId:e,success:true});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then((function(){n.postMessage({sourceName:s,targetName:i,stream:k.PULL_COMPLETE,streamId:e,success:true})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:k.PULL_COMPLETE,streamId:e,reason:wrapReason(t)})}));break;case k.ENQUEUE:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case k.CLOSE:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=true;a.controller.close();this.#ds(a,e);break;case k.ERROR:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#ds(a,e);break;case k.CANCEL_COMPLETE:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#ds(a,e);break;case k.CANCEL:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then((function(){n.postMessage({sourceName:s,targetName:i,stream:k.CANCEL_COMPLETE,streamId:e,success:true})}),(function(t){n.postMessage({sourceName:s,targetName:i,stream:k.CANCEL_COMPLETE,streamId:e,reason:wrapReason(t)})}));r.sinkCapability.reject(o);r.isCancelled=true;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#ds(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#os?.abort();this.#os=null}}class BaseCanvasFactory{#us=false;constructor({enableHWA:t=false}){this.#us=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#us})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=false}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");s.width=t;s.height=e;return s}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=true}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}
3))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=false){}}class DOMFilterFactory extends BaseFilterFactory{#ps;#gs;#fs;#ms;#bs;#As;#v=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ms=t;this.#bs=e}get#E(){return this.#gs||=new Map}get#ws(){return this.#As||=new Map}get#vs(){if(!this.#fs){const t=this.#bs.createElement("div");const{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const s=this.#bs.createElementNS(S,"svg");s.setAttribute("width",0);s.setAttribute("height",0);this.#fs=this.#bs.createElementNS(S,"defs");t.append(s);s.append(this.#fs);this.#bs.body.append(t)}return this.#fs}#ys(t){if(t.length===1){const e=t[0];const s=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255;const i=s.join(",");return[i,i,i]}const[e,s,i]=t;const n=new Array(256);const a=new Array(256);const r=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;a[t]=s[t]/255;r[t]=i[t]/255}return[n.join(","),a.join(","),r.join(",")]}#Es(t){if(this.#ps===void 0){this.#ps="";const t=this.#bs.URL;t!==this.#bs.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ps=t.split("#",1)[0])}return`url(${this.#ps}#${t})`}addFilter(t){if(!t)return"none";let e=this.#E.get(t);if(e)return e;const[s,i,n]=this.#ys(t);const a=t.length===1?s:`${s}${i}${n}`;e=this.#E.get(a);if(e){this.#E.set(t,e);return e}const r=`g_${this.#ms}_transfer_map_${this.#v++}`;const o=this.#Es(r);this.#E.set(t,o);this.#E.set(a,o);const l=this.#_s(r);this.#xs(s,i,n,l);return o}addHCMFilter(t,e){const s=`${t}-${e}`;const i="base";let n=this.#ws.get(i);if(n?.key===s)return n.url;if(n){n.filter?.remove();n.key=s;n.url="none";n.filter=null}else{n={key:s,url:"none",filter:null};this.#ws.set(i,n)}if(!t||!e)return n.url;const a=this.#Ss(t);t=Util.makeHexColor(...a);const r=this.#Ss(e);e=Util.makeHexColor(...r);this.#vs.style.color="";if(t==="#000000"&&e==="#ffffff"||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(",");const h=`g_${this.#ms}_hcm_filter`;const c=n.filter=this.#_s(h);this.#xs(l,l,l,c);this.#Cs(c);const getSteps=(t,e)=>{const s=a[t]/255;const i=r[t]/255;const n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=s+t/e*(i-s);return n.join(",")};this.#xs(getSteps(0,5),getSteps(1,5),getSteps(2,5),c);n.url=this.#Es(h);return n.url}addAlphaFilter(t){let e=this.#E.get(t);if(e)return e;const[s]=this.#ys([t]);const i=`alpha_${s}`;e=this.#E.get(i);if(e){this.#E.set(t,e);return e}const n=`g_${this.#ms}_alpha_map_${this.#v++}`;const a=this.#Es(n);this.#E.set(t,a);this.#E.set(i,a);const r=this.#_s(n);this.#Ts(s,r);return a}addLuminosityFilter(t){let e=this.#E.get(t||"luminosity");if(e)return e;let s,i;if(t){[s]=this.#ys([t]);i=`luminosity_${s}`}else i="luminosity";e=this.#E.get(i);if(e){this.#E.set(t,e);return e}const n=`g_${this.#ms}_luminosity_map_${this.#v++}`;const a=this.#Es(n);this.#E.set(t,a);this.#E.set(i,a);const r=this.#_s(n);this.#Ms(r);t&&this.#Ts(s,r);return a}addHighlightHCMFilter(t,e,s,i,n){const a=`${e}-${s}-${i}-${n}`;let r=this.#ws.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#ws.set(t,r)}if(!e||!s)return r.url;const[o,l]=[e,s].map(this.#Ss.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]);let c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]);let[d,u]=[i,n].map(this.#Ss.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]);this.#vs.style.color="";const getSteps=(t,e,s)=>{const i=new Array(256);const n=(c-h)/s;const a=t/255;const r=(e-t)/(255*s);let o=0;for(let t=0;t<=s;t++){const e=Math.round(h+t*n);const s=a+t*r;for(let t=o;t<=e;t++)i[t]=s;o=e+1}for(let t=o;t<256;t++)i[t]=i[o-1];return i.join(",")};const p=`g_${this.#ms}_hcm_${t}_filter`;const g=r.filter=this.#_s(p);this.#Cs(g);this.#xs(getSteps(d[0],u[0],5),getSteps(d[1],u[1],5),getSteps(d[2],u[2],5),g);r.url=this.#Es(p);return r.url}destroy(t=false){if(!t||!this.#As?.size){this.#fs?.parentNode.parentNode.remove();this.#fs=null;this.#gs?.clear();this.#gs=null;this.#As?.clear();this.#As=null;this.#v=0}}#Ms(t){const e=this.#bs.createElementNS(S,"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)}#Cs(t){const e=this.#bs.createElementNS(S,"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)}#_s(t){const e=this.#bs.createElementNS(S,"filter");e.setAttribute("color-interpolation-filters","sRGB");
3e.setAttribute("id",t);this.#vs.append(e);return e}#Ds(t,e,s){const i=this.#bs.createElementNS(S,e);i.setAttribute("type","discrete");i.setAttribute("tableValues",s);t.append(i)}#xs(t,e,s,i){const n=this.#bs.createElementNS(S,"feComponentTransfer");i.append(n);this.#Ds(n,"feFuncR",t);this.#Ds(n,"feFuncG",e);this.#Ds(n,"feFuncB",s)}#Ts(t,e){const s=this.#bs.createElementNS(S,"feComponentTransfer");e.append(s);this.#Ds(s,"feFuncA",t)}#Ss(t){this.#vs.style.color=t;return getRGB(getComputedStyle(this.#vs).getPropertyValue("color"))}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}class BaseWasmFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `wasmUrl` API parameter is provided.");if(!t)throw new Error("Wasm filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load wasm data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMWasmFactory extends BaseWasmFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}s&&warn("Please use the `legacy` build in Node.js environments.");async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs");const s=await e.promises.readFile(t);return new Uint8Array(s)}class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){const s=process.getBuiltinModule("module").createRequire(import.meta.url);const i=s("@napi-rs/canvas");return i.createCanvas(t,e)}}class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeWasmFactory extends BaseWasmFactory{async _fetch(t){return node_utils_fetchData(t)}}const R={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function applyBoundingBox(t,e){if(!e)return;const s=e[2]-e[0];const i=e[3]-e[1];const n=new Path2D;n.rect(e[0],e[1],s,i);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,s,i){let n;if(i===R.STROKE||i===R.FILL){const a=e.current.getClippedPathBoundingBox(i,getCurrentTransform(t))||[0,0,0,0];const r=Math.ceil(a[2]-a[0])||1;const o=Math.ceil(a[3]-a[1])||1;const l=e.cachedCanvases.getCanvas("pattern",r,o);const h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);s=Util.transform(s,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(s);n.setTransform(c)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,s,i,n,a,r,o){const l=e.coords,h=e.colors;const c=t.data,d=t.width*4;let u;if(l[s+1]>l[i+1]){u=s;s=i;i=u;u=a;a=r;r=u}if(l[i+1]>l[n+1]){u=i;i=n;n=u;u=r;r=o;o=u}if(l[s+1]>l[i+1]){u=s;s=i;i=u;u=a;a=r;r=u}const p=(l[s]+e.offsetX)*e.scaleX;const g=(l[s+1]+e.offsetY)*e.scaleY;
3const f=(l[i]+e.offsetX)*e.scaleX;const m=(l[i+1]+e.offsetY)*e.scaleY;const b=(l[n]+e.offsetX)*e.scaleX;const A=(l[n+1]+e.offsetY)*e.scaleY;if(g>=A)return;const w=h[a],v=h[a+1],y=h[a+2];const E=h[r],_=h[r+1],x=h[r+2];const S=h[o],C=h[o+1],T=h[o+2];const M=Math.round(g),D=Math.round(A);let P,I,k,R;let L,F,O,N;for(let t=M;t<=D;t++){if(t<m){const e=t<g?0:(g-t)/(g-m);P=p-(p-f)*e;I=w-(w-E)*e;k=v-(v-_)*e;R=y-(y-x)*e}else{let e;e=t>A?1:m===A?0:(m-t)/(m-A);P=f-(f-b)*e;I=E-(E-S)*e;k=_-(_-C)*e;R=x-(x-T)*e}let e;e=t<g?0:t>A?1:(g-t)/(g-A);L=p-(p-b)*e;F=w-(w-S)*e;O=v-(v-C)*e;N=y-(y-T)*e;const s=Math.round(Math.min(P,L));const i=Math.round(Math.max(P,L));let n=d*t+s*4;for(let t=s;t<=i;t++){e=(P-t)/(P-L);e<0?e=0:e>1&&(e=1);c[n++]=I-(I-F)*e|0;c[n++]=k-(k-O)*e|0;c[n++]=R-(R-N)*e|0;c[n++]=255}}}function drawFigure(t,e,s){const i=e.coords;const n=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow;const l=Math.floor(i.length/o)-1;const h=o-1;for(a=0;a<l;a++){let e=a*o;for(let a=0;a<h;a++,e++){drawTriangle(t,s,i[e],i[e+1],i[e+o],n[e],n[e+1],n[e+o]);drawTriangle(t,s,i[e+o+1],i[e+1],i[e+o],n[e+o+1],n[e+1],n[e+o])}}break;case"triangles":for(a=0,r=i.length;a<r;a+=3)drawTriangle(t,s,i[a],i[a+1],i[a+2],n[a],n[a+1],n[a+2]);break;default:throw new Error("illegal figure")}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._coords=t[2];this._colors=t[3];this._figures=t[4];this._bounds=t[5];this._bbox=t[6];this._background=t[7];this.matrix=null}_createMeshCanvas(t,e,s){const i=1.1;const n=3e3;const a=2;const r=Math.floor(this._bounds[0]);const o=Math.floor(this._bounds[1]);const l=Math.ceil(this._bounds[2])-r;const h=Math.ceil(this._bounds[3])-o;const c=Math.min(Math.ceil(Math.abs(l*t[0]*i)),n);const d=Math.min(Math.ceil(Math.abs(h*t[1]*i)),n);const u=l/c;const p=h/d;const g={coords:this._coords,colors:this._colors,offsetX:-r,offsetY:-o,scaleX:1/u,scaleY:1/p};const f=c+a*2;const m=d+a*2;const b=s.getCanvas("mesh",f,m);const A=b.context;const w=A.createImageData(c,d);if(e){const t=w.data;for(let s=0,i=t.length;s<i;s+=4){t[s]=e[0];t[s+1]=e[1];t[s+2]=e[2];t[s+3]=255}}for(const t of this._figures)drawFigure(w,t,g);A.putImageData(w,a,a);const v=b.canvas;return{canvas:v,offsetX:r-a*u,offsetY:o-a*p,scaleX:u,scaleY:p}}getPattern(t,e,s,i){applyBoundingBox(t,this._bbox);let n;if(i===R.SHADING)n=Util.singularValueDecompose2dScale(getCurrentTransform(t));else{n=Util.singularValueDecompose2dScale(e.baseTransform);if(this.matrix){const t=Util.singularValueDecompose2dScale(this.matrix);n=[n[0]*t[0],n[1]*t[1]]}}const a=this._createMeshCanvas(n,i===R.SHADING?null:this._background,e.cachedCanvases);if(i!==R.SHADING){t.setTransform(...e.baseTransform);this.matrix&&t.transform(...this.matrix)}t.translate(a.offsetX,a.offsetY);t.scale(a.scaleX,a.scaleY);return t.createPattern(a.canvas,"no-repeat")}}class DummyShadingPattern extends BaseShadingPattern{getPattern(){return"hotpink"}}function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}const L={COLORED:1,UNCOLORED:2};class TilingPattern{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2];this.matrix=t[3];this.bbox=t[4];this.xstep=t[5];this.ystep=t[6];this.paintType=t[7];this.tilingType=t[8];this.color=e;this.ctx=s;this.canvasGraphicsFactory=i;this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:a,canvasGraphicsFactory:r}=this;let{xstep:o,ystep:l}=this;o=Math.abs(o);l=Math.abs(l);info("TilingType: "+n);const h=e[0],c=e[1],d=e[2],u=e[3];const p=d-h;const g=u-c;const f=Util.singularValueDecompose2dScale(this.matrix);const m=Util.singularValueDecompose2dScale(this.baseTransform);const b=f[0]*m[0];const A=f[1]*m[1];let w=p,v=g,y=false,E=false;const _=Math.ceil(o*b);const x=Math.ceil(l*A);const S=Math.ceil(p*b);const C=Math.ceil(g*A);_>=S?w=o:y=true;x>=C?v=l:E=true;const T=this.getSizeAndScale(w,this.ctx.canvas.width,b);const M=this.getSizeAndScale(v,this.ctx.canvas.height,A);const D=t.cachedCanvases.getCanvas("pattern",T.size,M.size);const P=D.context;const I=r.createCanvasGraphics(P);I.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(I,i,a);P.translate(-T.scale*h,-M.scale*c);I.transform(T.scale,0,0,M.scale,0,0);P.save();this.clipBbox(I,h,c,d,u);I.baseTransform=getCurrentTransform(I.ctx);I.executeOperatorList(s);I.endDrawing();
3P.restore();if(y||E){const e=D.canvas;y&&(w=o);E&&(v=l);const s=this.getSizeAndScale(w,this.ctx.canvas.width,b);const i=this.getSizeAndScale(v,this.ctx.canvas.height,A);const n=s.size;const a=i.size;const r=t.cachedCanvases.getCanvas("pattern-workaround",n,a);const d=r.context;const u=y?Math.floor(p/o):0;const f=E?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let s=0;s<=f;s++)d.drawImage(e,n*t,a*s,n,a,0,0,n,a);return{canvas:r.canvas,scaleX:s.scale,scaleY:i.scale,offsetX:h,offsetY:c}}return{canvas:D.canvas,scaleX:T.scale,scaleY:M.scale,offsetX:h,offsetY:c}}getSizeAndScale(t,e,s){const i=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);n>=i?n=i:s=n/t;return{scale:s,size:n}}clipBbox(t,e,s,i,n){const a=i-e;const r=n-s;t.ctx.rect(e,s,a,r);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,s,i,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case L.COLORED:const t=this.ctx;i.fillStyle=t.fillStyle;i.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case L.UNCOLORED:const a=Util.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a;i.strokeStyle=a;n.fillColor=a;n.strokeColor=a;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;if(i!==R.SHADING){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const a=this.createPatternCanvas(e);let r=new DOMMatrix(n);r=r.translate(a.offsetX,a.offsetY);r=r.scale(1/a.scaleX,1/a.scaleY);const o=t.createPattern(a.canvas,"repeat");o.setTransform(r);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:s,width:i,height:n,nonBlackColor:a=4294967295,inverseDecode:r=false}){const o=util_FeatureTest.isLittleEndian?4278190080:255;const[l,h]=r?[a,o]:[o,a];const c=i>>3;const d=i&7;const u=t.length;s=new Uint32Array(s.buffer);let p=0;for(let i=0;i<n;i++){for(const i=e+c;e<i;e++){const i=e<u?t[e]:255;s[p++]=i&128?h:l;s[p++]=i&64?h:l;s[p++]=i&32?h:l;s[p++]=i&16?h:l;s[p++]=i&8?h:l;s[p++]=i&4?h:l;s[p++]=i&2?h:l;s[p++]=i&1?h:l}if(d===0)continue;const i=e<u?t[e++]:255;for(let t=0;t<d;t++)s[p++]=i&1<<7-t?h:l}return{srcPos:e,destPos:p}}const F=16;const O=100;const N=15;const B=10;const U=1e3;const H=16;function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,s){e.translate(t,s);this.__originalTranslate(t,s)};t.scale=function ctxScale(t,s){e.scale(t,s);this.__originalScale(t,s)};t.transform=function ctxTransform(t,s,i,n,a,r){e.transform(t,s,i,n,a,r);this.__originalTransform(t,s,i,n,a,r)};t.setTransform=function ctxSetTransform(t,s,i,n,a,r){e.setTransform(t,s,i,n,a,r);this.__originalSetTransform(t,s,i,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,s){e.moveTo(t,s);this.__originalMoveTo(t,s)};t.lineTo=function(t,s){e.lineTo(t,s);this.__originalLineTo(t,s)};t.bezierCurveTo=function(t,s,i,n,a,r){e.bezierCurveTo(t,s,i,n,a,r);this.__originalBezierCurveTo(t,s,i,n,a,r)};t.rect=function(t,s,i,n){e.rect(t,s,i,n);this.__originalRect(t,s,i,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,s){let i;if(this.cache[t]!==void 0){i=this.cache[t];this.canvasFactory.reset(i,e,s)}else{i=this.canvasFactory.create(e,s);this.cache[t]=i}return i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,s,i,n,a,r,o,l,h){const[c,d,u,p,g,f]=getCurrentTransform(t);if(d===0&&u===0){const m=r*c+g;const b=Math.round(m);const A=o*p+f;const w=Math.round(A);const v=(r+l)*c+g;const y=Math.abs(Math.round(v)-b)||1;const E=(o+h)*p+f;const _=Math.abs(Math.round(E)-w)||1;
3t.setTransform(Math.sign(c),0,0,Math.sign(p),b,w);t.drawImage(e,s,i,n,a,0,0,y,_);t.setTransform(c,d,u,p,g,f);return[y,_]}if(c===0&&p===0){const m=o*u+g;const b=Math.round(m);const A=r*d+f;const w=Math.round(A);const v=(o+h)*u+g;const y=Math.abs(Math.round(v)-b)||1;const E=(r+l)*d+f;const _=Math.abs(Math.round(E)-w)||1;t.setTransform(0,Math.sign(d),Math.sign(u),0,b,w);t.drawImage(e,s,i,n,a,0,0,_,y);t.setTransform(c,d,u,p,g,f);return[_,y]}t.drawImage(e,s,i,n,a,r,o,l,h);const m=Math.hypot(c,d);const b=Math.hypot(u,p);return[m*l,b*h]}function compileType3Glyph(t){const{width:e,height:s}=t;if(e>U||s>U)return null;const i=1e3;const n=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]);const a=e+1;let r=new Uint8Array(a*(s+1));let o,l,h;const c=e+7&-8;let d=new Uint8Array(c*s),u=0;for(const e of t.data){let t=128;while(t>0){d[u++]=e&t?0:255;t>>=1}}let p=0;u=0;if(d[u]!==0){r[0]=1;++p}for(l=1;l<e;l++){if(d[u]!==d[u+1]){r[l]=d[u]?2:1;++p}u++}if(d[u]!==0){r[l]=2;++p}for(o=1;o<s;o++){u=o*c;h=o*a;if(d[u-c]!==d[u]){r[h]=d[u]?1:8;++p}let t=(d[u]?4:0)+(d[u-c]?8:0);for(l=1;l<e;l++){t=(t>>2)+(d[u+1]?4:0)+(d[u-c+1]?8:0);if(n[t]){r[h+l]=n[t];++p}u++}if(d[u-c]!==d[u]){r[h+l]=d[u]?2:4;++p}if(p>i)return null}u=c*(s-1);h=o*a;if(d[u]!==0){r[h]=8;++p}for(l=1;l<e;l++){if(d[u]!==d[u+1]){r[h+l]=d[u]?4:8;++p}u++}if(d[u]!==0){r[h+l]=4;++p}if(p>i)return null;const g=new Int32Array([0,a,-1,0,-a,0,0,0,1]);const f=new Path2D;for(o=0;p&&o<=s;o++){let t=o*a;const s=t+e;while(t<s&&!r[t])t++;if(t===s)continue;f.moveTo(t%a,o);const i=t;let n=r[t];do{const e=g[n];do{t+=e}while(!r[t]);const s=r[t];if(s!==5&&s!==10){n=s;r[t]=0}else{n=s&51*n>>4;r[t]&=n>>2|n<<2}f.lineTo(t%a,t/a|0);r[t]||--p}while(i!==t);--o}d=null;r=null;const drawOutline=function(t){t.save();t.scale(1/e,-1/s);t.translate(0,-s);t.fill(f);t.beginPath();t.restore()};return drawOutline}class CanvasExtraState{constructor(t,e){this.alphaIsShape=false;this.fontSize=0;this.fontSizeScale=1;this.textMatrix=i;this.textMatrixScale=1;this.fontMatrix=n;this.leading=0;this.x=0;this.y=0;this.lineX=0;this.lineY=0;this.charSpacing=0;this.wordSpacing=0;this.textHScale=1;this.textRenderingMode=u.FILL;this.textRise=0;this.fillColor="#000000";this.strokeColor="#000000";this.patternFill=false;this.patternStroke=false;this.fillAlpha=1;this.strokeAlpha=1;this.lineWidth=1;this.activeSMask=null;this.transferMaps="none";this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();return t}setCurrentPoint(t,e){this.x=t;this.y=e}updatePathMinMax(t,e,s){[e,s]=Util.applyTransform([e,s],t);this.minX=Math.min(this.minX,e);this.minY=Math.min(this.minY,s);this.maxX=Math.max(this.maxX,e);this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=Util.applyTransform(e,t);const i=Util.applyTransform(e.slice(2),t);const n=Util.applyTransform([e[0],e[3]],t);const a=Util.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],a[0]);this.minY=Math.min(this.minY,s[1],i[1],n[1],a[1]);this.maxX=Math.max(this.maxX,s[0],i[0],n[0],a[0]);this.maxY=Math.max(this.maxY,s[1],i[1],n[1],a[1])}updateScalingPathMinMax(t,e){Util.scaleMinMax(t,e);this.minX=Math.min(this.minX,e[0]);this.minY=Math.min(this.minY,e[1]);this.maxX=Math.max(this.maxX,e[2]);this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,a,r,o,l,h){const c=Util.bezierBoundingBox(e,s,i,n,a,r,o,l,h);h||this.updateRectMinMax(t,c)}getPathBoundingBox(t=R.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===R.STROKE){e||unreachable("Stroke bounding box must include transform.");const t=Util.singularValueDecompose2dScale(e);const i=t[0]*this.lineWidth/2;const n=t[1]*this.lineWidth/2;s[0]-=i;s[1]-=n;s[2]+=i;s[3]+=n}return s}updateClipFromPath(){const t=Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===Infinity}startNewPathAndClipBox(t){this.clipBox=t;this.minX=Infinity;this.minY=Infinity;this.maxX=0;this.maxY=0}getClippedPathBoundingBox(t=R.FILL,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData){t.putImageData(e,0,0);return}const s=e.height,i=e.width;const n=s%H;const a=(s-n)/H;const r=n===0?a:a+1;const o=t.createImageData(i,H);let l,h=0;const c=e.data;const d=o.data;let u,g,f,m;if(e.kind===p.GRAYSCALE_1BPP){const e=c.byteLength;const s=new Uint32Array(d.buffer,0,d.byteLength>>2);const p=s.length;const m=i+7>>3;const b=4294967295;const A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;
3u<r;u++){f=u<a?H:n;l=0;for(g=0;g<f;g++){const t=e-h;let n=0;const a=t>m?i:t*8-7;const r=a&-8;let o=0;let d=0;for(;n<r;n+=8){d=c[h++];s[l++]=d&128?b:A;s[l++]=d&64?b:A;s[l++]=d&32?b:A;s[l++]=d&16?b:A;s[l++]=d&8?b:A;s[l++]=d&4?b:A;s[l++]=d&2?b:A;s[l++]=d&1?b:A}for(;n<a;n++){if(o===0){d=c[h++];o=128}s[l++]=d&o?b:A;o>>=1}}while(l<p)s[l++]=0;t.putImageData(o,0,u*H)}}else if(e.kind===p.RGBA_32BPP){g=0;m=i*H*4;for(u=0;u<a;u++){d.set(c.subarray(h,h+m));h+=m;t.putImageData(o,0,g);g+=H}if(u<r){m=i*n*4;d.set(c.subarray(h,h+m));t.putImageData(o,0,g)}}else{if(e.kind!==p.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);f=H;m=i*f;for(u=0;u<r;u++){if(u>=a){f=n;m=i*f}l=0;for(g=m;g--;){d[l++]=c[h++];d[l++]=c[h++];d[l++]=c[h++];d[l++]=255}t.putImageData(o,0,u*H)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const s=e.height,i=e.width;const n=s%H;const a=(s-n)/H;const r=n===0?a:a+1;const o=t.createImageData(i,H);let l=0;const h=e.data;const c=o.data;for(let e=0;e<r;e++){const s=e<a?H:n;({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:c,width:i,height:s,nonBlackColor:0}));t.putImageData(o,0,e*H)}}function copyCtxState(t,e){const s=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const i of s)t[i]!==void 0&&(e[i]=t[i]);if(t.setLineDash!==void 0){e.setLineDash(t.getLineDash());e.lineDashOffset=t.lineDashOffset}}function resetCtxToDefault(t){t.strokeStyle=t.fillStyle="#000000";t.fillRule="nonzero";t.globalAlpha=1;t.lineWidth=1;t.lineCap="butt";t.lineJoin="miter";t.miterLimit=10;t.globalCompositeOperation="source-over";t.font="10px sans-serif";if(t.setLineDash!==void 0){t.setLineDash([]);t.lineDashOffset=0}if(!s){const{filter:e}=t;e!=="none"&&e!==""&&(t.filter="none")}}function getImageSmoothingEnabled(t,e){if(e)return true;const s=Util.singularValueDecompose2dScale(t);s[0]=Math.fround(s[0]);s[1]=Math.fround(s[1]);const i=Math.fround(OutputScale.pixelRatio*PixelsPerInch.PDF_TO_CSS_UNITS);return s[0]<=i&&s[1]<=i}const z=["butt","round","square"];const G=["miter","round","bevel"];const V={};const $={};class CanvasGraphics{constructor(t,e,s,i,n,{optionalContentConfig:a,markedContentStack:r=null},o,l){this.ctx=t;this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.stateStack=[];this.pendingClip=null;this.pendingEOFill=false;this.res=null;this.xobjs=null;this.commonObjs=e;this.objs=s;this.canvasFactory=i;this.filterFactory=n;this.groupStack=[];this.processingType3=null;this.baseTransform=null;this.baseTransformStack=[];this.groupLevel=0;this.smaskStack=[];this.smaskCounter=0;this.tempSMask=null;this.suspendedCtx=null;this.contentVisible=true;this.markedContentStack=r||[];this.optionalContentConfig=a;this.cachedCanvases=new CachedCanvases(this.canvasFactory);this.cachedPatterns=new Map;this.annotationCanvasMap=o;this.viewportScale=1;this.outputScaleX=1;this.outputScaleY=1;this.pageColors=l;this._cachedScaleForStroking=[-1,0];this._cachedGetSinglePixelWidth=null;this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t==="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=false,background:i=null}){const n=this.ctx.canvas.width;const a=this.ctx.canvas.height;const r=this.ctx.fillStyle;this.ctx.fillStyle=i||"#ffffff";this.ctx.fillRect(0,0,n,a);this.ctx.fillStyle=r;if(s){const t=this.cachedCanvases.getCanvas("transparent",n,a);this.compositeCtx=this.ctx;this.transparentCanvas=t.canvas;this.ctx=t.context;this.ctx.save();this.ctx.transform(...getCurrentTransform(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[0]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=getCurrentTransform(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray;const a=t.fnArray;let r=e||0;const o=n.length;if(o===r)return r;const l=o-r>B&&typeof s==="function";const h=l?Date.now()+N:0;let c=0;const d=this.commonObjs;const u=this.objs;let p;while(true){if(i!==void 0&&r===i.nextBreakPoint){i.breakIt(r,s);return r}p=a[r];if(p!==b.dependency)this[p].apply(this,n[r]);else for(const t of n[r]){const e=t.startsWith("g_")?d:u;if(!e.has(t)){e.get(t,s);return r}}r++;if(r===o)return r;if(l&&++c>B){if(Date.now()>h){s();return r}c=0}}}#Ps(){while(this.stateStack.length||this.inSMaskMode)this.restore(
3);this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#Ps();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement!=="undefined"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#Is()}#Is(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth;const i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1);let a=Math.max(Math.hypot(e[2],e[3]),1);let r=s,o=i;let l="prescale1";let h,c;while(n>2&&r>1||a>2&&o>1){let e=r,s=o;if(n>2&&r>1){e=r>=16384?Math.floor(r/2)-1||1:Math.ceil(r/2);n/=r/e}if(a>2&&o>1){s=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o)/2;a/=o/s}h=this.cachedCanvases.getCanvas(l,e,s);c=h.context;c.clearRect(0,0,e,s);c.drawImage(t,0,0,r,o,0,0,e,s);t=h.canvas;r=e;o=s;l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:r,paintHeight:o}}_createMaskCanvas(t){const e=this.ctx;const{width:s,height:i}=t;const n=this.current.fillColor;const a=this.current.patternFill;const r=getCurrentTransform(e);let o,l,h,c;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(a?r:[r.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const s=o.get(l);if(s&&!a){const t=Math.round(Math.min(r[0],r[2])+r[4]);const e=Math.round(Math.min(r[1],r[3])+r[5]);return{canvas:s,offsetX:t,offsetY:e}}h=s}if(!h){c=this.cachedCanvases.getCanvas("maskCanvas",s,i);putBinaryImageMask(c.context,t)}let d=Util.transform(r,[1/s,0,0,-1/i,0,0]);d=Util.transform(d,[1,0,0,1,0,-i]);const[u,p,g,f]=Util.getAxialAlignedBoundingBox([0,0,s,i],d);const m=Math.round(g-u)||1;const b=Math.round(f-p)||1;const A=this.cachedCanvases.getCanvas("fillCanvas",m,b);const w=A.context;const v=u;const y=p;w.translate(-v,-y);w.transform(...d);if(!h){h=this._scaleImage(c.canvas,getCurrentTransformInverse(w));h=h.img;o&&a&&o.set(l,h)}w.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(w),t.interpolate);drawImageAtIntegerCoords(w,h,0,0,h.width,h.height,0,0,s,i);w.globalCompositeOperation="source-in";const E=Util.transform(getCurrentTransformInverse(w),[1,0,0,1,-v,-y]);w.fillStyle=a?n.getPattern(e,this,E,R.FILL):n;w.fillRect(0,0,s,i);if(o&&!a){this.cachedCanvases.delete("fillCanvas");o.set(l,A.canvas)}return{canvas:A.canvas,offsetX:Math.round(v),offsetY:Math.round(y)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=z[t]}setLineJoin(t){this.ctx.lineJoin=G[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;if(s.setLineDash!==void 0){s.setLineDash(t);s.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s;this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width;const e=this.ctx.canvas.height;const s="smaskGroupAt"+this.groupLevel;const i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx;this.ctx=i.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);mirrorContextOperations(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask;const s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);
3this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0];const a=i[1];const r=i[2]-n;const o=i[3]-a;if(r!==0&&o!==0){this.genericComposeSMask(e.context,s,r,o,e.subtype,e.backdrop,e.transferMap,n,a,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(s.canvas,0,0);t.restore()}}genericComposeSMask(t,e,s,i,n,a,r,o,l,h,c){let d=t.canvas;let u=o-h;let p=l-c;if(a){const e=Util.makeHexColor(...a);if(u<0||p<0||u+s>d.width||p+i>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",s,i);const n=t.context;n.drawImage(d,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,s,i);n.globalCompositeOperation="source-over";d=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,s,i);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,s,i);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);n==="Alpha"&&r?e.filter=this.filterFactory.addAlphaFilter(r):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,s,i);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(d,u,p,s,i,o,l,s,i);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode();if(this.stateStack.length!==0){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,s,i,n,a){this.ctx.transform(t,e,s,i,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx;const n=this.current;let a=n.x,r=n.y;let o,l;const h=getCurrentTransform(i);const c=h[0]===0&&h[3]===0||h[1]===0&&h[2]===0;const d=c?s.slice(0):null;for(let s=0,u=0,p=t.length;s<p;
3s++)switch(t[s]|0){case b.rectangle:a=e[u++];r=e[u++];const t=e[u++];const s=e[u++];const p=a+t;const g=r+s;i.moveTo(a,r);if(t===0||s===0)i.lineTo(p,g);else{i.lineTo(p,r);i.lineTo(p,g);i.lineTo(a,g)}c||n.updateRectMinMax(h,[a,r,p,g]);i.closePath();break;case b.moveTo:a=e[u++];r=e[u++];i.moveTo(a,r);c||n.updatePathMinMax(h,a,r);break;case b.lineTo:a=e[u++];r=e[u++];i.lineTo(a,r);c||n.updatePathMinMax(h,a,r);break;case b.curveTo:o=a;l=r;a=e[u+4];r=e[u+5];i.bezierCurveTo(e[u],e[u+1],e[u+2],e[u+3],a,r);n.updateCurvePathMinMax(h,o,l,e[u],e[u+1],e[u+2],e[u+3],a,r,d);u+=6;break;case b.curveTo2:o=a;l=r;i.bezierCurveTo(a,r,e[u],e[u+1],e[u+2],e[u+3]);n.updateCurvePathMinMax(h,o,l,a,r,e[u],e[u+1],e[u+2],e[u+3],d);a=e[u+2];r=e[u+3];u+=4;break;case b.curveTo3:o=a;l=r;a=e[u+2];r=e[u+3];i.bezierCurveTo(e[u],e[u+1],a,r,a,r);n.updateCurvePathMinMax(h,o,l,e[u],e[u+1],a,r,a,r,d);u+=4;break;case b.closePath:i.closePath();break}c&&n.updateScalingPathMinMax(h,d);n.setCurrentPoint(a,r)}closePath(){this.ctx.closePath()}stroke(t=true){const e=this.ctx;const s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if(typeof s==="object"&&s?.getPattern){e.save();e.strokeStyle=s.getPattern(e,this,getCurrentTransformInverse(e),R.STROKE);this.rescaleAndStroke(false);e.restore()}else this.rescaleAndStroke(true);t&&this.consumePath(this.current.getClippedPathBoundingBox());e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath();this.stroke()}fill(t=true){const e=this.ctx;const s=this.current.fillColor;const i=this.current.patternFill;let n=false;if(i){e.save();e.fillStyle=s.getPattern(e,this,getCurrentTransformInverse(e),R.FILL);n=true}const a=this.current.getClippedPathBoundingBox();if(this.contentVisible&&a!==null)if(this.pendingEOFill){e.fill("evenodd");this.pendingEOFill=false}else e.fill();n&&e.restore();t&&this.consumePath(a)}eoFill(){this.pendingEOFill=true;this.fill()}fillStroke(){this.fill(false);this.stroke(false);this.consumePath()}eoFillStroke(){this.pendingEOFill=true;this.fillStroke()}closeFillStroke(){this.closePath();this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=true;this.closePath();this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=V}eoClip(){this.pendingClip=$}beginText(){this.current.textMatrix=i;this.current.textMatrixScale=1;this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths;const e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D;const i=e.getTransform().invertSelf();for(const{transform:e,x:n,y:a,fontSize:r,path:o}of t)s.addPath(o,new DOMMatrix(e).preMultiplySelf(i).translate(n,a).scale(r,-r));e.clip(s);e.beginPath();delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t);const i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);i.fontMatrix=s.fontMatrix||n;i.fontMatrix[0]!==0&&i.fontMatrix[3]!==0||warn("Invalid font matrix for font "+t);if(e<0){e=-e;i.fontDirection=-1}else i.fontDirection=1;this.current.font=s;this.current.fontSize=e;if(s.isType3Font)return;const a=s.loadedName||"sans-serif";const r=s.systemFontInfo?.css||`"${a}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const l=s.italic?"italic":"normal";let h=e;e<F?h=F:e>O&&(h=O);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,s,i,n,a){this.current.textMatrix=[t,e,s,i,n,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#ks(t,e,s){const i=new Path2D;i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e));return i}paintChar(t,e,s,i,n){const a=this.ctx;const r=this.current;const o=r.font;const l=r.textRenderingMode;const h=r.fontSize/r.fontSizeScale;const c=l&u.FILL_STROKE_MASK;const d=!!(l&u.ADD_TO_PATH_FLAG);const p=r.patternFill&&!o.missingFile;const g=r.patternStroke&&!o.missingFile;let f;(o.disableFontFace||d||p||g)&&(f=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||p||g){a.save();a.translate(e,s);a.scale(h,-h);let t;if(c===u.FILL||c===u.FILL_STROKE)if(i){t=a.getTransform();a.setTransform(...i);a.fill(this.#ks(f,t,i))}else a.fill(f);if(c===u.STROKE||c===u.FILL_STROKE)if(n){t||=a.getTransform();a.setTransform(...n);const{a:e,b:s,c:i,d:r}=t;const o=Util.inverseTransform(n);const l=Util.transform([e,s,i,r,0,0],o);const[c,d]=Util.singularValueDecompose2dScale(l);a.lineWidth*=Math.max(c,d)/h;a.stroke(this.#ks(f,t,n))}else{a.lineWidth/=h;a.stroke(f)}
3a.restore()}else{c!==u.FILL&&c!==u.FILL_STROKE||a.fillText(t,e,s);c!==u.STROKE&&c!==u.FILL_STROKE||a.strokeText(t,e,s)}if(d){const t=this.pendingTextPaths||=[];t.push({transform:getCurrentTransform(a),x:e,y:s,fontSize:h,path:f})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=false;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){s=true;break}return shadow(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current;const s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx;const a=e.fontSizeScale;const r=e.charSpacing;const o=e.wordSpacing;const l=e.fontDirection;const h=e.textHScale*l;const c=t.length;const d=s.vertical;const p=d?1:-1;const g=s.defaultVMetrics;const f=i*e.fontMatrix[0];const m=e.textRenderingMode===u.FILL&&!s.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let b,A;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),R.FILL);b=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),R.STROKE);A=getCurrentTransform(n);n.restore();n.strokeStyle=t}let w=e.lineWidth;const v=e.textMatrixScale;if(v===0||w===0){const t=e.textRenderingMode&u.FILL_STROKE_MASK;t!==u.STROKE&&t!==u.FILL_STROKE||(w=this.getSinglePixelWidth())}else w/=v;if(a!==1){n.scale(a,a);w/=a}n.lineWidth=w;if(s.isInvalidPDFjsFont){const s=[];let i=0;for(const e of t){s.push(e.unicode);i+=e.width}n.fillText(s.join(""),0,0);e.x+=i*f*h;n.restore();this.compose();return}let y,E=0;for(y=0;y<c;++y){const e=t[y];if(typeof e==="number"){E+=p*e*i/1e3;continue}let h=false;const c=(e.isSpace?o:0)+r;const u=e.fontChar;const w=e.accent;let v,_;let x=e.width;if(d){const t=e.vmetric||g;const s=-(e.vmetric?t[1]:x*.5)*f;const i=t[2]*f;x=t?-t[0]:x;v=s/a;_=(E+i)/a}else{v=E/a;_=0}if(s.remeasure&&x>0){const t=n.measureText(u).width*1e3/i*a;if(x<t&&this.isFontSubpixelAAEnabled){const e=x/t;h=true;n.save();n.scale(e,1);v/=e}else x!==t&&(v+=(x-t)/2e3*i/a)}if(this.contentVisible&&(e.isInFont||s.missingFile))if(m&&!w)n.fillText(u,v,_);else{this.paintChar(u,v,_,b,A);if(w){const t=v+i*w.offset.x/a;const e=_-i*w.offset.y/a;this.paintChar(w.fontChar,t,e,b,A)}}const S=d?x*f-c*l:x*f+c*l;E+=S;h&&n.restore()}d?e.y-=E:e.x+=E*h;n.restore();this.compose()}showType3Text(t){const e=this.ctx;const s=this.current;const i=s.font;const a=s.fontSize;const r=s.fontDirection;const o=i.vertical?1:-1;const l=s.charSpacing;const h=s.wordSpacing;const c=s.textHScale*r;const d=s.fontMatrix||n;const p=t.length;const g=s.textRenderingMode===u.INVISIBLE;let f,m,b,A;if(!g&&a!==0){this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;e.save();e.transform(...s.textMatrix);e.translate(s.x,s.y+s.textRise);e.scale(c,r);for(f=0;f<p;++f){m=t[f];if(typeof m==="number"){A=o*m*a/1e3;this.ctx.translate(A,0);s.x+=A*c;continue}const n=(m.isSpace?h:0)+l;const r=i.charProcOperatorList[m.operatorListId];if(!r){warn(`Type3 character "${m.operatorListId}" is not available.`);continue}if(this.contentVisible){this.processingType3=m;this.save();e.scale(a,a);e.transform(...d);this.executeOperatorList(r);this.restore()}const u=Util.applyTransform([m.width,0],d);b=u[0]*a+n;e.translate(b,0);s.x+=b*c}e.restore();this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,a){this.ctx.rect(s,i,n-s,a-i);this.ctx.clip();this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1];const i=this.baseTransform||getCurrentTransform(this.ctx);const n={createCanvasGraphics:t=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=true}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=true}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,s);this.current.patternStroke=false}
3setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=false}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,s);this.current.patternFill=false}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=false}_getPattern(t,e=null){let s;if(this.cachedPatterns.has(t))s=this.cachedPatterns.get(t);else{s=getShadingPattern(this.getObject(t));this.cachedPatterns.set(t,s)}e&&(s.matrix=e);return s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,getCurrentTransformInverse(e),R.SHADING);const i=getCurrentTransformInverse(e);if(i){const{width:t,height:s}=e.canvas;const[n,a,r,o]=Util.getAxialAlignedBoundingBox([0,0,t,s],i);this.ctx.fillRect(n,a,r-n,o-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0];const s=e[3]-e[1];this.ctx.rect(e[0],e[1],t,s);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const s=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let i=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];i=Util.intersect(i,n)||[0,0,0,0];const a=Math.floor(i[0]);const r=Math.floor(i[1]);const o=Math.max(Math.ceil(i[2])-a,1);const l=Math.max(Math.ceil(i[3])-r,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(h,o,l);const d=c.context;d.translate(-a,-r);d.transform(...s);if(t.smask)this.smaskStack.push({canvas:c.canvas,context:d,offsetX:a,offsetY:r,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(a,r);e.save()}copyCtxState(e,d);this.ctx=d;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx;const s=this.groupStack.pop();this.ctx=s;this.ctx.imageSmoothingEnabled=false;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const s=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(s)}}beginAnnotation(t,e,s,i,n){this.#Ps();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const i=e[2]-e[0];const a=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice();s[4]-=e[0];s[5]-=e[1];e=e.slice();e[0]=e[1]=0;e[2]=i;e[3]=a;const[n,r]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx));const{viewportScale:o}=this;const l=Math.ceil(i*this.outputScaleX*o);const h=Math.ceil(a*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:c,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(t,c);this.annotationCanvas.savedCtx=this.ctx;this.ctx=d;this.ctx.save();this.ctx.setTransform(n,0,0,-r,0,a*r);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],i,a);this.ctx.clip();this.ctx.beginPath()}}
3this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...s);this.transform(...i)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#Is();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t);t.count=e;const s=this.ctx;const i=this.processingType3;if(i){i.compiled===void 0&&(i.compiled=compileType3Glyph(t));if(i.compiled){i.compiled(s);return}}const n=this._createMaskCanvas(t);const a=n.canvas;s.save();s.setTransform(1,0,0,1,0,0);s.drawImage(a,n.offsetX,n.offsetY);s.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,a){if(!this.contentVisible)return;t=this.getObject(t.data,t);const r=this.ctx;r.save();const o=getCurrentTransform(r);r.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);r.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=a.length;t<h;t+=2){const h=Util.transform(o,[e,s,i,n,a[t],a[t+1]]);const[c,d]=Util.applyTransform([0,0],h);r.drawImage(l.canvas,c,d)}r.restore();this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx;const s=this.current.fillColor;const i=this.current.patternFill;for(const n of t){const{data:t,width:a,height:r,transform:o}=n;const l=this.cachedCanvases.getCanvas("maskCanvas",a,r);const h=l.context;h.save();const c=this.getObject(t,n);putBinaryImageMask(h,c);h.globalCompositeOperation="source-in";h.fillStyle=i?s.getPattern(h,this,getCurrentTransformInverse(e),R.FILL):s;h.fillRect(0,0,a,r);h.restore();e.save();e.transform(...o);e.scale(1,-1);drawImageAtIntegerCoords(e,l.canvas,0,0,a,r,0,-1,1,1);e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);e?this.paintInlineImageXObject(e):warn("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){warn("Dependent image isn't ready yet");return}const a=n.width;const r=n.height;const o=[];for(let t=0,n=i.length;t<n;t+=2)o.push({transform:[e,0,0,s,i[t],i[t+1]],x:0,y:0,w:a,h:r});this.paintInlineImageXObjectGroup(n,o)}applyTransferMapsToCanvas(t){if(this.current.transferMaps!=="none"){t.filter=this.current.transferMaps;t.drawImage(t.canvas,0,0);t.filter="none"}return t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t;const n=this.cachedCanvases.getCanvas("inlineImage",s,i);const a=n.context;a.filter=this.current.transferMaps;a.drawImage(e,0,0);a.filter="none";return n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width;const i=t.height;const n=this.ctx;this.save();if(!s){const{filter:t}=n;t!=="none"&&t!==""&&(n.filter="none")}n.scale(1/e,-1/i);let a;if(t.bitmap)a=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement==="function"&&t instanceof HTMLElement||!t.data)a=t;else{const s=this.cachedCanvases.getCanvas("inlineImage",e,i);const n=s.context;putBinaryImageData(n,t);a=this.applyTransferMapsToCanvas(n)}const r=this._scaleImage(a,getCurrentTransformInverse(n));n.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(n),t.interpolate);drawImageAtIntegerCoords(n,r.img,0,0,r.paintWidth,r.paintHeight,0,-i,e,i);this.compose();this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const e=t.width;const s=t.height;const n=this.cachedCanvases.getCanvas("inlineImage",e,s);const a=n.context;putBinaryImageData(a,t);i=this.applyTransferMapsToCanvas(a)}for(const t of e){s.save();s.transform(...t.transform);s.scale(1,-1);drawImageAtIntegerCoords(s,i,t.x,t.y,t.w,t.h,0,-1,1,1);s.restore()}this.compose()}paintSolidColorImageMask(){if(this.contentVisible){this.ctx.fillRect(0,0,1,1);this.compose()}}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:true})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:true});this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop();this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath();this.pendingClip||this.compose(t);const s=this.ctx;if(this.pendingClip){e||(this.pendingClip===$?s.clip("evenodd"):s.clip());this.pendingClip=null}this.current.startNewPathAndClipBox(this.current.clipBox);s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=getCurrentTransform(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]);const s=Math.hypot(t[0],t[2]);const i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current;const{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let a,r;if(s===0&&i===0){const s=Math.abs(e);const i=Math.abs(n);if(s===i)if(t===0)a=r=1/s;else{const e=s*t;a=r=e<1?1/e:1}else if(t===0){a=1/s;r=1/i}else{const e=s*t;const n=i*t;a=e<1?1/e:1;r=n<1?1/n:1}}else{const o=Math.abs(e*n-s*i);const l=Math.hypot(e,s);const h=Math.hypot(i,n);if(t===0){a=h/o;r=l/o}else{const e=t*o;a=h>e?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this;const{lineWidth:s}=this.current;const[i,n]=this.getScaleForStroking();e.lineWidth=s||1;if(i===1&&n===1){e.stroke();return}const a=e.getLineDash();t&&e.save();e.scale(i,n);if(a.length>0){const t=Math.max(i,n);e.setLineDash(a.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();
3t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return false;return true}}for(const t in b)CanvasGraphics.prototype[t]!==void 0&&(CanvasGraphics.prototype[b[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#Rs=null;static#Ls="";static get workerPort(){return this.#Rs}static set workerPort(t){if(!(typeof Worker!=="undefined"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#Rs=t}static get workerSrc(){return this.#Ls}static set workerSrc(t){if(typeof t!=="string")throw new Error("Invalid `workerSrc` type.");this.#Ls=t}}class Metadata{#Fs;#Os;constructor({parsedData:t,rawData:e}){this.#Fs=t;this.#Os=e}getRaw(){return this.#Os}get(t){return this.#Fs.get(t)??null}getAll(){return objectFromMap(this.#Fs)}has(t){return this.#Fs.has(t)}}const W=Symbol("INTERNAL");class OptionalContentGroup{#Ns=false;#Bs=false;#Us=false;#Hs=true;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#Ns=!!(t&r.DISPLAY);this.#Bs=!!(t&r.PRINT);this.name=e;this.intent=s;this.usage=i;this.rbGroups=n}get visible(){if(this.#Us)return this.#Hs;if(!this.#Hs)return false;const{print:t,view:e}=this.usage;return this.#Ns?e?.viewState!=="OFF":!this.#Bs||t?.printState!=="OFF"}_setVisible(t,e,s=false){t!==W&&unreachable("Internal method `_setVisible` called.");this.#Us=s;this.#Hs=e}}class OptionalContentConfig{#zs=null;#Gs=new Map;#Vs=null;#$s=null;constructor(t,e=r.DISPLAY){this.renderingIntent=e;this.name=null;this.creator=null;if(t!==null){this.name=t.name;this.creator=t.creator;this.#$s=t.order;for(const s of t.groups)this.#Gs.set(s.id,new OptionalContentGroup(e,s));if(t.baseState==="OFF")for(const t of this.#Gs.values())t._setVisible(W,false);for(const e of t.on)this.#Gs.get(e)._setVisible(W,true);for(const e of t.off)this.#Gs.get(e)._setVisible(W,false);this.#Vs=this.getHash()}}#Ws(t){const e=t.length;if(e<2)return true;const s=t[0];for(let i=1;i<e;i++){const e=t[i];let n;if(Array.isArray(e))n=this.#Ws(e);else{if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return true}n=this.#Gs.get(e).visible}switch(s){case"And":if(!n)return false;break;case"Or":if(n)return true;break;case"Not":return!n;default:return true}}return s==="And"}isVisible(t){if(this.#Gs.size===0)return true;if(!t){info("Optional content group not defined.");return true}if(t.type==="OCG"){if(!this.#Gs.has(t.id)){warn(`Optional content group not found: ${t.id}`);return true}return this.#Gs.get(t.id).visible}if(t.type==="OCMD"){if(t.expression)return this.#Ws(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return true}if(this.#Gs.get(e).visible)return true}return false}if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return true}if(!this.#Gs.get(e).visible)return false}return true}if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return true}if(!this.#Gs.get(e).visible)return true}return false}if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#Gs.has(e)){warn(`Optional content group not found: ${e}`);return true}if(this.#Gs.get(e).visible)return false}return true}warn(`Unknown optional content policy ${t.policy}.`);return true}warn(`Unknown group type ${t.type}.`);return true}setVisibility(t,e=true,s=true){const i=this.#Gs.get(t);if(i){if(s&&e&&i.rbGroups.length)for(const e of i.rbGroups)for(const s of e)s!==t&&this.#Gs.get(s)?._setVisible(W,false,true);i._setVisible(W,!!e,true);this.#zs=null}else warn(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const t=this.#Gs.get(i);if(t)switch(s){case"ON":this.setVisibility(i,true,e);break;case"OFF":this.setVisibility(i,false,e);break;case"Toggle":this.setVisibility(i,!t.visible,e);break}}this.#zs=null}get hasInitialVisibility(){return this.#Vs===null||this.getHash()===this.#Vs}getOrder(){return this.#Gs.size?this.#$s?this.#$s.slice():[...this.#Gs.keys()]:null}getGroups(){return this.#Gs.size>0?objectFromMap(this.#Gs):null}getGroup(t){return this.#Gs.get(t)||null}getHash(){if(this.#zs!==null)return this.#zs;const t=new MurmurHash3_64;
3for(const[e,s]of this.#Gs)t.update(`${e}:${s.visible}`);return this.#zs=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=false,disableStream:s=false}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:a,contentDispositionFilename:r}=t;this._queuedChunks=[];this._progressiveDone=a;this._contentDispositionFilename=r;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!s;this._isRangeSupported=!e;this._contentLength=i;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const e=this._rangeReaders.some((function(e){if(e._begin!==t)return false;e._enqueue(s);return true}));assert(e,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=true}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,s=false,i=null){this._stream=t;this._done=s||false;this._filename=isPdfFile(i)?i:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){const e=this._requests.shift();e.resolve({value:t,done:false})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){const t=this._queuedChunks.shift();return{value:t,done:false}}if(this._done)return{value:void 0,done:true};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=true;for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0}progressiveDone(){this._done||(this._done=true)}}class PDFDataTransportStreamRangeReader{constructor(t,e,s){this._stream=t;this._begin=e;this._end=s;this._queuedChunk=null;this._requests=[];this._done=false;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{const e=this._requests.shift();e.resolve({value:t,done:false});for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0}this._done=true;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return false}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:false}}if(this._done)return{value:void 0,done:true};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=true;for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0;this._stream._removeRangeReader(this)}}function getFilenameFromContentDispositionHeader(t){let e=true;let s=toParamRegExp("filename\\*","i").exec(t);if(s){s=s[1];let t=rfc2616unquote(s);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}
3s=rfc2231getparam(t);if(s){const t=rfc2047decode(s);return fixupEncoding(t)}s=toParamRegExp("filename","i").exec(t);if(s){s=s[1];let t=rfc2616unquote(s);t=rfc2047decode(t);return fixupEncoding(t)}function toParamRegExp(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function textdecode(t,s){if(t){if(!/^[\x00-\xFF]+$/.test(s))return s;try{const i=new TextDecoder(t,{fatal:true});const n=stringToBytes(s);s=i.decode(n);e=false}catch{}}return s}function fixupEncoding(t){if(e&&/[\x80-\xff]/.test(t)){t=textdecode("utf-8",t);e&&(t=textdecode("iso-8859-1",t))}return t}function rfc2231getparam(t){const e=[];let s;const i=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");while((s=i.exec(t))!==null){let[,t,i,n]=s;t=parseInt(t,10);if(t in e){if(t===0)break}else e[t]=[i,n]}const n=[];for(let t=0;t<e.length;++t){if(!(t in e))break;let[s,i]=e[t];i=rfc2616unquote(i);if(s){i=unescape(i);t===0&&(i=rfc5987decode(i))}n.push(i)}return n.join("")}function rfc2616unquote(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const s=e[t].indexOf('"');if(s!==-1){e[t]=e[t].slice(0,s);e.length=t+1}e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function rfc5987decode(t){const e=t.indexOf("'");if(e===-1)return t;const s=t.slice(0,e);const i=t.slice(e+1);const n=i.replace(/^[^']*'/,"");return textdecode(s,n)}function rfc2047decode(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(t,e,s,i){if(s==="q"||s==="Q"){i=i.replaceAll("_"," ");i=i.replaceAll(/=([0-9a-fA-F]{2})/g,(function(t,e){return String.fromCharCode(parseInt(e,16))}));return textdecode(e,i)}try{i=atob(i)}catch{}return textdecode(e,i)}))}return""}function createHeaders(t,e){const s=new Headers;if(!t||!e||typeof e!=="object")return s;for(const t in e){const i=e[t];i!==void 0&&s.append(t,i)}return s}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:s,disableRange:i}){const n={allowRangeRequests:false,suggestedLength:void 0};const a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return n;n.suggestedLength=a;if(a<=2*s)return n;if(i||!e)return n;if(t.get("Accept-Ranges")!=="bytes")return n;const r=t.get("Content-Encoding")||"identity";if(r!=="identity")return n;n.allowRangeRequests=true;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=getFilenameFromContentDispositionHeader(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(isPdfFile(t))return t}return null}function createResponseError(t,e){return new ResponseException(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t,t===404||t===0&&e.startsWith("file:"))}function validateResponseStatus(t){return t===200||t===206}function createFetchOptions(t,e,s){return{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;warn(`getArrayBuffer - unexpected data format: ${t}`);return new Uint8Array(t).buffer}class PDFFetchStream{_responseOrigin=null;constructor(t){this.source=t;this.isHttp=/^https?:/i.test(t.url);this.headers=createHeaders(this.isHttp,t.httpHeaders);this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once.");this._fullRequestReader=new PDFFetchStreamReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new PDFFetchStreamRangeReader(this,t,e);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFFetchStreamReader{constructor(t){this._stream=t;this._reader=null;this._loaded=0;this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||false;this._contentLength=e.length;this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||false;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=true);this._abortController=new AbortController;this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers);const i=e.url;fetch(i,createFetchOptions(s,this._withCredentials,this._abortController)).then((e=>{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseError(e.status,i);this._reader=e.body.getReader();this._headersCapability.resolve();const s=e.headers;const{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(s);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:false}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,s){this._stream=t;this._reader=null;this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||false;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!i.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const a=i.url;fetch(a,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const s=getResponseOrigin(e.url);if(s!==t._responseOrigin)throw new Error(`Expected range response-origin "${s}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseError(e.status,a);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:false}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}const j=200;const q=206;function network_getArrayBuffer(t){const e=t.response;return typeof e!=="string"?e:stringToBytes(e).buffer}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=s||false;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest;const s=this.currXhrId++;const i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,s]of this.headers)e.setRequestHeader(t,s);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);i.expectedStatus=q}else i.expectedStatus=j;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,s);e.onprogress=this.onProgress.bind(this,s);i.onHeadersReceived=t.onHeadersReceived;i.onDone=t.onDone;i.onError=t.onError;i.onProgress=t.onProgress;e.send(null);return s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived){s.onHeadersReceived();delete s.onHeadersReceived}if(i.readyState!==4)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||j;const a=n===j&&s.expectedStatus===q;if(!a&&n!==s.expectedStatus){s.onError(i.status);return}
3const r=network_getArrayBuffer(i);if(n===q){const t=i.getResponseHeader("Content-Range");const e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)s.onDone({begin:parseInt(e[1],10),chunk:r});else{warn('Missing or invalid "Content-Range" header.');s.onError(0)}}else r?s.onDone({begin:0,chunk:r}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const s=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);s.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||false;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=true);this._isStreamingSupported=false;this._isRangeSupported=false;this._cachedChunks=[];this._requests=[];this._done=false;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId;const e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const s=e.getAllResponseHeaders();const i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...s]=t.split(": ");return[e,s.join(": ")]})):[]);const{allowRangeRequests:n,suggestedLength:a}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=true);this._contentLength=a||this._contentLength;this._filename=extractFilenameFromHeader(i);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){const e=this._requests.shift();e.resolve({value:t.chunk,done:false})}else this._cachedChunks.push(t.chunk);this._done=true;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0}}_onError(t){this._storedError=createResponseError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){const t=this._cachedChunks.shift();return{value:t,done:false}}if(this._done)return{value:void 0,done:true};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=true;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest
3(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,s){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=false;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){const t=this._requests.shift();t.resolve({value:e,done:false})}else this._queuedChunk=e;this._done=true;for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return false}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:false}}if(this._done)return{value:void 0,done:true};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=true;for(const t of this._requests)t.resolve({value:void 0,done:true});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const X=/^[a-z][a-z0-9\-+.]+:/i;function parseUrlOrPath(t){if(X.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}class PDFNodeStream{constructor(t){this.source=t;this.url=parseUrlOrPath(t.url);assert(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=false;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||false;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=true);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(s.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{t.code==="ENOENT"&&(t=createResponseError(0,this._url.href));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:true};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(t===null){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});const e=new Uint8Array(t).buffer;return{value:e,done:false}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=true;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,s){this._url=t.url;this._done=false;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:true};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(t===null){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});const e=new Uint8Array(t).buffer;return{value:e,done:false}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=true;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const K=1e5;const Y=30;
3class TextLayer{#js=Promise.withResolvers();#mt=null;#qs=false;#Xs=!!globalThis.FontInspector?.enabled;#Ks=null;#Ys=null;#Qs=0;#Js=0;#Zs=null;#ti=null;#ei=0;#si=0;#ii=Object.create(null);#ni=[];#ai=null;#ri=[];#oi=new WeakMap;#li=null;static#hi=new Map;static#ci=new Map;static#di=new WeakMap;static#ui=null;static#pi=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#ai=t;else{if(typeof t!=="object")throw new Error('No "textContentSource" parameter specified.');this.#ai=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#mt=this.#ti=e;this.#si=s.scale*OutputScale.pixelRatio;this.#ei=s.rotation;this.#Ys={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:a,pageY:r}=s.rawDims;this.#li=[1,0,0,-1,-a,r+n];this.#Js=i;this.#Qs=n;TextLayer.#gi();setLayerDimensions(e,s);this.#js.promise.finally((()=>{TextLayer.#pi.delete(this);this.#Ys=null;this.#ii=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Zs.read().then((({value:t,done:e})=>{if(e)this.#js.resolve();else{this.#Ks??=t.lang;Object.assign(this.#ii,t.styles);this.#fi(t.items);pump()}}),this.#js.reject)};this.#Zs=this.#ai.getReader();TextLayer.#pi.add(this);pump();return this.#js.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*OutputScale.pixelRatio;const i=t.rotation;if(i!==this.#ei){e?.();this.#ei=i;setLayerDimensions(this.#ti,{rotation:i})}if(s!==this.#si){e?.();this.#si=s;const t={div:null,properties:null,ctx:TextLayer.#mi(this.#Ks)};for(const e of this.#ri){t.properties=this.#oi.get(e);t.div=e;this.#bi(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Zs?.cancel(t).catch((()=>{}));this.#Zs=null;this.#js.reject(t)}get textDivs(){return this.#ri}get textContentItemsStr(){return this.#ni}#fi(t){if(this.#qs)return;this.#Ys.ctx??=TextLayer.#mi(this.#Ks);const e=this.#ri,s=this.#ni;for(const i of t){if(e.length>K){warn("Ignoring additional textDivs for performance reasons.");this.#qs=true;return}if(i.str!==void 0){s.push(i.str);this.#Ai(i)}else if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const t=this.#mt;this.#mt=document.createElement("span");this.#mt.classList.add("markedContent");i.id!==null&&this.#mt.setAttribute("id",`${i.id}`);t.append(this.#mt)}else i.type==="endMarkedContent"&&(this.#mt=this.#mt.parentNode)}}#Ai(t){const e=document.createElement("span");const s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#ri.push(e);const i=Util.transform(this.#li,t.transform);let n=Math.atan2(i[1],i[0]);const a=this.#ii[t.fontName];a.vertical&&(n+=Math.PI/2);let r=this.#Xs&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(i[2],i[3]);const l=o*TextLayer.#wi(r,a,this.#Ks);let h,c;if(n===0){h=i[4];c=i[5]-l}else{h=i[4]+l*Math.sin(n);c=i[5]-l*Math.cos(n)}const d="calc(var(--total-scale-factor) *";const u=e.style;if(this.#mt===this.#ti){u.left=`${(100*h/this.#Js).toFixed(2)}%`;u.top=`${(100*c/this.#Qs).toFixed(2)}%`}else{u.left=`${d}${h.toFixed(2)}px)`;u.top=`${d}${c.toFixed(2)}px)`}u.fontSize=`${d}${(TextLayer.#ui*o).toFixed(2)}px)`;u.fontFamily=r;s.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Xs&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);n!==0&&(s.angle=n*(180/Math.PI));let p=false;if(t.str.length>1)p=true;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),s=Math.abs(t.transform[3]);e!==s&&Math.max(e,s)/Math.min(e,s)>1.5&&(p=true)}p&&(s.canvasWidth=a.vertical?t.height:t.width);this.#oi.set(e,s);this.#Ys.div=e;this.#Ys.properties=s;this.#bi(this.#Ys);s.hasText&&this.#mt.append(e);if(s.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#mt.append(t)}}#bi(t){const{div:e,properties:s,ctx:i}=t;const{style:n}=e;let a="";TextLayer.#ui>1&&(a=`scale(${1/TextLayer.#ui})`);
3if(s.canvasWidth!==0&&s.hasText){const{fontFamily:t}=n;const{canvasWidth:r,fontSize:o}=s;TextLayer.#vi(i,o*this.#si,t);const{width:l}=i.measureText(e.textContent);l>0&&(a=`scaleX(${r*this.#si/l}) ${a}`)}s.angle!==0&&(a=`rotate(${s.angle}deg) ${a}`);a.length>0&&(n.transform=a)}static cleanup(){if(!(this.#pi.size>0)){this.#hi.clear();for(const{canvas:t}of this.#ci.values())t.remove();this.#ci.clear()}}static#mi(t=null){let e=this.#ci.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement";s.lang=t;document.body.append(s);e=s.getContext("2d",{alpha:false,willReadFrequently:true});this.#ci.set(t,e);this.#di.set(e,{size:0,family:""})}return e}static#vi(t,e,s){const i=this.#di.get(t);if(e!==i.size||s!==i.family){t.font=`${e}px ${s}`;i.size=e;i.family=s}}static#gi(){if(this.#ui!==null)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ui=t.getBoundingClientRect().height;t.remove()}static#wi(t,e,s){const i=this.#hi.get(t);if(i)return i;const n=this.#mi(s);n.canvas.width=n.canvas.height=Y;this.#vi(n,Y,t);const a=n.measureText("");const r=a.fontBoundingBoxAscent;const o=Math.abs(a.fontBoundingBoxDescent);n.canvas.width=n.canvas.height=0;let l=.8;if(r)l=r/(r+o);else{util_FeatureTest.platform.isFirefox&&warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");
3e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)}this.#hi.set(t,l);return l}}class XfaText{static textContent(t){const e=[];const s={items:e,styles:Object.create(null)};function walk(t){if(!t)return;let s=null;const i=t.name;if(i==="#text")s=t.value;else{if(!XfaText.shouldBuildText(i))return;t?.attributes?.textContent?s=t.attributes.textContent:t.value&&(s=t.value)}s!==null&&e.push({str:s});if(t.children)for(const e of t.children)walk(e)}walk(t);return s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Q=65536;const J=100;function getDocument(t={}){typeof t==="string"||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new PDFDocumentLoadingTask;const{docId:i}=e;const n=t.url?getUrlProp(t.url):null;const a=t.data?getDataProp(t.data):null;const r=t.httpHeaders||null;const o=t.withCredentials===true;const l=t.password??null;const h=t.range instanceof PDFDataRangeTransport?t.range:null;const c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Q;let d=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity;const p=typeof t.docBaseUrl!=="string"||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl;const g=getFactoryUrlProp(t.cMapUrl);const f=t.cMapPacked!==false;const m=t.CMapReaderFactory||(s?NodeCMapReaderFactory:DOMCMapReaderFactory);const b=getFactoryUrlProp(t.iccUrl);const A=getFactoryUrlProp(t.standardFontDataUrl);const w=t.StandardFontDataFactory||(s?NodeStandardFontDataFactory:DOMStandardFontDataFactory);const v=getFactoryUrlProp(t.wasmUrl);const y=t.WasmFactory||(s?NodeWasmFactory:DOMWasmFactory);const E=t.stopAtErrors!==true;const _=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1;const x=t.isEvalSupported!==false;const S=typeof t.isOffscreenCanvasSupported==="boolean"?t.isOffscreenCanvasSupported:!s;const C=typeof t.isImageDecoderSupported==="boolean"?t.isImageDecoderSupported:!s&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome);const T=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1;const M=typeof t.disableFontFace==="boolean"?t.disableFontFace:s;const D=t.fontExtraProperties===true;const P=t.enableXfa===true;const I=t.ownerDocument||globalThis.document;const k=t.disableRange===true;const R=t.disableStream===true;const L=t.disableAutoFetch===true;const F=t.pdfBug===true;const O=t.CanvasFactory||(s?NodeCanvasFactory:DOMCanvasFactory);const N=t.FilterFactory||(s?NodeFilterFactory:DOMFilterFactory);const B=t.enableHWA===true;const U=t.useWasm!==false;const H=h?h.length:t.length??NaN;const z=typeof t.useSystemFonts==="boolean"?t.useSystemFonts:!s&&!M;const G=typeof t.useWorkerFetch==="boolean"?t.useWorkerFetch:!!(m===DOMCMapReaderFactory&&w===DOMStandardFontDataFactory&&y===DOMWasmFactory&&g&&A&&v&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(A,document.baseURI)&&isValidFetchUrl(v,document.baseURI));const V=null;setVerbosityLevel(u);const $={canvasFactory:new O({ownerDocument:I,enableHWA:B}),filterFactory:new N({docId:i,ownerDocument:I}),cMapReaderFactory:G?null:new m({baseUrl:g,isCompressed:f}),standardFontDataFactory:G?null:new w({baseUrl:A}),wasmFactory:G?null:new y({baseUrl:v})};if(!d){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};d=t.port?PDFWorker.fromPort(t):new PDFWorker(t);e._worker=d}const W={docId:i,apiVersion:"5.0.375",data:a,password:l,disableAutoFetch:L,rangeChunkSize:c,length:H,docBaseUrl:p,enableXfa:P,evaluatorOptions:{maxImageSize:_,disableFontFace:M,ignoreErrors:E,isEvalSupported:x,isOffscreenCanvasSupported:S,isImageDecoderSupported:C,canvasMaxAreaInBytes:T,fontExtraProperties:D,useSystemFonts:z,useWasm:U,useWorkerFetch:G,cMapUrl:g,iccUrl:b,standardFontDataUrl:A,wasmUrl:v}};const j={ownerDocument:I,pdfBug:F,styleElement:V,loadingParams:{disableAutoFetch:L,enableXfa:P}};d.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const t=d.messageHandler.sendWithPromise("GetDocRequest",W,a?[a.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:k,disableStream:R});else if(!a){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;
3if(s)if(isValidFetchUrl(n)){if(typeof fetch==="undefined"||typeof Response==="undefined"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:H,httpHeaders:r,withCredentials:o,rangeChunkSize:c,disableRange:k,disableStream:R})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const s=new MessageHandler(i,t,d.port);const n=new WorkerTransport(s,e,l,j,$);e._transport=n;s.send("Ready",null)}))})).catch(e._capability.reject);return e}function getUrlProp(t){if(t instanceof URL)return t.href;if(typeof t==="string"){if(s)return t;const e=URL.parse(t,window.location);if(e)return e.href}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function getDataProp(t){if(s&&typeof Buffer!=="undefined"&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if(typeof t==="string")return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof t==="object"&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function getFactoryUrlProp(t){if(typeof t!=="string")return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const isRefProxy=t=>typeof t==="object"&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0;const isNameProxy=t=>typeof t==="object"&&typeof t?.name==="string";const Z=_isValidExplicitDest.bind(null,isRefProxy,isNameProxy);class PDFDocumentLoadingTask{static#ms=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ms++;this.destroyed=false;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=true;try{this._worker?.port&&(this._worker._pendingDestroy=true);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,s=false,i=null){this.length=t;this.initialData=e;this.progressiveDone=s;this.contentDispositionFilename=i;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const s of this._progressListeners)s(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}
3=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=false){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#yi=false;constructor(t,e,s,i=false){this._pageIndex=t;this._pageInfo=e;this._transport=s;this._stats=i?new StatTimer:null;this._pdfBug=i;this.commonObjs=s.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=false}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=false}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=o.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:l=null,annotationCanvasMap:h=null,pageColors:c=null,printAnnotationStorage:d=null,isEditing:u=false}){this._stats?.time("Overall");const p=this._transport.getRenderingIntent(s,i,d,u);const{renderingIntent:g,cacheKey:f}=p;this.#yi=false;l||=this._transport.getOptionalContentConfig(g);let m=this._intentStates.get(f);if(!m){m=Object.create(null);this._intentStates.set(f,m)}if(m.streamReaderCancelTimeout){clearTimeout(m.streamReaderCancelTimeout);m.streamReaderCancelTimeout=null}const b=!!(g&r.PRINT);if(!m.displayReadyCapability){m.displayReadyCapability=Promise.withResolvers();m.operatorList={fnArray:[],argsArray:[],lastChunk:false,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(p)}const complete=t=>{m.renderTasks.delete(A);b&&(this.#yi=true);this.#Ei();if(t){A.capability.reject(t);this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})}else A.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}};const A=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||=new Set).add(A);const w=A.task;Promise.all([m.displayReadyCapability.promise,l]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");
3if(!(e.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");A.initializeGraphics({transparency:t,optionalContentConfig:e});A.operatorListChanged()}})).catch(complete);return w}getOperatorList({intent:t="display",annotationMode:e=o.ENABLE,printAnnotationStorage:s=null,isEditing:i=false}={}){function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(r)}}const n=this._transport.getRenderingIntent(t,e,s,i,true);let a=this._intentStates.get(n.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(n.cacheKey,a)}let r;if(!a.opListReadCapability){r=Object.create(null);r.operatorListChanged=operatorListChanged;a.opListReadCapability=Promise.withResolvers();(a.renderTasks||=new Set).add(r);a.operatorList={fnArray:[],argsArray:[],lastChunk:false,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=false,disableNormalization:e=false}={}){const s=100;return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===true,disableNormalization:e===true},{highWaterMark:s,size(t){return t.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,s){function pump(){i.read().then((function({value:e,done:s}){if(s)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),s)}const i=e.getReader();const n={items:[],styles:Object.create(null),lang:null};pump()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=true;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:true});if(!e.opListReadCapability)for(const s of e.renderTasks){t.push(s.completed);s.cancel()}}this.objs.clear();this.#yi=false;return Promise.all(t)}cleanup(t=false){this.#yi=true;const e=this.#Ei();t&&e&&(this._stats&&=new StatTimer);return e}#Ei(){if(!this.#yi||this.destroyed)return false;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return false;this._intentStates.clear();this.objs.clear();this.#yi=false;return true}_startRenderPage(t,e){const s=this._intentStates.get(e);if(s){this._stats?.timeEnd("Page Request");s.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++){e.operatorList.fnArray.push(t.fnArray[s]);e.operatorList.argsArray.push(t.argsArray[s])}e.operatorList.lastChunk=t.lastChunk;e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Ei()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:a}=s;const r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},a);const o=r.getReader();const l=this._intentStates.get(e);l.streamReader=o;const pump=()=>{o.read().then((({value:t,done:e})=>{if(e)l.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,l);pump()}}),(t=>{l.streamReader=null;if(!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=true;for(const t of l.renderTasks)t.operatorListChanged();this.#Ei()}if(l.displayReadyCapability)l.displayReadyCapability.reject(t);else{if(!l.opListReadCapability)throw t;l.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:s=false}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!s){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let s=J;e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:true})}),s);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#_i=new Map;#xi=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#xi.then((()=>{for(const[t]of this.#_i)t.call(this,s)}))}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#_i.set(e,i)}removeEventListener(t,e){const s=this.#_i.get(e);s?.();this.#_i.delete(e)}terminate(){for(const[,t]of this.#_i)t?.();this.#_i.clear()}}class PDFWorker{static#Si=0;static#Ci=false;static#Ti;static{if(s){this.#Ci=true;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{const s=URL.parse(t);if(!s?.origin||s.origin==="null")return false;const i=new URL(e,s);return s.origin===i.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:s=getVerbosityLevel()}={}){this.name=t;this.destroyed=false;this.verbosity=s;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ti?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");
3(PDFWorker.#Ti||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Mi(){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 MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Mi()}_initialize(){if(PDFWorker.#Ci||PDFWorker.#Di){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"});const s=new MessageHandler("main","worker",e);const terminateEarly=()=>{i.abort();s.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()};const i=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:i.signal});s.on("test",(t=>{i.abort();if(!this.destroyed&&t){this._messageHandler=s;this._port=e;this._webWorker=e;this.#Mi()}else terminateEarly()}));s.on("ready",(t=>{i.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Ci){warn("Setting up fake worker.");PDFWorker.#Ci=true}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const s="fake"+PDFWorker.#Si++;const i=new MessageHandler(s+"_worker",s,e);t.setup(i,e);this._messageHandler=new MessageHandler(s,s+"_worker",e);this.#Mi()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=true;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ti?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ti?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Di(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){const loader=async()=>{if(this.#Di)return this.#Di;const t=await import(this.workerSrc);return t.WorkerMessageHandler};return shadow(this,"_setupFakeWorkerGlobal",loader())}}class WorkerTransport{#Pi=new Map;#Ii=new Map;#ki=new Map;#Ri=new Map;#Li=null;constructor(t,e,s,i,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:i.ownerDocument,styleElement:i.styleElement});this.loadingParams=i.loadingParams;this._params=i;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.wasmFactory=n.wasmFactory;this.destroyed=false;this.destroyCapability=null;this._networkStream=s;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Fi(t,e=null){const s=this.#Pi.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);this.#Pi.set(t,i);return i}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=o.ENABLE,s=null,i=false,n=false){let a=r.DISPLAY;let l=P;switch(t){case"any":a=r.ANY;break;case"display":break;case"print":a=r.PRINT;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const h=a&r.PRINT&&s instanceof PrintAnnotationStorage?s:this.annotationStorage;switch(e){case o.DISABLE:a+=r.ANNOTATIONS_DISABLE;break;case o.ENABLE:break;case o.ENABLE_FORMS:a+=r.ANNOTATIONS_FORMS;break;case o.ENABLE_STORAGE:a+=r.ANNOTATIONS_STORAGE;l=h.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(a+=r.IS_EDITING);n&&(a+=r.OPLIST);const{ids:c,hash:d}=h.modifiedIds;const u=[a,l.hash,d];
3return{renderingIntent:a,cacheKey:u.join("_"),annotationStorageSerializable:l,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=true;this.destroyCapability=Promise.withResolvers();this.#Li?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ii.values())t.push(e._destroy());this.#Ii.clear();this.#ki.clear();this.#Ri.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Pi.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:s}){if(s)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:s,isRangeSupported:i,contentLength:n}=this._fullReader;if(!s||!i){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:s,isRangeSupported:i,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const s=this._networkStream.getRangeReader(t.begin,t.end);if(s){e.onPull=()=>{s.read().then((function({value:t,done:s}){if(s)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{s.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Li=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Li.reject(t):this.#Li.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Li.reject(t)}return this.#Li.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;const e=this.#Ii.get(t.pageIndex);e._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(s){case"Font":if("error"in i){const t=i.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const n=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null;const a=new FontFaceObject(i,n);this.fontLoader.bind(a).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!a.fontExtraProperties&&a.data&&(a.data=null);this.commonObjs.resolve(e,a)}));break;case"CopyLocalImage":const{imageRef:r}=i;assert(r,"The imageRef must be defined.");for(const t of this.#Ii.values())for(const[,s]of t.objs)if(s?.ref===r){if(!s.dataLen)return null;this.commonObjs.resolve(e,structuredClone(s));return s.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,i);break;default:throw new Error(`Got unknown common object type ${s}`)}return null}));t.on("obj",(([t,e,s,i])=>{if(this.destroyed)return;const n=this.#Ii.get(e);if(!n.objs.has(t))if(n._intentStates.size!==0)switch(s){case"Image":case"Pattern":n.objs.resolve(t,i);break;default:throw new Error(`Got unknown object type ${s}`)}else i?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBinaryData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \`useWorkerFetch\` parameter.`);return e.fetch(t)}))}
3getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#ki.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((s=>{if(this.destroyed)throw new Error("Transport destroyed");s.refStr&&this.#Ri.set(s.refStr,t);const i=new PDFPageProxy(e,s,this,this._params.pdfBug);this.#Ii.set(e,i);return i}));this.#ki.set(e,i);return i}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Fi("GetFieldObjects")}hasJSActions(){return this.#Fi("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!=="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Fi("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.#Fi("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Pi.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Pi.set(t,s);return s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=false){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ii.values()){const e=t.cleanup();if(!e)throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Pi.clear();this.filterFactory.destroy(true);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#Ri.get(e)??null}}const tt=Symbol("INITIAL_DATA");class PDFObjects{#Oi=Object.create(null);#Ni(t){return this.#Oi[t]||={...Promise.withResolvers(),data:tt}}get(t,e=null){if(e){const s=this.#Ni(t);s.promise.then((()=>e(s.data)));return null}const s=this.#Oi[t];if(!s||s.data===tt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#Oi[t];return!!e&&e.data!==tt}delete(t){const e=this.#Oi[t];if(!e||e.data===tt)return false;delete this.#Oi[t];return true}resolve(t,e=null){const s=this.#Ni(t);s.data=e;s.resolve()}clear(){for(const t in this.#Oi){const{data:e}=this.#Oi[t];e?.bitmap?.close()}this.#Oi=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Oi){const{data:e}=this.#Oi[t];e!==tt&&(yield[t,e])}}}class RenderTask{#Bi=null;onContinue=null;onError=null;constructor(t){this.#Bi=t}get promise(){return this.#Bi.capability.promise}cancel(t=0){this.#Bi.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Bi.operatorList;if(!t)return false;const{annotationCanvasMap:e}=this.#Bi;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ui=null;static#Hi=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=false,pdfBug:c=false,pageColors:d=null}){this.callback=t;this.params=e;this.objs=s;this.commonObjs=i;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=c;this.pageColors=d;this.running=false;this.graphicsReadyCallback=null;this.graphicsReady=false;this._useRequestAnimationFrame=h===true&&typeof window!=="undefined";this.cancelled=false;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=false,optionalContentConfig:e}){if(this.cancelled)return;
3if(this._canvas){if(InternalRenderTask.#Hi.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Hi.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:s,viewport:i,transform:n,background:a}=this.params;this.gfx=new CanvasGraphics(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=true;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=false;this.cancelled=true;this.gfx?.endDrawing();if(this.#Ui){window.cancelAnimationFrame(this.#Ui);this.#Ui=null}InternalRenderTask.#Hi.delete(this._canvas);t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e);this.callback(t);this.task.onError?.(t)}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=true;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ui=window.requestAnimationFrame((()=>{this.#Ui=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=false;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Hi.delete(this._canvas);this.callback()}}}}}const et="5.0.375";const st="23972e194";function makeColorComp(t){return Math.floor(Math.max(0,Math.min(1,t))*255).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){t=scaleAndClamp(t);return[t,t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[scaleAndClamp(1-Math.min(1,t+i)),scaleAndClamp(1-Math.min(1,s+i)),scaleAndClamp(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t;const n=1-e;const a=1-s;const r=Math.min(i,n,a);return["CMYK",i,n,a,r]}}class BaseSVGFactory{create(t,e,s=false){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");i.setAttribute("version","1.1");if(!s){i.setAttribute("width",`${t}px`);i.setAttribute("height",`${e}px`)}i.setAttribute("preserveAspectRatio","none");i.setAttribute("viewBox",`0 0 ${t} ${e}`);return i}createElement(t){if(typeof t!=="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(S,t)}}class XfaLayer{static setupStorage(t,e,s,i,n){const a=i.getValue(e,{value:null});switch(s.name){case"textarea":a.value!==null&&(t.textContent=a.value);if(n==="print")break;t.addEventListener("input",(t=>{i.setValue(e,{value:t.target.value})}));break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){a.value===s.attributes.xfaOn?t.setAttribute("checked",true):a.value===s.attributes.xfaOff&&t.removeAttribute("checked");if(n==="print")break;t.addEventListener("change",(t=>{i.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{a.value!==null&&t.setAttribute("value",a.value);if(n==="print")break;t.addEventListener("input",(t=>{i.setValue(e,{value:t.target.value})}))}break;case"select":if(a.value!==null){t.setAttribute("value",a.value);for(const t of s.children)t.attributes.value===a.value?t.attributes.selected=true:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const s=t.target.options;const n=s.selectedIndex===-1?"":s[s.selectedIndex].value;i.setValue(e,{value:n})}
3));break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:a}=e;const r=t instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(const[e,s]of Object.entries(a))if(s!==null&&s!==void 0)switch(e){case"class":s.length&&t.setAttribute(e,s.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",s);break;case"style":Object.assign(t.style,s);break;case"textContent":t.textContent=s;break;default:(!r||e!=="href"&&e!=="newWindow")&&t.setAttribute(e,s)}r&&n.addLinkAttributes(t,a.href,a.newWindow);s&&a.dataId&&this.setupStorage(t,a.dataId,e,s)}static render(t){const e=t.annotationStorage;const s=t.linkService;const i=t.xfaHtml;const n=t.intent||"display";const a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:n,linkService:s});const r=n!=="richText";const o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const t=document.createTextNode(i.value);a.append(t);r&&XfaText.shouldBuildText(i.name)&&l.push(t)}return{textDivs:l}}const h=[[i,-1,a]];while(h.length>0){const[t,i,a]=h.at(-1);if(i+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(o===null)continue;const{name:c}=o;if(c==="#text"){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);a.append(d);o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:s});if(o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(c)&&l.push(t);d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",true);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=false}}const it=1e3;const nt=9;const at=new WeakSet;class AnnotationElementFactory{static create(t){const e=t.data.annotationType;switch(e){case g.LINK:return new LinkAnnotationElement(t);case g.TEXT:return new TextAnnotationElement(t);case g.WIDGET:const e=t.data.fieldType;switch(e){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case g.POPUP:return new PopupAnnotationElement(t);case g.FREETEXT:return new FreeTextAnnotationElement(t);case g.LINE:return new LineAnnotationElement(t);case g.SQUARE:return new SquareAnnotationElement(t);case g.CIRCLE:return new CircleAnnotationElement(t);case g.POLYLINE:return new PolylineAnnotationElement(t);case g.CARET:return new CaretAnnotationElement(t);case g.INK:return new InkAnnotationElement(t);case g.POLYGON:return new PolygonAnnotationElement(t);case g.HIGHLIGHT:return new HighlightAnnotationElement(t);case g.UNDERLINE:return new UnderlineAnnotationElement(t);case g.SQUIGGLY:return new SquigglyAnnotationElement(t);case g.STRIKEOUT:return new StrikeOutAnnotationElement(t);case g.STAMP:return new StampAnnotationElement(t);case g.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#zi=null;#Gi=false;#Vi=null;constructor(t,{isRenderable:e=false,ignoreBorder:s=false,createQuadrilaterals:i=false}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(s));i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#zi||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#$i(e);this.#Vi?.popup.updateEdited(t)}resetEdited(){if(this.#zi){this.#$i(this.#zi.rect);this.#Vi?.popup.resetEdited();this.#zi=null}}#$i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:a,pageX:r,pageY:o}}}}=this;s?.splice(0,4,...t);e.left=100*(t[0]-r)/n+"%";e.top=100*(a-t[3]+o)/a+"%";if(i===0){e.width=100*(t[2]-t[0])/n+"%";e.height=100*(t[3]-t[1])/a+"%"}else this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this;const n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=it);const{style:a}=n;a.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||t===0||this.setRotation(t,n);return n}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius;const s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${s}px * var(--total-scale-factor))`;a.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${r}px * var(--total-scale-factor)) / calc(${o}px * var(--total-scale-factor))`;a.borderRadius=t}switch(e.borderStyle.style){case f.SOLID:a.borderStyle="solid";break;case f.DASHED:a.borderStyle="dashed";break;case f.BEVELED:warn("Unimplemented border style: beveled");break;case f.INSET:warn("Unimplemented border style: inset");break;case f.UNDERLINE:a.borderBottomStyle="solid";break;default:break}const i=e.borderColor||null;if(i){this.#Gi=true;a.borderColor=Util.makeHexColor(i[0]|0,i[1]|0,i[2]|0)}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]);const{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=i.rawDims;a.left=100*(l[0]-d)/h+"%";a.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;if(e.hasOwnCanvas||p===0){a.width=100*r/h+"%";a.height=100*o/c+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims;let{width:n,height:a}=this;t%180!==0&&([n,a]=[a,n]);e.style.width=100*n/s+"%";e.style.height=100*a/i+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,s)=>{const i=s.detail[t];const n=i[0];const a=i.slice(1);s.target.style[e]=ColorConverters[`${n}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail;const s=e%2===1;this.container.style.visibility=s?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:e===1||e===2})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>
3t.target.focus({preventScroll:false})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const a=s[i];if(a){const s={detail:{[i]:n},target:t};a(s);delete e[i]}}}
3_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map((t=>Math.fround(t)));if(t.length===8){const[a,r,o,l]=t.subarray(2,6);if(i===a&&n===r&&e===o&&s===l)return}const{style:a}=this.container;let r;if(this.#Gi){const{borderColor:t,borderWidth:e}=a;a.borderWidth=0;r=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${t}" stroke-width="${e}">`];this.container.classList.add("hasBorder")}const o=i-e;const l=n-s;const{svgFactory:h}=this;const c=h.createElement("svg");c.classList.add("quadrilateralsContainer");c.setAttribute("width",0);c.setAttribute("height",0);const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath");const p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");d.append(u);for(let s=2,i=t.length;s<i;s+=8){const i=t[s];const a=t[s+1];const c=t[s+2];const d=t[s+3];const p=h.createElement("rect");const g=(c-e)/o;const f=(n-a)/l;const m=(i-c)/o;const b=(a-d)/l;p.setAttribute("x",g);p.setAttribute("y",f);p.setAttribute("width",m);p.setAttribute("height",b);u.append(p);r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${f}" width="${m}" height="${b}"/>`)}if(this.#Gi){r.push("</g></svg>')");a.backgroundImage=r.join("")}this.container.append(c);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this;const e=this.#Vi=new PopupAnnotationElement({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(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:n,exportValues:a}of i){if(t===-1)continue;if(n===e)continue;const i=typeof a==="string"?a:null;const r=document.querySelector(`[data-element-id="${n}"]`);!r||at.has(r)?s.push({id:n,exportValue:i,domElement:r}):warn(`_getElementsByName - element not allowed: ${n}`)}return s}for(const i of document.getElementsByName(t)){const{exportValue:t}=i;const n=i.getAttribute("data-element-id");n!==e&&(at.has(i)&&s.push({id:n,exportValue:t,domElement:i}))}return s}show(){this.container&&(this.container.hidden=false);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=true);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:true,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:true});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this;const s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=false;if(t.url){e.addLinkAttributes(s,t.url,t.newWindow);i=true}else if(t.action){this._bindNamedAction(s,t.action);i=true}else if(t.attachment){this.#Wi(s,t.attachment,t.attachmentDest);i=true}else if(t.setOCGState){this.#ji(s,t.setOCGState);i=true}else if(t.dest){this._bindLink(s,t.dest);i=true}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(s,t);i=true}if(t.resetForm){this._bindResetFormAction(s,t.resetForm);i=true}else if(this.isTooltipOnly&&!i){this._bindLink(s,"");i=true}}
3this.container.classList.add("linkAnnotation");i&&this.container.append(s);return this.container}#qi(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return false};(e||e==="")&&this.#qi()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return false};this.#qi()}#Wi(t,e,s=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,s);return false};this.#qi()}#ji(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return false};this.#qi()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}});return false})}t.onclick||(t.onclick=()=>false);this.#qi()}_bindResetFormAction(t,e){const s=t.onclick;s||(t.href=this.linkService.getAnchorUrl(""));this.#qi();if(this._fieldObjects)t.onclick=()=>{s?.();const{fields:t,refs:i,include:n}=e;const a=[];if(t.length!==0||i.length!==0){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===n&&a.push(s)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage;const o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}case"checkbox":case"radiobutton":{const s=t.defaultValue===t.exportValues;r.setValue(e,{value:s});break}case"combobox":case"listbox":{const s=t.defaultValue||"";r.setValue(e,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${e}"]`);s&&(at.has(s)?s.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return false};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');s||(t.onclick=()=>false)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=true);t.hidden=false}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(s,(t=>{if(s==="blur"){if(!e.focused||!t.relatedTarget)return;e.focused=false}else if(s==="focus"){if(e.focused)return;e.focused=true}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(t)}})}))}_setEventListeners(t,e,s,i){for(const[n,a]of s)if(a==="Action"||this.data.actions?.[a]){a!=="Focus"&&a!=="Blur"||(e||={focused:false});this._setEventListener(t,e,n,a,i);a!=="Focus"||this.data.actions?.Blur?a!=="Blur"||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}
3_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"];const{fontColor:s}=this.data.defaultAppearanceData;const i=this.data.defaultAppearanceData.fontSize||nt;const n=t.style;let r;const o=2;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-o);const e=Math.round(t/(a*i))||1;const s=t/e;r=Math.min(i,roundToOneDecimal(s/a))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,roundToOneDecimal(t/a))}n.fontSize=`calc(${r}px * var(--total-scale-factor))`;n.color=Util.makeHexColor(s[0],s[1],s[2]);this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",true):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;
3for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=s);n.setValue(a.id,{[i]:s})}}render(){const t=this.annotationStorage;const e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&n.length>a&&(n=n.slice(0,a));let r=i.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:false};if(this.data.multiLine){s=document.createElement("textarea");s.textContent=r??n;this.data.doNotScroll&&(s.style.overflowY="hidden")}else{s=document.createElement("input");s.type=this.data.password?"password":"text";s.setAttribute("value",r??n);this.data.doNotScroll&&(s.style.overflowX="hidden")}this.data.hasOwnCanvas&&(s.hidden=true);at.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;s.name=this.data.fieldName;s.tabIndex=it;this._setRequired(s,this.data.required);a&&(s.maxLength=a);s.addEventListener("input",(i=>{t.setValue(e,{value:i.target.value});this.setPropertyOnSiblings(s,"value",i.target.value,"value");o.formattedValue=null}));s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";s.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;e!==null&&e!==void 0&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=true)}));s.addEventListener("updatefromsandbox",(s=>{this.showElementAndHideCanvas(s.target);const i={value(s){o.userValue=s.detail.value??"";t.setValue(e,{value:o.userValue.toString()});s.target.value=o.userValue},formattedValue(s){const{formattedValue:i}=s.detail;o.formattedValue=i;i!==null&&i!==void 0&&s.target!==document.activeElement&&(s.target.value=i);t.setValue(e,{formattedValue:i})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:s=>{const{charLimit:i}=s.detail;const{target:n}=s;if(i===0){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",i);let a=o.userValue;if(a&&!(a.length<=i)){a=a.slice(0,i);n.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:true,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(i,s)}));s.addEventListener("keydown",(t=>{o.commitKey=1;let s=-1;t.key==="Escape"?s=0:t.key!=="Enter"||this.data.multiLine?t.key==="Tab"&&(o.commitKey=3):s=2;if(s===-1)return;const{value:i}=t.target;if(o.lastCommittedValue!==i){o.lastCommittedValue=i;o.userValue=i;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:true,commitKey:s,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const i=blurListener;blurListener=null;s.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=false);const{value:s}=t.target;o.userValue=s;o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:true,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});i(t)}));this.data.actions?.Keystroke&&s.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:s,target:i}=t;const{value:n,selectionStart:a,selectionEnd:r}=i;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}
3case"deleteWordForward":{const t=n.substring(a).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1);break}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:s||"",willCommit:false,selStart:l,selEnd:h}})}));this._setEventListeners(s,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&s.addEventListener("blur",blurListener);if(this.data.comb){const t=this.data.rect[2]-this.data.rect[0];const e=t/a;s.classList.add("comb");s.style.letterSpacing=`calc(${e}px * var(--total-scale-factor) - 1ch)`}}else{s=document.createElement("div");s.textContent=this.data.fieldValue;s.style.verticalAlign="middle";s.style.display="table-cell";this.data.hasOwnCanvas&&(s.hidden=true)}this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage;const e=this.data;const s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;if(typeof i==="string"){i=i!=="Off";t.setValue(s,{value:i})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");at.add(n);n.setAttribute("data-element-id",s);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;i&&n.setAttribute("checked",true);n.setAttribute("exportValue",e.exportValue);n.tabIndex=it;n.addEventListener("change",(i=>{const{name:n,checked:a}=i.target;for(const i of this._getElementsByName(n,s)){const s=a&&i.exportValue===e.exportValue;i.domElement&&(i.domElement.checked=s);t.setValue(i.id,{value:s})}t.setValue(s,{value:a})}));n.addEventListener("resetform",(t=>{const s=e.defaultFieldValue||"Off";t.target.checked=s===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const i={value(e){e.target.checked=e.detail.value!=="Off";t.setValue(s,{value:e.target.checked})}};this._dispatchEventFromSandbox(i,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage;const e=this.data;const s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i==="string"){i=i!==e.buttonValue;t.setValue(s,{value:i})}if(i)for(const i of this._getElementsByName(e.fieldName,s))t.setValue(i.id,{value:false});const n=document.createElement("input");at.add(n);n.setAttribute("data-element-id",s);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;i&&n.setAttribute("checked",true);n.tabIndex=it;n.addEventListener("change",(e=>{const{name:i,checked:n}=e.target;for(const e of this._getElementsByName(i,s))t.setValue(e.id,{value:false});t.setValue(s,{value:n})}));n.addEventListener("resetform",(t=>{const s=e.defaultFieldValue;t.target.checked=s!==null&&s!==void 0&&s===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const i=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=i===e.detail.value;for(const i of this._getElementsByName(e.target.name)){const e=n&&i.id===s;i.domElement&&(i.domElement.checked=e);t.setValue(i.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}
3this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage;const e=this.data.id;const s=t.getValue(e,{value:this.data.fieldValue});const i=document.createElement("select");at.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;this._setRequired(i,this.data.required);i.name=this.data.fieldName;i.tabIndex=it;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){i.size=this.data.options.length;this.data.multiSelect&&(i.multiple=true)}i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of i.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(s.value.includes(t.exportValue)){e.setAttribute("selected",true);n=false}i.append(e)}let a=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",true);t.setAttribute("selected",true);i.prepend(t);a=()=>{t.remove();i.removeEventListener("input",a);a=null};i.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent";const{options:s,multiple:n}=i;return n?Array.prototype.filter.call(s,(t=>t.selected)).map((t=>t[e])):s.selectedIndex===-1?null:s[s.selectedIndex][e]};let r=getValue(false);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){i.addEventListener("updatefromsandbox",(s=>{const n={value(s){a?.();const n=s.detail.value;const o=new Set(Array.isArray(n)?n:[n]);for(const t of i.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(true)});r=getValue(false)},multipleSelection(t){i.multiple=true},remove(s){const n=i.options;const a=s.detail.remove;n[a].selected=false;i.remove(a);if(n.length>0){const t=Array.prototype.findIndex.call(n,(t=>t.selected));t===-1&&(n[0].selected=true)}t.setValue(e,{value:getValue(true),items:getItems(s)});r=getValue(false)},clear(s){while(i.length!==0)i.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(false)},insert(s){const{index:n,displayValue:a,exportValue:o}=s.detail.insert;const l=i.children[n];const h=document.createElement("option");h.textContent=a;h.value=o;l?l.before(h):i.append(h);t.setValue(e,{value:getValue(true),items:getItems(s)});r=getValue(false)},items(s){const{items:n}=s.detail;while(i.length!==0)i.remove(0);for(const t of n){const{displayValue:e,exportValue:s}=t;const n=document.createElement("option");n.textContent=e;n.value=s;i.append(n)}i.options.length>0&&(i.options[0].selected=true);t.setValue(e,{value:getValue(true),items:getItems(s)});r=getValue(false)},indices(s){const i=new Set(s.detail.indices);for(const t of s.target.options)t.selected=i.has(t.index);t.setValue(e,{value:getValue(true)});r=getValue(false)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,s)}));i.addEventListener("input",(s=>{const i=getValue(true);const n=getValue(false);t.setValue(e,{value:i});s.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:n,changeEx:i,willCommit:false,commitKey:1,keyDown:false}})}));this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else i.addEventListener("input",(function(s){t.setValue(e,{value:getValue(true)})}
3));this.data.combo&&this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=s;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({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});const e=[];for(const s of this.elements){s.popup=t;s.container.ariaHasPopup="dialog";e.push(s.data.id);s.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${x}${t}`)).join(","));return this.container}}class PopupElement{#Xi=this.#Ki.bind(this);#Yi=this.#Qi.bind(this);#Ji=this.#Zi.bind(this);#tn=this.#en.bind(this);#sn=null;#mt=null;#in=null;#nn=null;#an=null;#rn=null;#on=null;#ln=false;#hn=null;#T=null;#cn=null;#dn=null;#un=null;#zi=null;#pn=false;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:c}){this.#mt=t;this.#un=i;this.#in=a;this.#dn=r;this.#rn=o;this.#sn=e;this.#cn=l;this.#on=h;this.#an=s;this.#nn=PDFDateString.toDateObject(n);this.trigger=s.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#tn);t.addEventListener("mouseenter",this.#Ji);t.addEventListener("mouseleave",this.#Yi);t.classList.add("popupTriggerArea")}for(const t of s)t.container?.addEventListener("keydown",this.#Xi);this.#mt.hidden=true;c&&this.#en()}render(){if(this.#hn)return;const t=this.#hn=document.createElement("div");t.className="popup";if(this.#sn){const e=t.style.outlineColor=Util.makeHexColor(...this.#sn);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");e.append(s);({dir:s.dir,str:s.textContent}=this.#un);t.append(e);if(this.#nn){const 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.#nn.valueOf()}));e.append(t)}const i=this.#gn;if(i){XfaLayer.render({xfaHtml:i,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#in);t.append(e)}this.#mt.append(t)}get#gn(){const t=this.#dn;const e=this.#in;return!t?.str||e?.str&&e.str!==t.str?null:this.#dn.html||null}get#fn(){return this.#gn?.attributes?.style?.fontSize||0}get#mn(){return this.#gn?.attributes?.style?.color||null}#bn(t){const e=[];const s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}};const i={style:{color:this.#mn,fontSize:this.#fn?`calc(${this.#fn}px * var(--total-scale-factor))`:""}};for(const s of t.split("\n"))e.push({name:"span",value:s,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent");s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let t=0,e=i.length;t<e;++t){const n=i[t];s.append(document.createTextNode(n));t<e-1&&s.append(document.createElement("br"))}return s}#Ki(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#ln)&&this.#en()}updateEdited({rect:t,popupContent:e}){this.#zi||={contentsObj:this.#in,richText:this.#dn};t&&(this.#T=null);if(e){this.#dn=this.#bn(e);this.#in=null}this.#hn?.remove();this.#hn=null}resetEdited(){if(this.#zi){({contentsObj:this.#in,richText:this.#dn}=this.#zi);this.#zi=null;this.#hn?.remove();this.#hn=null;this.#T=null}}#An(){if(this.#T!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#rn;let a=!!this.#on;let r=a?this.#on:this.#cn;for(const t of this.#an)if(!r||Util.intersect(t.data.rect,r)!==null){r=t.data.rect;a=true;break}const o=Util.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]);const l=5;const h=a?r[2]-r[0]+l:0;const c=o[0]+h;const d=o[1];this.#T=[100*(c-i)/e,100*(d-n)/s];const{style:u}=this.#mt;u.left=`${this.#T[0]}%`;u.top=`${this.#T[1]}%`}#en(){this.#ln=!this.#ln;if(this.#ln){this.#Zi();this.#mt.addEventListener("click",this.#tn);this.#mt.addEventListener("keydown",this.#Xi)}else{this.#Qi();this.#mt.removeEventListener("click",this.#tn);this.#mt.removeEventListener("keydown",this.#Xi)}}#Zi(){this.#hn||this.render();if(this.isVisible)this.#ln&&this.#mt.classList.add("focused");else{this.#An();this.#mt.hidden=false;this.#mt.style.zIndex=parseInt(this.#mt.style.zIndex)+1e3}}#Qi(){this.#mt.classList.remove("focused");
3if(!this.#ln&&this.isVisible){this.#mt.hidden=true;this.#mt.style.zIndex=parseInt(this.#mt.style.zIndex)-1e3}}forceHide(){this.#pn=this.isVisible;this.#pn&&(this.#mt.hidden=true)}maybeShow(){if(this.#pn){this.#hn||this.#Zi();this.#pn=false;this.#mt.hidden=false}}get isVisible(){return this.#mt.hidden===false}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=h.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent");t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e;t.append(s)}this.container.append(t)}!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#wn=null;constructor(t){super(t,{isRenderable:true,ignoreBorder:true})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:s}=this;const i=this.svgFactory.create(e,s,true);const n=this.#wn=this.svgFactory.createElement("svg:line");n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);n.setAttribute("stroke-width",t.borderStyle.width||1);n.setAttribute("stroke","transparent");n.setAttribute("fill","transparent");i.append(n);this.container.append(i);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#wn}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#vn=null;constructor(t){super(t,{isRenderable:true,ignoreBorder:true})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:s}=this;const i=this.svgFactory.create(e,s,true);const n=t.borderStyle.width;const a=this.#vn=this.svgFactory.createElement("svg:rect");a.setAttribute("x",n/2);a.setAttribute("y",n/2);a.setAttribute("width",e-n);a.setAttribute("height",s-n);a.setAttribute("stroke-width",n||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");i.append(a);this.container.append(i);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#vn}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#yn=null;constructor(t){super(t,{isRenderable:true,ignoreBorder:true})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:s}=this;const i=this.svgFactory.create(e,s,true);const n=t.borderStyle.width;const a=this.#yn=this.svgFactory.createElement("svg:ellipse");a.setAttribute("cx",e/2);a.setAttribute("cy",s/2);a.setAttribute("rx",e/2-n/2);a.setAttribute("ry",s/2-n/2);a.setAttribute("stroke-width",n||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");i.append(a);this.container.append(i);!t.popupRef&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#yn}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#En=null;constructor(t){super(t,{isRenderable:true,ignoreBorder:true});this.containerClassName="polylineAnnotation";this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i},width:n,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(n,a,true);let o=[];for(let s=0,i=e.length;s<i;s+=2){const i=e[s]-t[0];const n=t[3]-e[s+1];o.push(`${i},${n}`)}o=o.join(" ");const l=this.#En=this.svgFactory.createElement(this.svgElementName);l.setAttribute("points",o);l.setAttribute("stroke-width",s.width||1);l.setAttribute("stroke","transparent");l.setAttribute("fill","transparent");r.append(l);this.container.append(r);!i&&this.hasPopupData&&this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t);this.containerClassName="polygonAnnotation";this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true})}render(){this.container.classList.add("caretAnnotation");!this.data.popupRef&&this.hasPopupData&&this._createPopup();return this.container}}
3class InkAnnotationElement extends AnnotationElement{#_n=null;#xn=[];constructor(t){super(t,{isRenderable:true,ignoreBorder:true});this.containerClassName="inkAnnotation";this.svgElementName="svg:polyline";this.annotationEditorType=this.data.it==="InkHighlight"?h.HIGHLIGHT:h.INK}#Sn(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this;const{transform:a,width:r,height:o}=this.#Sn(e,t);const l=this.svgFactory.create(r,o,true);const h=this.#_n=this.svgFactory.createElement("svg:g");l.append(h);h.setAttribute("stroke-width",i.width||1);h.setAttribute("stroke-linecap","round");h.setAttribute("stroke-linejoin","round");h.setAttribute("stroke-miterlimit",10);h.setAttribute("stroke","transparent");h.setAttribute("fill","transparent");h.setAttribute("transform",a);for(let t=0,e=s.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#xn.push(e);e.setAttribute("points",s[t].join(","));h.append(e)}!n&&this.hasPopupData&&this._createPopup();this.container.append(l);this._editOnDoubleClick();return this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t;const n=this.#_n;e>=0&&n.setAttribute("stroke-width",e||1);if(s)for(let t=0,e=this.#xn.length;t<e;t++)this.#xn[t].setAttribute("points",s[t].join(","));if(i){const{transform:t,width:e,height:s}=this.#Sn(this.data.rotation,i);const a=n.parentElement;a.setAttribute("viewBox",`0 0 ${e} ${s}`);n.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#xn}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true,createQuadrilaterals:true});this.annotationEditorType=h.HIGHLIGHT}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("highlightAnnotation");this._editOnDoubleClick();return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true,createQuadrilaterals:true})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("underlineAnnotation");return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true,createQuadrilaterals:true})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("squigglyAnnotation");return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true,createQuadrilaterals:true})}render(){!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.classList.add("strikeoutAnnotation");return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:true,ignoreBorder:true});this.annotationEditorType=h.STAMP}render(){this.container.classList.add("stampAnnotation");this.container.setAttribute("role","img");!this.data.popupRef&&this.hasPopupData&&this._createPopup();this._editOnDoubleClick();return this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#Cn=null;constructor(t){super(t,{isRenderable:true});const{file:e}=this.data;this.filename=e.filename;this.content=e.content;this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;if(e.hasAppearance||e.fillAlpha===0)s=document.createElement("div");else{s=document.createElement("img");s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`;e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)}s.addEventListener("dblclick",this.#Tn.bind(this));this.#Cn=s;const{isMac:i}=util_FeatureTest.platform;t.addEventListener("keydown",(t=>{t.key==="Enter"&&(i?t.metaKey:t.ctrlKey)&&this.#Tn()}));!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea");t.append(s);return t}getElementsToTriggerPopup(){return this.#Cn}addHighlightArea(){this.container.classList.add("highlightArea")}#Tn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Mn=null;#Dn=null;#Pn=new Map;#In=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:
3a,structTreeLayer:r}){this.div=t;this.#Mn=e;this.#Dn=s;this.#In=r||null;this.page=n;this.viewport=a;this.zIndex=0;this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#Pn.size>0}async#kn(t,e){const s=t.firstChild||t;const i=s.id=`${x}${e}`;const n=await(this.#In?.getAriaAttributes(i));if(n)for(const[t,e]of n)s.setAttribute(t,e);this.div.append(t);this.#Mn?.moveElementInDOM(this.div,t,s,false)}async render(t){const{annotations:e}=t;const s=this.div;setLayerDimensions(s,this.viewport);const i=new Map;const n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==false,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:t.enableScripting===true,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===g.POPUP;if(e){const e=i.get(t.id);if(!e)continue;n.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;n.data=t;const s=AnnotationElementFactory.create(n);if(!s.isRenderable)continue;if(!e&&t.popupRef){const e=i.get(t.popupRef);e?e.push(s):i.set(t.popupRef,[s])}const a=s.render();t.hidden&&(a.style.visibility="hidden");await this.#kn(a,t.id);if(s._isEditable){this.#Pn.set(s.data.id,s);this._annotationEditorUIManager?.renderAnnotationElement(s)}}this.#Rn()}async addLinkAnnotations(t,e){const s={data:null,layer:this.div,linkService:e,svgFactory:new DOMSVGFactory,parent:this};for(const e of t){e.borderStyle||=AnnotationLayer._defaultBorderStyle;s.data=e;const t=AnnotationElementFactory.create(s);if(!t.isRenderable)continue;const i=t.render();await this.#kn(i,e.id)}}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#Rn();e.hidden=false}#Rn(){if(!this.#Dn)return;const t=this.div;for(const[e,s]of this.#Dn){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s);const a=this.#Pn.get(e);if(a)if(a._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,i.id,s);a._hasNoCanvas=false}else a.canvas=s}this.#Dn.clear()}getEditableAnnotations(){return Array.from(this.#Pn.values())}getEditableAnnotation(t){return this.#Pn.get(t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:f.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const rt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#sn;#Ln="";#Fn=`${this.id}-editor`;#On=null;#fn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype;const arrowChecker=t=>t.isEmpty();const e=AnnotationEditorUIManager.TRANSLATE_SMALL;const s=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:true}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[s,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,s],checker:arrowChecker}]]))}static _type="freetext";static _editorType=h.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#sn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#fn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}
3static updateDefaultParams(t,e){switch(t){case c.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case c.FREETEXT_COLOR:FreeTextEditor._defaultColor=e;break}}updateParams(t,e){switch(t){case c.FREETEXT_SIZE:this.#Nn(e);break;case c.FREETEXT_COLOR:this.#Bn(e);break}}static get defaultPropertiesToUpdate(){return[[c.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[c.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[c.FREETEXT_SIZE,this.#fn],[c.FREETEXT_COLOR,this.#sn]]}#Nn(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#fn)*this.parentScale);this.#fn=t;this.#Un()};const e=this.#fn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:true,type:c.FREETEXT_SIZE,overwriteIfSameType:true,keepUndo:true})}#Bn(t){const setColor=t=>{this.#sn=this.editorDiv.style.color=t};const e=this.#sn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:true,type:c.FREETEXT_COLOR,overwriteIfSameType:true,keepUndo:true})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,true)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#fn)*t]}rebuild(){if(this.parent){super.rebuild();this.div!==null&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(false);this.parent.updateToolbar(h.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=true;this._isDraggable=false;this.div.removeAttribute("aria-activedescendant");this.#On=new AbortController;const t=this._uiManager.combinedSignal(this.#On);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(){if(this.isInEditMode()){this.parent.setEditingState(true);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=false;this.div.setAttribute("aria-activedescendant",this.#Fn);this._isDraggable=true;this.#On?.abort();this.#On=null;this.div.focus({preventScroll:true});this.isEditing=false;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=false;if(this.parent){this.parent.setEditingState(true);this.parent.div.classList.add("freetextEditing")}super.remove()}#Hn(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||s.nodeName!=="BR"){t.push(FreeTextEditor.#zn(s));e=s}return t.join("\n")}#Un(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this;const i=e.style.display;const n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);s=e.getBoundingClientRect();e.remove();e.style.display=i;e.classList.toggle("hidden",n)}if(this.rotation%180===this.parentRotation%180){this.width=s.width/t;this.height=s.height/e}else{this.width=s.height/t;this.height=s.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Ln;const e=this.#Ln=this.#Hn().trimEnd();if(t===e)return;const setText=t=>{this.#Ln=t;if(t){this.#Gn();this._uiManager.rebuild(this);this.#Un()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:false});this.#Un()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&t.key==="Enter"){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=true}editorDivBlur(t){this.isEditing=false}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",true)}
3render(){if(this.div)return this.div;let t,e;if(this._isCopy||this.annotationElementId){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#Fn);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=true;const{style:s}=this.editorDiv;s.fontSize=`calc(${this.#fn}px * var(--total-scale-factor))`;s.color=this.#sn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this._isCopy||this.annotationElementId){const[s,i]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions;const[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-h)/o;u=e+this.height-(n[1]-c)/l;break;case 90:d=t+(n[0]-h)/o;u=e-(n[1]-c)/l;[a,r]=[r,-a];break;case 180:d=t-this.width+(n[0]-h)/o;u=e-(n[1]-c)/l;[a,r]=[-a,-r];break;case 270:d=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-c-this.width*o)/l;[a,r]=[-r,a];break}this.setAt(d*s,u*i,a,r)}else this._moveAfterPaste(t,e);this.#Gn();this._isDraggable=true;this.editorDiv.contentEditable=false}else{this._isDraggable=false;this.editorDiv.contentEditable=true}return this.div}static#zn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(rt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData;const{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=FreeTextEditor.#Vn(e.getData("text")||"").replaceAll(rt,"\n");if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const a=n.getRangeAt(0);if(!i.includes("\n")){a.insertNode(document.createTextNode(i));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:r,startOffset:o}=a;const l=[];const h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(rt,""));if(t!==this.editorDiv){let e=l;for(const s of this.editorDiv.childNodes)s!==t?e.push(FreeTextEditor.#zn(s)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(rt,""))}else if(r===this.editorDiv){let t=l;let e=0;for(const s of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#zn(s))}}this.#Ln=`${l.join("\n")}${i}${h.join("\n")}`;this.#Gn();const c=new Range;let d=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d);c.setEnd(t,d);break}d-=e}n.removeAllRanges();n.addRange(c)}#Gn(){this.editorDiv.replaceChildren();if(this.#Ln)for(const t of this.#Ln.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#$n(){return this.#Ln.replaceAll("Â "," ")}static#Vn(t){return t.replaceAll(" ","Â ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:s},rect:n,rotation:a,id:r,popupRef:o},textContent:l,textPosition:c,parent:{page:{pageNumber:d}}}=t;if(!l||l.length===0)return null;i=t={annotationType:h.FREETEXT,color:Array.from(s),fontSize:e,value:l.join("\n"),position:c,pageIndex:d-1,rect:n.slice(0),rotation:a,id:r,deleted:false,popupRef:o}}const n=await super.deserialize(t,e,s);n.#fn=t.fontSize;n.#sn=Util.makeHexColor(...t.color);n.#Ln=FreeTextEditor.#Vn(t.value);n.annotationElementId=t.id||null;n._initialData=i;return n}serialize(t=false){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale;const s=this.getRect(e,e);const i=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#sn);const n={annotationType:h.FREETEXT,color:i,fontSize:this.#fn,value:this.#$n(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t){n.isCopy=true;return n}if(this.annotationElementId&&!this.#Wn(n))return null;n.id=this.annotationElementId;return n}#Wn(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some(((t,e)=>t!==i[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#fn}
3px * var(--total-scale-factor))`;s.color=this.#sn;e.replaceChildren();for(const t of this.#Ln.split("\n")){const s=document.createElement("div");s.append(t?document.createTextNode(t):document.createElement("br"));e.append(s)}const i=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(i,i),popupContent:this.#Ln});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r]*i;a[r+1]=s+t[r+1]*n}return a}static _rescaleAndSwap(t,e,s,i,n,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r+1]*i;a[r+1]=s+t[r]*n}return a}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,a=t.length;n<a;n+=2){i[n]=e+t[n];i[n+1]=s+t[n+1]}return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,a){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+a)/6,(s+n)/2,(i+a)/2]}}class FreeDrawOutliner{#jn;#qn=[];#Xn;#Kn;#Yn=[];#Qn=new Float32Array(18);#Jn;#Zn;#ta;#ea;#sa;#ia;#na=[];static#aa=8;static#ra=2;static#oa=FreeDrawOutliner.#aa+FreeDrawOutliner.#ra;constructor({x:t,y:e},s,i,n,a,r=0){this.#jn=s;this.#ia=n*i;this.#Kn=a;this.#Qn.set([NaN,NaN,NaN,NaN,t,e],6);this.#Xn=r;this.#ea=FreeDrawOutliner.#aa*i;this.#ta=FreeDrawOutliner.#oa*i;this.#sa=i;this.#na.push(t,e)}isEmpty(){return isNaN(this.#Qn[8])}#la(){const t=this.#Qn.subarray(4,6);const e=this.#Qn.subarray(16,18);const[s,i,n,a]=this.#jn;return[(this.#Jn+(t[0]-e[0])/2-s)/n,(this.#Zn+(t[1]-e[1])/2-i)/a,(this.#Jn+(e[0]-t[0])/2-s)/n,(this.#Zn+(e[1]-t[1])/2-i)/a]}add({x:t,y:e}){this.#Jn=t;this.#Zn=e;const[s,i,n,a]=this.#jn;let[r,o,l,h]=this.#Qn.subarray(8,12);const c=t-l;const d=e-h;const u=Math.hypot(c,d);if(u<this.#ta)return false;const p=u-this.#ea;const g=p/u;const f=g*c;const m=g*d;let b=r;let A=o;r=l;o=h;l+=f;h+=m;this.#na?.push(t,e);const w=-m/p;const v=f/p;const y=w*this.#ia;const E=v*this.#ia;this.#Qn.set(this.#Qn.subarray(2,8),0);this.#Qn.set([l+y,h+E],4);this.#Qn.set(this.#Qn.subarray(14,18),12);this.#Qn.set([l-y,h-E],16);if(isNaN(this.#Qn[6])){if(this.#Yn.length===0){this.#Qn.set([r+y,o+E],2);this.#Yn.push(NaN,NaN,NaN,NaN,(r+y-s)/n,(o+E-i)/a);this.#Qn.set([r-y,o-E],14);this.#qn.push(NaN,NaN,NaN,NaN,(r-y-s)/n,(o-E-i)/a)}this.#Qn.set([b,A,r,o,l,h],6);return!this.isEmpty()}this.#Qn.set([b,A,r,o,l,h],6);const _=Math.abs(Math.atan2(A-o,b-r)-Math.atan2(m,f));if(_<Math.PI/2){[r,o,l,h]=this.#Qn.subarray(2,6);this.#Yn.push(NaN,NaN,NaN,NaN,((r+l)/2-s)/n,((o+h)/2-i)/a);[r,o,b,A]=this.#Qn.subarray(14,18);this.#qn.push(NaN,NaN,NaN,NaN,((b+r)/2-s)/n,((A+o)/2-i)/a);return true}[b,A,r,o,l,h]=this.#Qn.subarray(0,6);this.#Yn.push(((b+5*r)/6-s)/n,((A+5*o)/6-i)/a,((5*r+l)/6-s)/n,((5*o+h)/6-i)/a,((r+l)/2-s)/n,((o+h)/2-i)/a);[l,h,r,o,b,A]=this.#Qn.subarray(12,18);this.#qn.push(((b+5*r)/6-s)/n,((A+5*o)/6-i)/a,((5*r+l)/6-s)/n,((5*o+h)/6-i)/a,((r+l)/2-s)/n,((o+h)/2-i)/a);return true}toSVGPath(){if(this.isEmpty())return"";const t=this.#Yn;const e=this.#qn;if(isNaN(this.#Qn[6])&&!this.isEmpty())return this.#ha();const s=[];
3s.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?s.push(`L${t[e+4]} ${t[e+5]}`):s.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#ca(s);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?s.push(`L${e[t+4]} ${e[t+5]}`):s.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#da(s);return s.join(" ")}#ha(){const[t,e,s,i]=this.#jn;const[n,a,r,o]=this.#la();return`M${(this.#Qn[2]-t)/s} ${(this.#Qn[3]-e)/i} L${(this.#Qn[4]-t)/s} ${(this.#Qn[5]-e)/i} L${n} ${a} L${r} ${o} L${(this.#Qn[16]-t)/s} ${(this.#Qn[17]-e)/i} L${(this.#Qn[14]-t)/s} ${(this.#Qn[15]-e)/i} Z`}#da(t){const e=this.#qn;t.push(`L${e[4]} ${e[5]} Z`)}#ca(t){const[e,s,i,n]=this.#jn;const a=this.#Qn.subarray(4,6);const r=this.#Qn.subarray(16,18);const[o,l,h,c]=this.#la();t.push(`L${(a[0]-e)/i} ${(a[1]-s)/n} L${o} ${l} L${h} ${c} L${(r[0]-e)/i} ${(r[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,a){return new FreeDrawOutline(t,e,s,i,n,a)}getOutlines(){const t=this.#Yn;const e=this.#qn;const s=this.#Qn;const[i,n,a,r]=this.#jn;const o=new Float32Array((this.#na?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2){o[t]=(this.#na[t]-i)/a;o[t+1]=(this.#na[t+1]-n)/r}o[o.length-2]=(this.#Jn-i)/a;o[o.length-1]=(this.#Zn-n)/r;if(isNaN(s[6])&&!this.isEmpty())return this.#ua(o);const l=new Float32Array(this.#Yn.length+24+this.#qn.length);let h=t.length;for(let e=0;e<h;e+=2)if(isNaN(t[e]))l[e]=l[e+1]=NaN;else{l[e]=t[e];l[e+1]=t[e+1]}h=this.#pa(l,h);for(let t=e.length-6;t>=6;t-=6)for(let s=0;s<6;s+=2)if(isNaN(e[t+s])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+s];l[h+1]=e[t+s+1];h+=2}this.#ga(l,h);return this.newFreeDrawOutline(l,o,this.#jn,this.#sa,this.#Xn,this.#Kn)}#ua(t){const e=this.#Qn;const[s,i,n,a]=this.#jn;const[r,o,l,h]=this.#la();const c=new Float32Array(36);c.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/a,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/a,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/a],0);return this.newFreeDrawOutline(c,t,this.#jn,this.#sa,this.#Xn,this.#Kn)}#ga(t,e){const s=this.#qn;t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e);return e+6}#pa(t,e){const s=this.#Qn.subarray(4,6);const i=this.#Qn.subarray(16,18);const[n,a,r,o]=this.#jn;const[l,h,c,d]=this.#la();t.set([NaN,NaN,NaN,NaN,(s[0]-n)/r,(s[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(i[0]-n)/r,(i[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#jn;#fa=new Float32Array(4);#Xn;#Kn;#na;#sa;#ma;constructor(t,e,s,i,n,a){super();this.#ma=t;this.#na=e;this.#jn=s;this.#sa=i;this.#Xn=n;this.#Kn=a;this.lastPoint=[NaN,NaN];this.#ba(a);const[r,o,l,h]=this.#fa;for(let e=0,s=t.length;e<s;e+=2){t[e]=(t[e]-r)/l;t[e+1]=(t[e+1]-o)/h}for(let t=0,s=e.length;t<s;t+=2){e[t]=(e[t]-r)/l;e[t+1]=(e[t+1]-o)/h}}toSVGPath(){const t=[`M${this.#ma[4]} ${this.#ma[5]}`];for(let e=6,s=this.#ma.length;e<s;e+=6)isNaN(this.#ma[e])?t.push(`L${this.#ma[e+4]} ${this.#ma[e+5]}`):t.push(`C${this.#ma[e]} ${this.#ma[e+1]} ${this.#ma[e+2]} ${this.#ma[e+3]} ${this.#ma[e+4]} ${this.#ma[e+5]}`);t.push("Z");return t.join(" ")}serialize([t,e,s,i],n){const a=s-t;const r=i-e;let o;let l;switch(n){case 0:o=Outline._rescale(this.#ma,t,i,a,-r);l=Outline._rescale(this.#na,t,i,a,-r);break;case 90:o=Outline._rescaleAndSwap(this.#ma,t,e,a,r);l=Outline._rescaleAndSwap(this.#na,t,e,a,r);break;case 180:o=Outline._rescale(this.#ma,s,e,-a,r);l=Outline._rescale(this.#na,s,e,-a,r);break;case 270:o=Outline._rescaleAndSwap(this.#ma,s,i,-a,-r);l=Outline._rescaleAndSwap(this.#na,s,i,-a,-r);break}return{outline:Array.from(o),points:[Array.from(l)]}}#ba(t){const e=this.#ma;let s=e[4];let i=e[5];let n=s;let a=i;let r=s;let o=i;let l=s;let h=i;const c=t?Math.max:Math.min;for(let t=6,d=e.length;t<d;t+=6){if(isNaN(e[t])){n=Math.min(n,e[t+4]);a=Math.min(a,e[t+5]);r=Math.max(r,e[t+4]);o=Math.max(o,e[t+5]);if(h<e[t+5]){l=e[t+4];h=e[t+5]}else h===e[t+5]&&(l=c(l,e[t+4]))}else{const d=Util.bezierBoundingBox(s,i,...e.slice(t,t+6));n=Math.min(n,d[0]);a=Math.min(a,d[1]);r=Math.max(r,d[2]);o=Math.max(o,d[3]);if(h<d[3]){l=d[2];h=d[3]}else h===d[3]&&(l=c(l,d[2]))}s=e[t+4];i=e[t+5]}const d=this.#fa;d[0]=n-this.#Xn;d[1]=a-this.#Xn;d[2]=r-n+2*this.#Xn;d[3]=o-a+2*this.#Xn;this.lastPoint=[l,h]}get box(){return this.#fa}newOutliner(t,e,s,i,n,a=0){return new FreeDrawOutliner(t,e,s,i,n,a)}getNewOutline(t,e){const[s,i,n,a]=this.#fa;const[r,o,l,h]=this.#jn;const c=n*l;const d=a*h;const u=s*l+r;const p=i*h+o;const g=this.newOutliner({x:this.#na[0]*c+u,y:this.#na[1]*d+p},this.#jn,this.#sa,t,this.#Kn,e??this.#Xn);for(let t=2;t<this.#na.length;t+=2)g.add({x:this.#na[t]*c+u,y:this.#na[t+1]*d+p});return g.getOutlines()}}class HighlightOutliner{#jn;#Aa;#wa=[];#va=[];constructor(t,e=0,s=0,i=true){let n=Infinity;let a=-Infinity;let r=Infinity;let o=-Infinity;const l=4;const h=10**-l;for(const{x:s,y:i,width:l,height:c}of t){const t=Math.floor((s-e)/h)*h;const d=Math.ceil((s+l+e)/h)*h;const u=Math.floor((i-e)/h)*h;const p=Math.ceil((i+c+e)/h)*h;const g=[t,u,p,true];const f=[d,u,p,false];this.#wa.push(g,f);n=Math.min(n,t);a=Math.max(a,d);r=Math.min(r,u);o=Math.max(o,p)}const c=a-n+2*s;const d=o-r+2*s;const u=n-s;const p=r-s;const g=this.#wa.at(i?-1:-2);const f=[g[0],g[2]];for(const t of this.#wa){const[e,s,i]=t;t[0]=(e-u)/c;t[1]=(s-p)/d;t[2]=(i-p)/d}this.#jn=new Float32Array([u,p,c,d]);this.#Aa=f}getOutlines(){this.#wa.sort(((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#wa)if(e[3]){t.push(...this.#ya(e));this.#Ea(e)}else{this.#_a(e);t.push(...this.#ya(e))}return this.#xa(t)}#xa(t){const e=[];const s=new Set;for(const s of t){const[t,i,n]=s;e.push([t,i,s],[t,n,s])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,i=e.length;t<i;t+=2){const i=e[t][2];const n=e[t+1][2];i.push(n);n.push(i);s.add(i);s.add(n)}const i=[];let n;while(s.size>0){const t=s.values().next().value;let[e,a,r,o,l]=t;s.delete(t);let h=e;let c=a;n=[e,r];i.push(n);while(true){let t;if(s.has(o))t=o;else{if(!s.has(l))break;t=l}s.delete(t);[e,a,r,o,l]=t;if(h!==e){n.push(h,c,e,c===a?a:r);h=e}c=c===a?r:a}n.push(h,c)}return new HighlightOutline(i,this.#jn,this.#Aa)}#Sa(t){const e=this.#va;let s=0;let i=e.length-1;while(s<=i){const n=s+i>>1;const a=e[n][0];if(a===t)return n;a<t?s=n+1:i=n-1}return i+1}#Ea([,t,e]){const s=this.#Sa(t);this.#va.splice(s,0,[t,e])}#_a([,t,e]){const s=this.#Sa(t);for(let i=s;i<this.#va.length;i++){const[s,n]=this.#va[i];if(s!==t)break;
3if(s===t&&n===e){this.#va.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[s,n]=this.#va[i];if(s!==t)break;if(s===t&&n===e){this.#va.splice(i,1);return}}}#ya(t){const[e,s,i]=t;const n=[[e,s,i]];const a=this.#Sa(i);for(let t=0;t<a;t++){const[s,i]=this.#va[t];for(let t=0,a=n.length;t<a;t++){const[,r,o]=n[t];if(!(i<=r||o<=s))if(r>=s)if(o>i)n[t][1]=i;else{if(a===1)return[];n.splice(t,1);t--;a--}else{n[t][2]=s;o>i&&n.push([e,i,o])}}}return n}}class HighlightOutline extends Outline{#jn;#Ca;constructor(t,e,s){super();this.#Ca=t;this.#jn=e;this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#Ca){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const a=e[n];const r=e[n+1];if(a===s){t.push(`V${r}`);i=r}else if(r===i){t.push(`H${a}`);s=a}}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const a=[];const r=s-t;const o=i-e;for(const e of this.#Ca){const s=new Array(e.length);for(let n=0;n<e.length;n+=2){s[n]=t+e[n]*r;s[n+1]=i-e[n+1]*o}a.push(s)}return a}get box(){return this.#jn}get classNamesForOutlining(){return["highlightOutline"]}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,s,i,n,a){return new FreeHighlightOutline(t,e,s,i,n,a)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,s,i,n,a=0){return new FreeHighlightOutliner(t,e,s,i,n,a)}}class ColorPicker{#Ta=null;#Ma=null;#Da;#Pa=null;#Ia=false;#ka=false;#a=null;#Ra;#La=null;#m=null;#Fa;static#Oa=null;static get _keyboardManager(){return shadow(this,"_keyboardManager",new KeyboardManager([[["Escape","mac+Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home","mac+Home"],ColorPicker.prototype._moveToBeginning],[["End","mac+End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#ka=false;this.#Fa=c.HIGHLIGHT_COLOR;this.#a=t}else{this.#ka=true;this.#Fa=c.HIGHLIGHT_DEFAULT_COLOR}this.#m=t?._uiManager||e;this.#Ra=this.#m._eventBus;this.#Da=t?.color||this.#m?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#Oa||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#Ta=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.setAttribute("aria-haspopup",true);const e=this.#m._signal;t.addEventListener("click",this.#Na.bind(this),{signal:e});t.addEventListener("keydown",this.#Ki.bind(this),{signal:e});const s=this.#Ma=document.createElement("span");s.className="swatch";s.setAttribute("aria-hidden",true);s.style.backgroundColor=this.#Da;t.append(s);return t}renderMainDropdown(){const t=this.#Pa=this.#Ba();t.setAttribute("aria-orientation","horizontal");t.setAttribute("aria-labelledby","highlightColorPickerLabel");return t}#Ba(){const t=document.createElement("div");const e=this.#m._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.className="dropdown";t.role="listbox";t.setAttribute("aria-multiselectable",false);t.setAttribute("aria-orientation","vertical");t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#m.highlightColors){const n=document.createElement("button");n.tabIndex="0";n.role="option";n.setAttribute("data-color",i);n.title=s;n.setAttribute("data-l10n-id",ColorPicker.#Oa[s]);const a=document.createElement("span");n.append(a);a.className="swatch";a.style.backgroundColor=i;n.setAttribute("aria-selected",i===this.#Da);n.addEventListener("click",this.#Ua.bind(this,i),{signal:e});t.append(n)}t.addEventListener("keydown",this.#Ki.bind(this),{signal:e});return t}#Ua(t,e){e.stopPropagation();this.#Ra.dispatch("switchannotationeditorparams",{source:this,type:this.#Fa,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#Ta){this.#Na(t);return}const e=t.target.getAttribute("data-color");e&&this.#Ua(e,t)}_moveToNext(t){this.#Ha?t.target!==this.#Ta?t.target.nextSibling?.focus():this.#Pa.firstChild?.focus():this.#Na(t)}_moveToPrevious(t){if(t.target!==this.#Pa?.firstChild&&t.target!==this.#Ta){this.#Ha||this.#Na(t);t.target.previousSibling?.focus()}else this.#Ha&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Ha?this.#Pa.firstChild?.focus():this.#Na(t)}_moveToEnd(t){this.#Ha?this.#Pa.lastChild?.focus():this.#Na(t)}#Ki(t){ColorPicker._keyboardManager.exec(this,t)}#Na(t){if(this.#Ha){this.hideDropdown();return}this.#Ia=t.detail===0;if(!this.#La){this.#La=new AbortController;window.addEventListener("pointerdown",this.#c.bind(this),{signal:this.#m.combinedSignal(this.#La)})}if(this.#Pa){this.#Pa.classList.remove("hidden");return}const e=this.#Pa=this.#Ba();this.#Ta.append(e)}#c(t){this.#Pa?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Pa?.classList.add("hidden");this.#La?.abort();this.#La=null}get#Ha(){return this.#Pa&&!this.#Pa.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#ka)if(this.#Ha){this.hideDropdown();this.#Ta.focus({preventScroll:true,focusVisible:this.#Ia})}else this.#a?.unselect()}updateColor(t){this.#Ma&&(this.#Ma.style.backgroundColor=t);if(!this.#Pa)return;const e=this.#m.highlightColors.values();for(const s of this.#Pa.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#Ta?.remove();this.#Ta=null;this.#Ma=null;this.#Pa?.remove();this.#Pa=null}}class HighlightEditor extends AnnotationEditor{#za=null;#Ga=0;#Va;#$a=null;#n=null;#Wa=null;#ja=null;#qa=0;#Xa=null;#Ka=null;#v=null;#Ya=false;#Aa=null;#Qa;#Ja=null;#Za="";#ia;#tr="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=h.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=HighlightEditor.prototype;return shadow(this,"_keyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"});this.color=t.color||HighlightEditor._defaultColor;this.#ia=t.thickness||HighlightEditor._defaultThickness;this.#Qa=t.opacity||HighlightEditor._defaultOpacity;this.#Va=t.boxes||null;this.#tr=t.methodOfCreation||"";this.#Za=t.text||"";this._isDraggable=false;this.defaultL10nId="pdfjs-editor-highlight-editor";if(t.highlightId>-1){this.#Ya=true;this.#er(t);this.#sr()}else if(this.#Va){this.#za=t.anchorNode;this.#Ga=t.anchorOffset;this.#ja=t.focusNode;this.#qa=t.focusOffset;this.#ir();this.#sr();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Ya?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#ia,methodOfCreation:this.#tr}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ir(){const t=new HighlightOutliner(this.#Va,.001);
3this.#Ka=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#Ka.box;const e=new HighlightOutliner(this.#Va,.0025,.001,this._uiManager.direction==="ltr");this.#Wa=e.getOutlines();const{lastPoint:s}=this.#Wa;this.#Aa=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#er({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#Ka=t;const i=1.5;this.#Wa=t.getNewOutline(this.#ia/2+i,.0025);if(e>=0){this.#v=e;this.#$a=s;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Ja=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:true,free:true},bbox:this.#Wa.box,path:{d:this.#Wa.toSVGPath()}},true)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#v,{bbox:HighlightEditor.#nr(this.#Ka.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Ja,{bbox:HighlightEditor.#nr(this.#Wa.box,e),path:{d:this.#Wa.toSVGPath()}})}const[n,a,r,o]=t.box;switch(this.rotation){case 0:this.x=n;this.y=a;this.width=r;this.height=o;break;case 90:{const[t,e]=this.parentDimensions;this.x=a;this.y=1-n;this.width=r*e/t;this.height=o*t/e;break}case 180:this.x=1-n;this.y=1-a;this.width=r;this.height=o;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-a;this.y=n;this.width=r*e/t;this.height=o*t/e;break}}const{lastPoint:l}=this.#Wa;this.#Aa=[(l[0]-n)/r,(l[1]-a)/o]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case c.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case c.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#Aa}updateParams(t,e){switch(t){case c.HIGHLIGHT_COLOR:this.#Bn(e);break;case c.HIGHLIGHT_THICKNESS:this.#ar(e);break}}static get defaultPropertiesToUpdate(){return[[c.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[c.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[c.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[c.HIGHLIGHT_THICKNESS,this.#ia||HighlightEditor._defaultThickness],[c.HIGHLIGHT_FREE,this.#Ya]]}#Bn(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Qa=e;this.parent?.drawLayer.updateProperties(this.#v,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)};const e=this.color;const s=this.#Qa;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:true,type:c.HIGHLIGHT_COLOR,overwriteIfSameType:true,keepUndo:true});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},true)}#ar(t){const e=this.#ia;const setThickness=t=>{this.#ia=t;this.#rr(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:true,type:c.INK_THICKNESS,overwriteIfSameType:true,keepUndo:true});this._reportTelemetry({action:"thickness_changed",thickness:t},true)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",true)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",false)}fixAndSetPosition(){return super.fixAndSetPosition(this.#or())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#or())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#lr();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(this.div!==null){this.#sr();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=false;if(this.parent&&!t)this.#lr();else if(t){this.#sr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#rr(t){if(!this.#Ya)return;this.#er({highlightOutlines:this.#Ka.getNewOutline(t/2)});this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#lr(){if(this.#v!==null&&this.parent){this.parent.drawLayer.remove(this.#v);this.#v=null;this.parent.drawLayer.remove(this.#Ja);this.#Ja=null}}#sr(t=this.parent){if(this.#v===null){({id:this.#v,clipPathId:this.#$a}=t.drawLayer.draw({bbox:this.#Ka.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Qa},rootClass:{highlight:true,free:this.#Ya},path:{d:this.#Ka.toSVGPath()}},false,true));this.#Ja=t.drawLayer.drawOutline({rootClass:{highlightOutline:true,free:this.#Ya},bbox:this.#Wa.box,path:{d:this.#Wa.toSVGPath()}},this.#Ya);this.#Xa&&(this.#Xa.style.clipPath=this.#$a)}}static#nr([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;if(this.#Ya){t=(t-this.rotation+360)%360;s=HighlightEditor.#nr(this.#Ka.box,t)}else s=HighlightEditor.#nr([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#v,{bbox:s,root:{"data-main-rotation":t}});e.updateProperties(this.#Ja,{bbox:HighlightEditor.#nr(this.#Wa.box,t),root:{"data-main-rotation":t}})}
3render(){if(this.div)return this.div;const t=super.render();if(this.#Za){t.setAttribute("aria-label",this.#Za);t.setAttribute("role","mark")}this.#Ya?t.classList.add("free"):this.div.addEventListener("keydown",this.#hr.bind(this),{signal:this._uiManager._signal});const e=this.#Xa=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#$a;const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i);bindEvents(this,this.#Xa,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ja,{rootClass:{hovered:true}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Ja,{rootClass:{hovered:false}})}#hr(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#cr(true);break;case 1:case 3:this.#cr(false);break}}#cr(t){if(!this.#za)return;const e=window.getSelection();t?e.setPosition(this.#za,this.#Ga):e.setPosition(this.#ja,this.#qa)}select(){super.select();this.#Ja&&this.parent?.drawLayer.updateProperties(this.#Ja,{rootClass:{hovered:false,selected:true}})}unselect(){super.unselect();if(this.#Ja){this.parent?.drawLayer.updateProperties(this.#Ja,{rootClass:{selected:false}});this.#Ya||this.#cr(false)}}get _mustFixPosition(){return!this.#Ya}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#v,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Ja,{rootClass:{hidden:!t}})}}#or(){return this.#Ya?this.rotation:0}#dr(){if(this.#Ya)return null;const[t,e]=this.pageDimensions;const[s,i]=this.pageTranslation;const n=this.#Va;const a=new Float32Array(n.length*8);let r=0;for(const{x:o,y:l,width:h,height:c}of n){const n=o*t+s;const d=(1-l)*e+i;a[r]=a[r+4]=n;a[r+1]=a[r+3]=d;a[r+2]=a[r+6]=n+h*t;a[r+5]=a[r+7]=d-c*e;r+=8}return a}#ur(t){return this.#Ka.serialize(t,this.#or())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:a,y:r,width:o,height:l}=s.getBoundingClientRect();const h=new AbortController;const c=t.combinedSignal(h);const pointerUpCallback=e=>{h.abort();this.#pr(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:c});window.addEventListener("pointerup",pointerUpCallback,{signal:c});window.addEventListener("pointerdown",stopEvent,{capture:true,passive:false,signal:c});window.addEventListener("contextmenu",noContextMenu,{signal:c});s.addEventListener("pointermove",this.#gr.bind(this,t),{signal:c});this._freeHighlight=new FreeHighlightOutliner({x:i,y:n},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:true,free:true},path:{d:this._freeHighlight.toSVGPath()}},true,true))}static#gr(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#pr(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,false,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:s,rotation:n,id:a,color:r,opacity:o,popupRef:l},parent:{page:{pageNumber:c}}}=t;i=t={annotationType:h.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:c-1,rect:s.slice(0),rotation:n,id:a,deleted:false,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:s,rotation:n,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:c}}}=t;i=t={annotationType:h.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:c-1,rect:s.slice(0),rotation:n,id:a,deleted:false,popupRef:l}}const{color:n,quadPoints:a,inkLists:r,opacity:o}=t;const l=await super.deserialize(t,e,s);l.color=Util.makeHexColor(...n);l.#Qa=o||1;r&&(l.#ia=t.thickness);l.annotationElementId=t.id||null;l._initialData=i;const[c,d]=l.pageDimensions;const[u,p]=l.pageTranslation;if(a){const t=l.#Va=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-u)/c,y:1-(a[e+1]-p)/d,width:(a[e+2]-a[e])/c,height:(a[e+1]-a[e+5])/d});l.#ir();l.#sr();l.rotate(l.rotation)}else if(r){l.#Ya=true;const t=r[0];const s={x:t[0]-u,y:d-(t[1]-p)};const i=new FreeHighlightOutliner(s,[0,0,c,d],1,l.#ia/2,true,.001);for(let e=0,n=t.length;e<n;e+=2){s.x=t[e]-u;s.y=d-(t[e+1]-p);i.add(s)}const{id:n,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:true,free:true},path:{d:i.toSVGPath()}},true,true);l.#er({highlightOutlines:i.getOutlines(),highlightId:n,clipPathId:a});l.#sr()}return l}serialize(t=false){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0);const s=AnnotationEditor._colorManager.convert(this.color);const i={annotationType:h.HIGHLIGHT,color:s,opacity:this.#Qa,thickness:this.#ia,quadPoints:this.#dr(),outlines:this.#ur(e),pageIndex:this.pageIndex,rect:e,rotation:this.#or(),structTreeParentId:this._structTreeParentId};if(this.annotationElementId&&!this.#Wn(i))return null;i.id=this.annotationElementId;return i}#Wn(t){const{color:e}=this._initialData;return t.color.some(((t,s)=>t!==e[s]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return false}}class DrawingOptions{#fr=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,s)}updateSVGProperty(t,e){this.#fr[t]=e}toSVGProperties(){const t=this.#fr;this.#fr=Object.create(null);return{root:t}}reset(){this.#fr=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#mr=null;#br;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Ar=null;static#wr=null;static#vr=null;static#yr=NaN;static#Er=null;static#_r=null;static#xr=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#br=t.mustBeCommitted||false;this._addOutlines(t)}_addOutlines(t){if(t.drawOutlines){this.#Sr(t);this.#sr()}}#Sr({drawOutlines:t,drawId:e,drawingOptions:s}){this.#mr=t;this._drawingOptions||=s;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Cr(t,this.parent);this.#Tr(t.box)}#Cr(t,e){const{id:s}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),false,false);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return true}static get supportMultipleDrawings(){return false}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e);if(this._currentParent){DrawingEditor.#Ar.updateProperty(s,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[];const e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[];const{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions;const n=i[e];const setter=t=>{i.updateProperty(e,t);const s=this.#mr.updateProperty(e,t);s&&this.#Tr(s);this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};
3this.addCommands({cmd:setter.bind(this,s),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:true,type:t,overwriteIfSameType:true,keepUndo:true})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#mr.getPathResizingSVGProperties(this.#Mr()),{bbox:this.#Dr()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#mr.getPathResizedSVGProperties(this.#Mr()),{bbox:this.#Dr()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Dr()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#mr.getPathTranslatedSVGProperties(this.#Mr(),this.parentDimensions),{bbox:this.#Dr()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:true}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:false}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",true)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",false)}getBaseTranslation(){return[0,0]}get isResizable(){return true}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=true;if(this.#br){this.#br=false;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#lr();super.remove()}rebuild(){if(this.parent){super.rebuild();if(this.div!==null){this.#sr();this.#Tr(this.#mr.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=false;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#lr()}else if(t){this._uiManager.addShouldRescale(this);this.#sr(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#lr(){if(this._drawId!==null&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#sr(t=this.parent){if(this._drawId===null||this.parent!==t)if(this._drawId===null){this._drawingOptions.updateAll();this._drawId=this.#Cr(this.#mr,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Pr([t,e,s,i]){const{parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[e,1-t,s*(a/n),i*(n/a)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(a/n),i*(n/a)];default:return[t,e,s,i]}}#Mr(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,a],rotation:r}=this;switch(r){case 90:return[1-e,t,s*(n/a),i*(a/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/a),i*(a/n)];default:return[t,e,s,i]}}#Tr(t){[this.x,this.y,this.width,this.height]=this.#Pr(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Dr(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:a,parentDimensions:[r,o]}=this;switch((n*4+a)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(r/o),i*(o/r),s*(r/o)];case 5:return[1-e,t,s*(r/o),i*(o/r)];case 6:return[1-t-i*(o/r),1-e,i*(o/r),s*(r/o)];case 7:return[e-s*(r/o),1-t-i*(o/r),s*(r/o),i*(o/r)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(o/r),e,i*(o/r),s*(r/o)];case 13:return[1-e-s*(r/o),t-i*(o/r),s*(r/o),i*(o/r)];case 14:return[1-t,1-e-s*(r/o),i*(o/r),s*(r/o)];case 15:return[e,1-t,s*(r/o),i*(o/r)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Dr()},this.#mr.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Tr(this.#mr.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}const s=super.render();s.classList.add("draw");const i=document.createElement("div");s.append(i);i.setAttribute("aria-hidden","true");i.className="internal";const[n,a]=this.parentDimensions;this.setDims(this.width*n,this.height*a);this._uiManager.addShouldRescale(this);this.disableEditing();this._isCopy&&this._moveAfterPaste(t,e);return s}static createDrawerInstance(t,e,s,i,n){unreachable("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=i;if(DrawingEditor.#Er&&DrawingEditor.#Er!==l)return;const{viewport:{rotation:h}}=t;const{width:c,height:d}=n.getBoundingClientRect();const u=DrawingEditor.#wr=new AbortController;const p=t.combinedSignal(u);DrawingEditor.#yr||=o;DrawingEditor.#Er??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#yr===t.pointerId?this._endDraw(t):DrawingEditor.#_r?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#yr===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#_r?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#Er===t.pointerType){(DrawingEditor.#_r||=new Set).add(t.pointerId);if(DrawingEditor.#Ar.isCancellable()){DrawingEditor.#Ar.removeLastElement();DrawingEditor.#Ar.isEmpty()?this._currentParent.endDrawingSession(true):this._endDraw(null)}}}
3),{capture:true,passive:false,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xr&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#Ar)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ar.startNew(a,r,c,d,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#Ar=this.createDrawerInstance(a,r,c,d,h);DrawingEditor.#vr=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#vr.toSVGProperties(),DrawingEditor.#Ar.defaultSVGProperties),true,false))}}static _drawMove(t){DrawingEditor.#xr=-1;if(!DrawingEditor.#Ar)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(DrawingEditor.#yr===i)if(DrawingEditor.#_r?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ar.add(e,s));DrawingEditor.#xr=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#Ar=null;DrawingEditor.#vr=null;DrawingEditor.#Er=null;DrawingEditor.#xr=NaN}if(DrawingEditor.#wr){DrawingEditor.#wr.abort();DrawingEditor.#wr=null;DrawingEditor.#yr=NaN;DrawingEditor.#_r=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(true);this._cleanup(false);t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ar.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#Ar;const s=this._currentDrawId;const i=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(s,t.setLastElement(i))},undo:()=>{e.drawLayer.updateProperties(s,t.removeLastElement())},mustExec:false,type:c.DRAW_STEP})}else this.endDrawing(false)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(true);e.cleanUndoStack(c.DRAW_STEP);if(!DrawingEditor.#Ar.isEmpty()){const{pageDimensions:[s,i],scale:n}=e;const a=e.createAndAddNewEditor({offsetX:0,offsetY:0},false,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#Ar.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#vr,mustBeCommitted:!t});this._cleanup(true);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(true);return null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,a){unreachable("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:a,pageY:r}}=e.viewport;const o=this.deserializeDraw(a,r,i,n,this._INNER_MARGIN,t);const l=await super.deserialize(t,e,s);l.createDrawingOptions(t);l.#Sr({drawOutlines:o});l.#sr();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,s]=this.pageTranslation;const[i,n]=this.pageDimensions;return this.#mr.serialize([e,s,i,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return false}}class InkDrawOutliner{#Qn=new Float64Array(6);#wn;#Ir;#ei;#ia;#na;#kr="";#Rr=0;#Ca=new InkDrawOutline;#Lr;#Fr;constructor(t,e,s,i,n,a){this.#Lr=s;this.#Fr=i;this.#ei=n;this.#ia=a;[t,e]=this.#Or(t,e);const r=this.#wn=[NaN,NaN,NaN,NaN,t,e];this.#na=[t,e];this.#Ir=[{line:r,points:this.#na}];this.#Qn.set(r,0)}updateProperty(t,e){t==="stroke-width"&&(this.#ia=e)}#Or(t,e){return Outline._normalizePoint(t,e,this.#Lr,this.#Fr,this.#ei)}isEmpty(){return!this.#Ir||this.#Ir.length===0}isCancellable(){return this.#na.length<=10}add(t,e){[t,e]=this.#Or(t,e);const[s,i,n,a]=this.#Qn.subarray(2,6);const r=t-n;const o=e-a;const l=Math.hypot(this.#Lr*r,this.#Fr*o);if(l<=2)return null;this.#na.push(t,e);if(isNaN(s)){this.#Qn.set([n,a,t,e],2);this.#wn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Qn[0])&&this.#wn.splice(6,6);this.#Qn.set([s,i,n,a,t,e],0);this.#wn.push(...Outline.createBezierPoints(s,i,n,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const s=this.add(t,e);return s||(this.#na.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#Lr=s;this.#Fr=i;this.#ei=n;[t,e]=this.#Or(t,e);const a=this.#wn=[NaN,NaN,NaN,NaN,t,e];this.#na=[t,e];const r=this.#Ir.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#Ir.push({line:a,points:this.#na});this.#Qn.set(a,0);this.#Rr=0;this.toSVGPath();return null}getLastElement(){return this.#Ir.at(-1)}
3setLastElement(t){if(!this.#Ir)return this.#Ca.setLastElement(t);this.#Ir.push(t);this.#wn=t.line;this.#na=t.points;this.#Rr=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Ir)return this.#Ca.removeLastElement();this.#Ir.pop();this.#kr="";for(let t=0,e=this.#Ir.length;t<e;t++){const{line:e,points:s}=this.#Ir[t];this.#wn=e;this.#na=s;this.#Rr=0;this.toSVGPath()}return{path:{d:this.#kr}}}toSVGPath(){const t=Outline.svgRound(this.#wn[4]);const e=Outline.svgRound(this.#wn[5]);if(this.#na.length===2){this.#kr=`${this.#kr} M ${t} ${e} Z`;return this.#kr}if(this.#na.length<=6){const s=this.#kr.lastIndexOf("M");this.#kr=`${this.#kr.slice(0,s)} M ${t} ${e}`;this.#Rr=6}if(this.#na.length===4){const t=Outline.svgRound(this.#wn[10]);const e=Outline.svgRound(this.#wn[11]);this.#kr=`${this.#kr} L ${t} ${e}`;this.#Rr=12;return this.#kr}const s=[];if(this.#Rr===0){s.push(`M ${t} ${e}`);this.#Rr=6}for(let t=this.#Rr,e=this.#wn.length;t<e;t+=6){const[e,i,n,a,r,o]=this.#wn.slice(t,t+6).map(Outline.svgRound);s.push(`C${e} ${i} ${n} ${a} ${r} ${o}`)}this.#kr+=s.join(" ");this.#Rr=this.#wn.length;return this.#kr}getOutlines(t,e,s,i){const n=this.#Ir.at(-1);n.line=new Float32Array(n.line);n.points=new Float32Array(n.points);this.#Ca.build(this.#Ir,t,e,s,this.#ei,this.#ia,i);this.#Qn=null;this.#wn=null;this.#Ir=null;this.#kr=null;return this.#Ca}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:true},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#fa;#Nr=0;#Xn;#Ir;#Lr;#Fr;#Br;#ei;#ia;build(t,e,s,i,n,a,r){this.#Lr=e;this.#Fr=s;this.#Br=i;this.#ei=n;this.#ia=a;this.#Xn=r??0;this.#Ir=t;this.#Ur()}get thickness(){return this.#ia}setLastElement(t){this.#Ir.push(t);return{path:{d:this.toSVGPath()}}}removeLastElement(){this.#Ir.pop();return{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#Ir){t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`);if(e.length!==6)if(e.length===12&&isNaN(e[6]))t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else for(let s=6,i=e.length;s<i;s+=6){const[i,n,a,r,o,l]=e.subarray(s,s+6).map(Outline.svgRound);t.push(`C${i} ${n} ${a} ${r} ${o} ${l}`)}else t.push("Z")}return t.join("")}serialize([t,e,s,i],n){const a=[];const r=[];const[o,l,h,c]=this.#Hr();let d,u,p,g,f,m,b,A,w;switch(this.#ei){case 0:w=Outline._rescale;d=t;u=e+i;p=s;g=-i;f=t+o*s;m=e+(1-l-c)*i;b=t+(o+h)*s;A=e+(1-l)*i;break;case 90:w=Outline._rescaleAndSwap;d=t;u=e;p=s;g=i;f=t+l*s;m=e+o*i;b=t+(l+c)*s;A=e+(o+h)*i;break;case 180:w=Outline._rescale;d=t+s;u=e;p=-s;g=i;f=t+(1-o-h)*s;m=e+l*i;b=t+(1-o)*s;A=e+(l+c)*i;break;case 270:w=Outline._rescaleAndSwap;d=t+s;u=e+i;p=-s;g=-i;f=t+(1-l-c)*s;m=e+(1-o-h)*i;b=t+(1-l)*s;A=e+(1-o)*i;break}for(const{line:t,points:e}of this.#Ir){a.push(w(t,d,u,p,g,n?new Array(t.length):null));r.push(w(e,d,u,p,g,n?new Array(e.length):null))}return{lines:a,points:r,rect:[f,m,b,A]}}static deserialize(t,e,s,i,n,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=Outline._rescale;c=-t/s;d=e/i+1;u=1/s;p=-1/i;break;case 90:g=Outline._rescaleAndSwap;c=-e/i;d=-t/s;u=1/i;p=1/s;break;case 180:g=Outline._rescale;c=t/s+1;d=-e/i;u=-1/s;p=1/i;break;case 270:g=Outline._rescaleAndSwap;c=e/i+1;d=t/s+1;u=-1/i;p=-1/s;break}if(!a){a=[];for(const t of r){const e=t.length;if(e===2){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(e===4){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const s=new Float32Array(3*(e-2));a.push(s);let[i,n,r,o]=t.subarray(0,4);s.set([NaN,NaN,NaN,NaN,i,n],0);for(let a=4;a<e;a+=2){const e=t[a];const l=t[a+1];s.set(Outline.createBezierPoints(i,n,r,o,e,l),3*(a-2));[i,n,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map((t=>t??NaN)),c,d,u,p),points:g(r[t].map((t=>t??NaN)),c,d,u,p)});const f=new this.prototype.constructor;f.build(h,s,i,1,o,l,n);return f}#zr(t=this.#ia){const e=this.#Xn+t/2*this.#Br;return this.#ei%180===0?[e/this.#Lr,e/this.#Fr]:[e/this.#Fr,e/this.#Lr]}#Hr(){const[t,e,s,i]=this.#fa;const[n,a]=this.#zr(0);return[t+n,e+a,s-2*n,i-2*a]}#Ur(){const t=this.#fa=new Float32Array([Infinity,Infinity,-Infinity,-Infinity]);for(const{line:e}of this.#Ir){if(e.length<=12){for(let s=4,i=e.length;s<i;s+=6){const[i,n]=e.subarray(s,s+2);t[0]=Math.min(t[0],i);t[1]=Math.min(t[1],n);t[2]=Math.max(t[2],i);t[3]=Math.max(t[3],n)}continue}let s=e[4],i=e[5];for(let n=6,a=e.length;n<a;n+=6){const[a,r,o,l,h,c]=e.subarray(n,n+6);Util.bezierBoundingBox(s,i,a,r,o,l,h,c,t);s=h;i=c}}const[e,s]=this.#zr();t[0]=MathClamp(t[0]-e,0,1);t[1]=MathClamp(t[1]-s,0,1);t[2]=MathClamp(t[2]+e,0,1);t[3]=MathClamp(t[3]+s,0,1);t[2]-=t[0];t[3]-=t[1]}get box(){return this.#fa}updateProperty(t,e){return t==="stroke-width"?this.#ar(e):null}#ar(t){const[e,s]=this.#zr();this.#ia=t;const[i,n]=this.#zr();const[a,r]=[i-e,n-s];const o=this.#fa;o[0]-=a;o[1]-=r;o[2]+=2*a;o[3]+=2*r;return o}updateParentDimensions([t,e],s){const[i,n]=this.#zr();this.#Lr=t;this.#Fr=e;this.#Br=s;const[a,r]=this.#zr();const o=a-i;const l=r-n;const h=this.#fa;h[0]-=o;h[1]-=l;h[2]+=2*o;h[3]+=2*l;return h}updateRotation(t){this.#Nr=t;return{path:{transform:this.rotationTransform}}}get viewBox(){return this.#fa.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#fa;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#fa;let s=0,i=0,n=0,a=0,r=0,o=0;switch(this.#Nr){case 90:i=e/t;n=-t/e;r=t;break;case 180:s=-1;a=-1;r=t;o=e;break;case 270:i=-e/t;n=t/e;o=e;break;default:return""}return`matrix(${s} ${i} ${n} ${a} ${Outline.svgRound(r)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,a]=this.#zr();const[r,o,l,h]=this.#fa;if(Math.abs(l-n)<=Outline.PRECISION||Math.abs(h-a)<=Outline.PRECISION){const n=t+s/2-(r+l/2);
3const a=e+i/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${n} ${a})`}}}const c=(s-2*n)/(l-2*n);const d=(i-2*a)/(h-2*a);const u=l/s;const p=h/i;return{path:{"transform-origin":`${Outline.svgRound(r)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(n)} ${Outline.svgRound(a)}) scale(${c} ${d}) translate(${Outline.svgRound(-n)} ${Outline.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,a]=this.#zr();const r=this.#fa;const[o,l,h,c]=r;r[0]=t;r[1]=e;r[2]=s;r[3]=i;if(Math.abs(h-n)<=Outline.PRECISION||Math.abs(c-a)<=Outline.PRECISION){const n=t+s/2-(o+h/2);const a=e+i/2-(l+c/2);for(const{line:t,points:e}of this.#Ir){Outline._translate(t,n,a,t);Outline._translate(e,n,a,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(h-2*n);const u=(i-2*a)/(c-2*a);const p=-d*(o+n)+t+n;const g=-u*(l+a)+e+a;if(d!==1||u!==1||p!==0||g!==0)for(const{line:t,points:e}of this.#Ir){Outline._rescale(t,p,g,d,u,t);Outline._rescale(e,p,g,d,u,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s;const a=this.#fa;const r=t-a[0];const o=e-a[1];if(this.#Lr===i&&this.#Fr===n)for(const{line:t,points:e}of this.#Ir){Outline._translate(t,r,o,t);Outline._translate(e,r,o,e)}else{const t=this.#Lr/i;const e=this.#Fr/n;this.#Lr=i;this.#Fr=n;for(const{line:s,points:i}of this.#Ir){Outline._rescale(s,r,o,t,e,s);Outline._rescale(i,r,o,t,e,i)}a[2]*=t;a[3]*=e}a[0]=t;a[1]=e;return{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#fa;return{root:{viewBox:this.viewBox},rootClass:{draw:true},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{constructor(t){super();this._viewParameters=t;super.updateProperties({fill:"none",stroke:AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){if(t==="stroke-width"){e??=this["stroke-width"];e*=this._viewParameters.realScale}super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this._viewParameters);t.updateAll(this);return t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=h.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"});this._willKeepAspectRatio=true;this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return true}static get typesMap(){return shadow(this,"typesMap",new Map([[c.INK_THICKNESS,"stroke-width"],[c.INK_COLOR,"stroke"],[c.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new InkDrawOutliner(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,a){return InkDrawOutline.deserialize(t,e,s,i,n,a)}static async deserialize(t,e,s){let i=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:s,rotation:n,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:c},parent:{page:{pageNumber:d}}}=t;i=t={annotationType:h.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:d-1,rect:s.slice(0),rotation:n,id:a,deleted:false,popupRef:c}}const n=await super.deserialize(t,e,s);n.annotationElementId=t.id||null;n._initialData=i;return n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width");s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;if(t){super.onScaleChangingWhenDrawing();this._defaultDrawingOptions.updateSVGProperty("stroke-width");t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=InkEditor.getDefaultDrawingOptions({stroke:Util.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=false){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t);const{_drawingOptions:{stroke:n,"stroke-opacity":a,"stroke-width":r}}=this;const o={annotationType:h.INK,color:AnnotationEditor._colorManager.convert(n),opacity:a,thickness:r,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t){o.isCopy=true;return o}if(this.annotationElementId&&!this.#Wn(o))return null;o.id=this.annotationElementId;return o}#Wn(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some(((t,s)=>t!==e[s]))||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(false);t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();t.endsWith("Z")||(t+="Z");return t}}const ot=8;const lt=3;class SignatureExtractor{static#Gr={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Vr(t,e,s,i){s-=t;i-=e;return s===0?i>0?0:4:s===1?i+6:2-i}static#$r=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Wr(t,e,s,i,n,a,r){const o=this.#Vr(s,i,n,a);for(let n=0;n<8;n++){const a=(-n+o-r+16)%8;const l=this.#$r[2*a];const h=this.#$r[2*a+1];if(t[(s+l)*e+(i+h)]!==0)return a}return-1}static#jr(t,e,s,i,n,a,r){const o=this.#Vr(s,i,n,a);for(let n=0;n<8;n++){const a=(n+o+r+16)%8;const l=this.#$r[2*a];const h=this.#$r[2*a+1];if(t[(s+l)*e+(i+h)]!==0)return a}return-1}static#qr(t,e,s,i){const n=t.length;const a=new Int32Array(n);for(let e=0;e<n;e++)a[e]=t[e]<=i?1:0;for(let t=1;t<s-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*s-1-t]=0;let r=1;let o;const l=[];for(let t=1;t<s-1;t++){o=1;for(let s=1;s<e-1;s++){const i=t*e+s;const n=a[i];if(n===0)continue;let h=t;
3let c=s;if(n===1&&a[i-1]===0){r+=1;c-=1}else{if(!(n>=1&&a[i+1]===0)){n!==1&&(o=Math.abs(n));continue}r+=1;c+=1;n>1&&(o=n)}const d=[s,t];const u=c===s+1;const p={isHole:u,points:d,id:r,parent:0};l.push(p);let g;for(const t of l)if(t.id===o){g=t;break}g?g.isHole?p.parent=u?g.parent:o:p.parent=u?o:g.parent:p.parent=u?o:0;const f=this.#Wr(a,e,t,s,h,c,0);if(f===-1){a[i]=-r;a[i]!==1&&(o=Math.abs(a[i]));continue}let m=this.#$r[2*f];let b=this.#$r[2*f+1];const A=t+m;const w=s+b;h=A;c=w;let v=t;let y=s;while(true){const n=this.#jr(a,e,v,y,h,c,1);m=this.#$r[2*n];b=this.#$r[2*n+1];const l=v+m;const u=y+b;d.push(u,l);const p=v*e+y;a[p+1]===0?a[p]=-r:a[p]===1&&(a[p]=r);if(l===t&&u===s&&v===A&&y===w){a[i]!==1&&(o=Math.abs(a[i]));break}h=v;c=y;v=l;y=u}}}return l}static#Xr(t,e,s,i){if(s-e<=4){for(let n=e;n<s-2;n+=2)i.push(t[n],t[n+1]);return}const n=t[e];const a=t[e+1];const r=t[s-4]-n;const o=t[s-3]-a;const l=Math.hypot(r,o);const h=r/l;const c=o/l;const d=h*a-c*n;const u=o/r;const p=1/l;const g=Math.atan(u);const f=Math.cos(g);const m=Math.sin(g);const b=p*(Math.abs(f)+Math.abs(m));const A=p*(1-b+b**2);const w=Math.max(Math.atan(Math.abs(m+f)*A),Math.atan(Math.abs(m-f)*A));let v=0;let y=e;for(let i=e+2;i<s-2;i+=2){const e=Math.abs(d-h*t[i+1]+c*t[i]);if(e>v){y=i;v=e}}if(v>(l*w)**2){this.#Xr(t,e,y+2,i);this.#Xr(t,y,s,i)}else i.push(n,a)}static#Kr(t){const e=[];const s=t.length;this.#Xr(t,0,s,e);e.push(t[s-2],t[s-1]);return e.length<=4?null:e}static#Yr(t,e,s,i,n,a){const r=new Float32Array(a**2);const o=-2*i**2;const l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let s=0;s<a;s++)r[t*a+s]=Math.exp((e+(s-l)**2)/o)}const h=new Float32Array(256);const c=-2*n**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length;const u=new Uint8Array(d);const p=new Uint32Array(256);for(let i=0;i<s;i++)for(let n=0;n<e;n++){const o=i*e+n;const c=t[o];let d=0;let g=0;for(let o=0;o<a;o++){const u=i+o-l;if(!(u<0||u>=s))for(let s=0;s<a;s++){const i=n+s-l;if(i<0||i>=e)continue;const p=t[u*e+i];const f=r[o*a+s]*h[Math.abs(p-c)];d+=p*f;g+=f}}const f=u[o]=Math.round(d/g);p[f]++}return[u,p]}static#Qr(t){const e=new Uint32Array(256);for(const s of t)e[s]++;return e}static#Jr(t){const e=t.length;const s=new Uint8ClampedArray(e>>2);let i=-Infinity;let n=Infinity;for(let e=0,a=s.length;e<a;e++){const a=t[3+(e<<2)];if(a===0){i=s[e]=255;continue}const r=s[e]=t[e<<2];r>i&&(i=r);r<n&&(n=r)}const a=255/(i-n);for(let t=0;t<e;t++)s[t]=(s[t]-n)*a;return s}static#Zr(t){let e;let s=-Infinity;let i=-Infinity;const n=t.findIndex((t=>t!==0));let a=n;let r=n;for(e=n;e<256;e++){const n=t[e];if(n>s){if(e-a>i){i=e-a;r=e-1}s=n;a=e}}for(e=r-1;e>=0;e--)if(t[e]>t[e+1])break;return e}static#to(t){const e=t;const{width:s,height:i}=t;const{maxDim:n}=this.#Gr;let a=s;let r=i;if(s>n||i>n){let o=s;let l=i;let h=Math.log2(Math.max(s,i)/n);const c=Math.floor(h);h=h===c?c-1:c;for(let s=0;s<h;s++){a=o;r=l;a>n&&(a=Math.ceil(a/2));r>n&&(r=Math.ceil(r/2));const s=new OffscreenCanvas(a,r);const i=s.getContext("2d");i.drawImage(t,0,0,o,l,0,0,a,r);o=a;l=r;t!==e&&t.close();t=s.transferToImageBitmap()}const d=Math.min(n/a,n/r);a=Math.round(a*d);r=Math.round(r*d)}const o=new OffscreenCanvas(a,r);const l=o.getContext("2d",{willReadFrequently:true});l.filter="grayscale(1)";l.drawImage(t,0,0,t.width,t.height,0,0,a,r);const h=l.getImageData(0,0,a,r).data;const c=this.#Jr(h);return[c,a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:s,fontWeight:i},n,a,r,o){let l=new OffscreenCanvas(1,1);let h=l.getContext("2d",{alpha:false});const c=200;const d=h.font=`${s} ${i} ${c}px ${e}`;const{actualBoundingBoxLeft:u,actualBoundingBoxRight:p,actualBoundingBoxAscent:g,actualBoundingBoxDescent:f,fontBoundingBoxAscent:m,fontBoundingBoxDescent:b,width:A}=h.measureText(t);const w=1.5;const v=Math.ceil(Math.max(Math.abs(u)+Math.abs(p)||0,A)*w);const y=Math.ceil(Math.max(Math.abs(g)+Math.abs(f)||c,Math.abs(m)+Math.abs(b)||c)*w);l=new OffscreenCanvas(v,y);h=l.getContext("2d",{alpha:true,willReadFrequently:true});h.font=d;h.filter="grayscale(1)";h.fillStyle="white";h.fillRect(0,0,v,y);h.fillStyle="black";h.fillText(t,v*(w-1)/2,y*(3-w)/2);const E=this.#Jr(h.getImageData(0,0,v,y).data);const _=this.#Qr(E);const x=this.#Zr(_);const S=this.#qr(E,v,y,x);return this.processDrawnLines({lines:{curves:S,width:v,height:y},pageWidth:n,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:true,areContours:true})}static process(t,e,s,i,n){const[a,r,o]=this.#to(t);const[l,h]=this.#Yr(a,r,o,Math.hypot(r,o)*this.#Gr.sigmaSFactor,this.#Gr.sigmaR,this.#Gr.kernelSize);const c=this.#Zr(h);const d=this.#qr(l,r,o,c);return this.processDrawnLines({lines:{curves:d,width:r,height:o},pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:true,areContours:true})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:n,mustSmooth:a,areContours:r}){i%180!==0&&([e,s]=[s,e]);const{curves:o,width:l,height:h}=t;const c=t.thickness??0;const d=[];const u=Math.min(e/l,s/h);const p=u/e;const g=u/s;const f=[];for(const{points:t}of o){const e=a?this.#Kr(t):t;if(!e)continue;f.push(e);const s=e.length;const i=new Float32Array(s);const n=new Float32Array(3*(s===2?2:s-2));d.push({line:n,points:i});if(s===2){i[0]=e[0]*p;i[1]=e[1]*g;n.set([NaN,NaN,NaN,NaN,i[0],i[1]],0);continue}let[r,o,l,h]=e;r*=p;o*=g;l*=p;h*=g;i.set([r,o,l,h],0);n.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<s;t+=2){const s=i[t]=e[t]*p;const a=i[t+1]=e[t+1]*g;n.set(Outline.createBezierPoints(r,o,l,h,s,a),3*(t-2));[r,o,l,h]=[l,h,s,a]}}if(d.length===0)return null;const m=r?new ContourDrawOutline:new InkDrawOutline;m.build(d,e,s,1,i,r?0:c,n);return{outline:m,newCurves:f,areContours:r,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:s,width:i,height:n}){let a=Infinity;let r=-Infinity;let o=0;for(const e of t){o+=e.length;for(let t=2,s=e.length;t<s;t++){const s=e[t]-e[t-2];a=Math.min(a,s);r=Math.max(r,s)}}let l;l=a>=-128&&r<=127?Int8Array:a>=-32768&&r<=32767?Int16Array:Int32Array;const h=t.length;const c=ot+lt*h;const d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(o-2*h)*l.BYTES_PER_ELEMENT;d[u++]=0;d[u++]=i;d[u++]=n;d[u++]=e?0:1;d[u++]=Math.max(0,Math.floor(s??0));d[u++]=h;d[u++]=l.BYTES_PER_ELEMENT;for(const e of t){d[u++]=e.length-2;d[u++]=e[0];d[u++]=e[1]}const p=new CompressionStream("deflate-raw");const g=p.writable.getWriter();await g.ready;g.write(d);const f=l.prototype.constructor;for(const e of t){const t=new f(e.length-2);for(let s=2,i=e.length;s<i;s++)t[s-2]=e[s]-e[s-2];g.write(t)}g.close();const m=await new Response(p.readable).arrayBuffer();const b=new Uint8Array(m);return toBase64Util(b)}static async decompressSignature(t){try{const e=fromBase64Util(t);const{readable:s,writable:i}=new DecompressionStream("deflate-raw");const n=i.getWriter();await n.ready;n.write(e).then((async()=>{await n.ready;await n.close()})).catch((()=>{}));let a=null;let r=0;for await(const t of s){a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]);a.set(t,r);r+=t.length}const o=new Uint32Array(a.buffer,0,a.length>>2);const l=o[1];if(l!==0)throw new Error(`Invalid version: ${l}`);const h=o[2];const c=o[3];const d=o[4]===0;const u=o[5];const p=o[6];const g=o[7];const f=[];const m=(ot+lt*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(a.buffer,m);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(a.buffer,m);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(a.buffer,m);break}r=0;for(let t=0;t<p;t++){const e=o[lt*t+ot];const s=new Float32Array(e+2);f.push(s);for(let e=0;e<lt-1;e++)s[e]=o[lt*t+ot+e+1];for(let t=0;t<e;t++)s[t+2]=s[t]+b[r++]}return{areContours:d,thickness:u,outlines:f,width:h,height:c}}catch(t){warn(`decompressSignature: ${t}`);return null}}}class SignatureOptions extends DrawingOptions{constructor(){super();
3super.updateProperties({fill:"CanvasText","stroke-width":0})}clone(){const t=new SignatureOptions;t.updateAll(this);return t}}class DrawnSignatureOptions extends InkDrawingOptions{constructor(t){super(t);super.updateProperties({stroke:"CanvasText","stroke-width":1})}clone(){const t=new DrawnSignatureOptions(this._viewParameters);t.updateAll(this);return t}}class SignatureEditor extends DrawingEditor{#eo=false;#so=null;#io=null;#no=null;static _type="signature";static _editorType=h.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:true,name:"signatureEditor"});this._willKeepAspectRatio=true;this.#io=t.signatureData||null;this.#so=null;this.defaultL10nId="pdfjs-editor-signature-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new SignatureOptions;this._defaultDrawnSignatureOptions=new DrawnSignatureOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return false}static get typesMap(){return shadow(this,"typesMap",new Map)}static get isDrawer(){return false}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#so}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(true)??0,hasNoAltText:e.get(false)??0}}get isResizable(){return true}onScaleChanging(){this._drawId!==null&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:s}=this;if(s){this._isCopy=false;t=this.x;e=this.y}super.render();if(this._drawId===null)if(this.#io){const{lines:t,mustSmooth:e,areContours:s,description:i,uuid:n,heightInPage:a}=this.#io;const{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport;const h=SignatureExtractor.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:e,areContours:s});this.addSignature(h,a,i,n)}else{this.div.hidden=true;this._uiManager.getSignature(this)}if(s){this._isCopy=true;this._moveAfterPaste(t,e)}return this.div}setUuid(t){this.#no=t;this.addEditToolbar()}getUuid(){return this.#no}get description(){return this.#so}set description(t){this.#so=t;super.addEditToolbar().then((e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:s,width:i,height:n}=this.#io;const a=Math.max(i,n);const r=SignatureExtractor.processDrawnLines({lines:{curves:t.map((t=>({points:t}))),thickness:s,width:i,height:n},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:false,areContours:e});return{areContours:e,outline:r.outline}}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.signatureManager&&this.#so!==null){await t.addEditSignatureButton(this._uiManager.signatureManager,this.#no,this.#so);t.show()}return t}addSignature(t,e,s,i){const{x:n,y:a}=this;const{outline:r}=this.#io=t;this.#eo=r instanceof ContourDrawOutline;this.#so=s;this.div.setAttribute("aria-description",s);let o;if(this.#eo)o=SignatureEditor.getDefaultDrawingOptions();else{o=SignatureEditor._defaultDrawnSignatureOptions.clone();o.updateProperties({"stroke-width":r.thickness})}this._addOutlines({drawOutlines:r,drawingOptions:o});const[l,h]=this.parentDimensions;const[,c]=this.pageDimensions;let d=e/c;d=d>=1?.5:d;this.width*=d/this.height;if(this.width>=1){d*=.9/this.width;this.width=.9}this.height=d;this.setDims(l*this.width,h*this.height);this.x=n;this.y=a;this.center();this._onResized();this.onScaleChanging();this.rotate();this._uiManager.addToAnnotationStorage(this);this.setUuid(i);this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!i,hasDescription:!!s}});this.div.hidden=false}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return SignatureExtractor.process(t,e,s,i,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:s,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,s,i,n,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:s},rotation:i}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:s,rotation:i,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:false,areContours:false})}createDrawingOptions({areContours:t,thickness:e}){if(t)this._drawingOptions=SignatureEditor.getDefaultDrawingOptions();else{this._drawingOptions=SignatureEditor._defaultDrawnSignatureOptions.clone();this._drawingOptions.updateProperties({"stroke-width":e})}}serialize(t=false){if(this.isEmpty())return null;const{lines:e,points:s,rect:i}=this.serializeDraw(t);const{_drawingOptions:{"stroke-width":n}}=this;const a={annotationType:h.SIGNATURE,isSignature:true,areContours:this.#eo,color:[0,0,0],thickness:this.#eo?0:n,pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t){a.paths={lines:e,points:s};a.uuid=this.#no;a.isCopy=true}else a.lines=e;
3this.#so&&(a.accessibilityData={type:"Figure",alt:this.#so});return a}static deserializeDraw(t,e,s,i,n,a){return a.areContours?ContourDrawOutline.deserialize(t,e,s,i,n,a):InkDrawOutline.deserialize(t,e,s,i,n,a)}static async deserialize(t,e,s){const i=await super.deserialize(t,e,s);i.#eo=t.areContours;i.#so=t.accessibilityData?.alt||"";i.#no=t.uuid;return i}}class StampEditor extends AnnotationEditor{#ao=null;#ro=null;#oo=null;#lo=null;#ho=null;#co="";#do=null;#uo=false;#po=null;#go=false;#fo=false;static _type="stamp";static _editorType=h.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#lo=t.bitmapUrl;this.#ho=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return C.includes(t)}static paste(t,e){e.pasteEditor(h.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=false);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(true)??0,hasNoAltText:e.get(false)??0}}#mo(t,e=false){if(t){this.#ao=t.bitmap;if(!e){this.#ro=t.id;this.#go=t.isSvg}t.file&&(this.#co=t.file.name);this.#bo()}else this.remove()}#Ao(){this.#oo=null;this._uiManager.enableWaiting(false);if(this.#do)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#ao){this._editToolbar.hide();this._uiManager.editAltText(this,true)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#ao){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:false,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=true){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:a}=t||this.copyCanvas(null,null,true).imageData;const r=await s.guess({name:"altText",request:{data:i,width:n,height:a,channels:i.length/(n*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:false});return o}#wo(){if(this.#ro){this._uiManager.enableWaiting(true);this._uiManager.imageManager.getFromId(this.#ro).then((t=>this.#mo(t,true))).finally((()=>this.#Ao()));return}if(this.#lo){const t=this.#lo;this.#lo=null;this._uiManager.enableWaiting(true);this.#oo=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#mo(t))).finally((()=>this.#Ao()));return}if(this.#ho){const t=this.#ho;this.#ho=null;this._uiManager.enableWaiting(true);this.#oo=this._uiManager.imageManager.getFromFile(t).then((t=>this.#mo(t))).finally((()=>this.#Ao()));return}const t=document.createElement("input");t.type="file";t.accept=C.join(",");const e=this._uiManager._signal;this.#oo=new Promise((s=>{t.addEventListener("change",(async()=>{if(t.files&&t.files.length!==0){this._uiManager.enableWaiting(true);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#mo(e)}else this.remove();s()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();s()}),{signal:e})})).finally((()=>this.#Ao()));t.click()}remove(){if(this.#ro){this.#ao=null;this._uiManager.imageManager.deleteId(this.#ro);this.#do?.remove();this.#do=null;if(this.#po){clearTimeout(this.#po);this.#po=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(this.div!==null){this.#ro&&this.#do===null&&this.#wo();this.isAttachedToDOM||this.parent.add(this)}}else this.#ro&&this.#wo()}onceAdded(t){this._isDraggable=true;t&&this.div.focus()}isEmpty(){return!(this.#oo||this.#ao||this.#lo||this.#ho||this.#ro||this.#uo)}get isResizable(){return true}
3render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}super.render();this.div.hidden=true;this.addAltTextButton();this.#uo||(this.#ao?this.#bo():this.#wo());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:s,bitmap:i}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(s&&this._uiManager.imageManager.isValidId(s)){this.#ro=s;i&&(this.#ao=i);this.#uo=false;this.#bo()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#po!==null&&clearTimeout(this.#po);const t=200;this.#po=setTimeout((()=>{this.#po=null;this.#vo()}),t)}#bo(){const{div:t}=this;let{width:e,height:s}=this.#ao;const[i,n]=this.pageDimensions;const a=.75;if(this.width){e=this.width*i;s=this.height*n}else if(e>a*i||s>a*n){const t=Math.min(a*i/e,a*n/s);e*=t;s*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/i,s*o/n);this._uiManager.enableWaiting(false);const l=this.#do=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/i;this.height=s/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=false);this.#vo();if(!this.#fo){this.parent.addUndoableEditor(this);this.#fo=true}this._reportTelemetry({action:"inserted_image"});this.#co&&this.div.setAttribute("aria-description",this.#co)}copyCanvas(t,e,s=false){t||(t=224);const{width:i,height:n}=this.#ao;const a=new OutputScale;let r=this.#ao;let o=i,l=n;let h=null;if(e){if(i>e||n>e){const t=Math.min(e/i,e/n);o=Math.floor(i*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx);const s=h.height=Math.ceil(l*a.sy);this.#go||(r=this.#yo(t,s));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";if(this._uiManager.hcmFilter!=="none")u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){d="#8f8f9d";u="#42414d"}const p=15;const g=p*a.sx;const f=p*a.sy;const m=new OffscreenCanvas(g*2,f*2);const b=m.getContext("2d");b.fillStyle=d;b.fillRect(0,0,g*2,f*2);b.fillStyle=u;b.fillRect(0,0,g,f);b.fillRect(g,f,g,f);c.fillStyle=c.createPattern(m,"repeat");c.fillRect(0,0,t,s);c.drawImage(r,0,0,r.width,r.height,0,0,t,s)}let c=null;if(s){let e,s;if(a.symmetric&&r.width<t&&r.height<t){e=r.width;s=r.height}else{r=this.#ao;if(i>t||n>t){const a=Math.min(t/i,t/n);e=Math.floor(i*a);s=Math.floor(n*a);this.#go||(r=this.#yo(e,s))}}const o=new OffscreenCanvas(e,s);const l=o.getContext("2d",{willReadFrequently:true});l.drawImage(r,0,0,r.width,r.height,0,0,e,s);c={width:e,height:s,data:l.getImageData(0,0,e,s).data}}return{canvas:h,width:o,height:l,imageData:c}}#yo(t,e){const{width:s,height:i}=this.#ao;let n=s;let a=i;let r=this.#ao;while(n>2*t||a>2*e){const s=n;const i=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);const l=o.getContext("2d");l.drawImage(r,0,0,s,i,0,0,n,a);r=o.transferToImageBitmap()}return r}#vo(){const[t,e]=this.parentDimensions;const{width:s,height:i}=this;const n=new OutputScale;const a=Math.ceil(s*t*n.sx);const r=Math.ceil(i*e*n.sy);const o=this.#do;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#go?this.#ao:this.#yo(a,r);const h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#Eo(t){if(t){if(this.#go){const t=this._uiManager.imageManager.getSvgUrl(this.#ro);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#ao);const e=t.getContext("2d");e.drawImage(this.#ao,0,0);return t.toDataURL()}if(this.#go){const[t,e]=this.pageDimensions;const s=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS);const i=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS);const n=new OffscreenCanvas(s,i);const a=n.getContext("2d");a.drawImage(this.#ao,0,0,this.#ao.width,this.#ao.height,0,0,s,i);return n.transferToImageBitmap()}return structuredClone(this.#ao)}static async deserialize(t,e,s){let i=null;let n=false;if(t instanceof StampAnnotationElement){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:c},container:d,parent:{page:{pageNumber:u}},canvas:p}=t;let g,f;if(p){delete t.canvas;({id:g,bitmap:f}=s.imageManager.getFromCanvas(d.id,p));p.remove()}else{n=true;t._hasNoCanvas=true}const m=(await e._structTree.getAriaAttributes(`${x}${o}`))?.get("aria-label")||"";i=t={annotationType:h.STAMP,bitmapId:g,bitmap:f,pageIndex:u-1,rect:a.slice(0),rotation:r,id:o,deleted:false,accessibilityData:{decorative:false,altText:m},isSvg:false,structParent:l,popupRef:c}}const a=await super.deserialize(t,e,s);const{rect:r,bitmap:o,bitmapUrl:l,bitmapId:c,isSvg:d,accessibilityData:u}=t;if(n){s.addMissingCanvas(t.id,a);a.#uo=true}else if(c&&s.imageManager.isValidId(c)){a.#ro=c;o&&(a.#ao=o)}else a.#lo=l;a.#go=d;const[p,g]=a.pageDimensions;a.width=(r[2]-r[0])/p;a.height=(r[3]-r[1])/g;a.annotationElementId=t.id||null;u&&(a.altTextData=u);a._initialData=i;a.#fo=!!i;return a}serialize(t=false,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:h.STAMP,bitmapId:this.#ro,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#go,structTreeParentId:this._structTreeParentId};if(t){s.bitmapUrl=this.#Eo(true);s.accessibilityData=this.serializeAltText(true);s.isCopy=true;return s}const{decorative:i,altText:n}=this.serializeAltText(false);!i&&n&&(s.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#Wn(s);if(t.isSame)return null;t.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}s.id=this.annotationElementId;if(e===null)return s;e.stamps||=new Map;const a=this.#go?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(e.stamps.has(this.#ro)){if(this.#go){const t=e.stamps.get(this.#ro);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#Eo(false)}}}else{e.stamps.set(this.#ro,{area:a,serialized:s});s.bitmap=this.#Eo(false)}return s}#Wn(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData;const i=t.pageIndex===e;const n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Mn;#_o=false;#xo=null;#So=null;#Co=null;#To=new Map;#Mo=false;#Do=false;#Po=false;#Io=null;#ko=null;#Ro=null;#Lo=null;#m;static _initialized=false;static#G=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const c=[...AnnotationEditorLayer.#G.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=true;for(const e of c)e.initialize(h,t)}
3t.registerEditorTypes(c);this.#m=t;this.pageIndex=e;this.div=s;this.#Mn=n;this.#xo=a;this.viewport=l;this.#Ro=o;this.drawLayer=r;this._structTree=i;this.#m.addLayer(this)}get isEmpty(){return this.#To.size===0}get isInvisible(){return this.isEmpty&&this.#m.getMode()===h.NONE}updateToolbar(t){this.#m.updateToolbar(t)}updateMode(t=this.#m.getMode()){this.#Fo();switch(t){case h.NONE:this.disableTextSelection();this.togglePointerEvents(false);this.toggleAnnotationLayerPointerEvents(true);this.disableClick();return;case h.INK:this.disableTextSelection();this.togglePointerEvents(true);this.enableClick();break;case h.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(false);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(true);this.enableClick()}this.toggleAnnotationLayerPointerEvents(false);const{classList:e}=this.div;for(const s of AnnotationEditorLayer.#G.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=false}hasTextLayer(t){return t===this.#Ro?.div}setEditingState(t){this.#m.setEditingState(t)}addCommands(t){this.#m.addCommands(t)}cleanUndoStack(t){this.#m.cleanUndoStack(t)}toggleDrawing(t=false){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=false){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=false){this.#xo?.div.classList.toggle("disabled",!t)}async enable(){this.#Po=true;this.div.tabIndex=0;this.togglePointerEvents(true);const t=new Set;for(const e of this.#To.values()){e.enableEditing();e.show(true);if(e.annotationElementId){this.#m.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#xo){this.#Po=false;return}const e=this.#xo.getEditableAnnotations();for(const s of e){s.hide();if(this.#m.isDeletedAnnotationElement(s.data.id))continue;if(t.has(s.data.id))continue;const e=await this.deserialize(s);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#Po=false}disable(){this.#Do=true;this.div.tabIndex=-1;this.togglePointerEvents(false);const t=new Map;const e=new Map;for(const s of this.#To.values()){s.disableEditing();if(s.annotationElementId)if(s.serialize()===null){e.set(s.annotationElementId,s);this.getEditableAnnotation(s.annotationElementId)?.show();s.remove()}else t.set(s.annotationElementId,s)}if(this.#xo){const s=this.#xo.getEditableAnnotations();for(const i of s){const{id:s}=i.data;if(this.#m.isDeletedAnnotationElement(s))continue;let n=e.get(s);if(n){n.resetAnnotationElement(i);n.show(false);i.show()}else{n=t.get(s);if(n){this.#m.addChangedExistingAnnotation(n);n.renderAnnotationElement(i)&&n.show(false)}i.show()}}}this.#Fo();this.isEmpty&&(this.div.hidden=true);const{classList:s}=this.div;for(const t of AnnotationEditorLayer.#G.values())s.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(true);this.#Do=false}getEditableAnnotation(t){return this.#xo?.getEditableAnnotation(t)||null}setActiveEditor(t){const e=this.#m.getActive();e!==t&&this.#m.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#Ro?.div&&!this.#Lo){this.#Lo=new AbortController;const t=this.#m.combinedSignal(this.#Lo);this.#Ro.div.addEventListener("pointerdown",this.#Oo.bind(this),{signal:t});this.#Ro.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#Ro?.div&&this.#Lo){this.#Lo.abort();this.#Lo=null;this.#Ro.div.classList.remove("highlighting")}}#Oo(t){this.#m.unselectAll();const{target:e}=t;if(e===this.#Ro.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#Ro.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(t.button!==0||t.ctrlKey&&e)return;this.#m.showAllEditors("highlight",true,true);this.#Ro.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,this.#m.direction==="ltr",{target:this.#Ro.div,x:t.x,y:t.y});this.#Ro.div.addEventListener("pointerup",(()=>{this.#Ro.div.classList.remove("free");this.toggleDrawing(true)}),{once:true,signal:this.#m._signal});t.preventDefault()}}enableClick(){if(this.#So)return;this.#So=new AbortController;const t=this.#m.combinedSignal(this.#So);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#So?.abort();this.#So=null}attach(t){this.#To.set(t.id,t);const{annotationElementId:e}=t;e&&this.#m.isDeletedAnnotationElement(e)&&this.#m.removeDeletedAnnotationElement(t)}detach(t){this.#To.delete(t.id);this.#Mn?.removePointerInTextLayer(t.contentDiv);!this.#Do&&t.annotationElementId&&this.#m.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#m.removeEditor(t);t.div.remove();t.isAttachedToDOM=false}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#m.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#m.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=true}t.fixAndSetPosition();t.onceAdded(!this.#Po);this.#m.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#Co){t._focusEventsAllowed=false;this.#Co=setTimeout((()=>{this.#Co=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=true;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=true}),{once:true,signal:this.#m._signal});e.focus()}}),0)}t._structTreeParentId=this.#Mn?.moveElementInDOM(this.div,t.div,t.contentDiv,true)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){const cmd=()=>t._uiManager.rebuild(t);const undo=()=>{t.remove()};this.addCommands({cmd:cmd,undo:undo,mustExec:false})}getNextId(){return this.#m.getId()}get#No(){return AnnotationEditorLayer.#G.get(this.#m.getMode())}combinedSignal(t){return this.#m.combinedSignal(t)}#Bo(t){const e=this.#No;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#No?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.#m.updateToolbar(t);await this.#m.updateMode(t);const{offsetX:s,offsetY:i}=this.#Uo();const n=this.getNextId();const a=this.#Bo({parent:this,id:n,x:s,y:i,uiManager:this.#m,isCentered:true,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#G.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#m))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId();const n=this.#Bo({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#m,isCentered:e,...s});n&&this.add(n);return n}#Uo(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect();const n=Math.max(0,t);const a=Math.max(0,e);const r=Math.min(window.innerWidth,t+s);const o=Math.min(window.innerHeight,e+i);const l=(n+r)/2-t;const h=(a+o)/2-e;const[c,d]=this.viewport.rotation%180===0?[l,h]:[h,l];return{offsetX:c,offsetY:d}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Uo(),true,t)}setSelected(t){this.#m.setSelected(t)}toggleSelected(t){this.#m.toggleSelected(t)}unselect(t){this.#m.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(t.button!==0||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Mo)return;this.#Mo=false;if(this.#No?.isDrawer&&this.#No.supportMultipleDrawings)return;if(!this.#_o){this.#_o=true;return}const s=this.#m.getMode();s!==h.STAMP&&s!==h.SIGNATURE?this.createAndAddNewEditor(t,false):this.#m.unselectAll()}pointerdown(t){this.#m.getMode()===h.HIGHLIGHT&&this.enableTextSelection();if(this.#Mo){this.#Mo=false;return}const{isMac:e}=util_FeatureTest.platform;if(t.button!==0||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Mo=true;if(this.#No?.isDrawer){this.startDrawingSession(t);return}const s=this.#m.getActive();this.#_o=!s||s.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:true});if(this.#Io){this.#No.startDrawing(this,this.#m,false,t);return}this.#m.setCurrentDrawingSession(this);this.#Io=new AbortController;const e=this.#m.combinedSignal(this.#Io);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#ko=null;this.commitOrRemove()}}),{signal:e});this.#No.startDrawing(this,this.#m,false,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#ko=t)}else this.#ko&&setTimeout((()=>{this.#ko?.focus();this.#ko=null}),0)}endDrawingSession(t=false){if(!this.#Io)return null;this.#m.setCurrentDrawingSession(null);this.#Io.abort();this.#Io=null;this.#ko=null;return this.#No.endDrawing(t)}findNewParent(t,e,s){const i=this.#m.findParent(e,s);if(i===null||i===this)return false;i.changeParent(t);return true}commitOrRemove(){if(this.#Io){this.endDrawingSession();return true}return false}onScaleChanging(){this.#Io&&this.#No.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#m.getActive()?.parent===this){this.#m.commitOrRemove();this.#m.setActiveEditor(null)}if(this.#Co){clearTimeout(this.#Co);this.#Co=null}for(const t of this.#To.values()){this.#Mn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=false;t.div.remove()}this.div=null;this.#To.clear();this.#m.removeLayer(this)}#Fo(){for(const t of this.#To.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#m.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#m.commitOrRemove();this.#Fo();const e=this.viewport.rotation;const s=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:s});if(e!==s)for(const t of this.#To.values())t.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#m.viewParameters.realScale}}class DrawLayer{#rn=null;#Ho=new Map;#zo=new Map;static#v=0;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#rn){if(this.#rn!==t){if(this.#Ho.size>0)for(const e of this.#Ho.values()){e.remove();t.append(e)}this.#rn=t}}else this.#rn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#Go(t,[e,s,i,n]){const{style:a}=t;a.top=100*s+"%";a.left=100*e+"%";a.width=100*i+"%";a.height=100*n+"%"}#Vo(){const t=DrawLayer._svgFactory.create(1,1,true);this.#rn.append(t);t.setAttribute("aria-hidden",true);return t}#$o(t,e){const s=DrawLayer._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i);s.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");s.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return i}#Wo(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=false,s=false){const i=DrawLayer.#v++;const n=this.#Vo();const a=DrawLayer._svgFactory.createElement("defs");n.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_p${this.pageIndex}_${i}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#zo.set(i,r);const l=s?this.#$o(a,o):null;const h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#Ho.set(i,n);return{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=DrawLayer.#v++;const i=this.#Vo();const n=DrawLayer._svgFactory.createElement("defs");i.append(n);const a=DrawLayer._svgFactory.createElement("path");n.append(a);const r=`path_p${this.pageIndex}_${s}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${s}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const i=DrawLayer._svgFactory.createElement("use");t.append(i);i.setAttribute("href",`#${r}`);i.setAttribute("stroke","none");i.setAttribute("fill","black");i.setAttribute("fill-rule","nonzero");i.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");i.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();i.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(i,t);this.#Ho.set(s,i);return s}finalizeDraw(t,e){this.#zo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:a}=e;const r=typeof t==="number"?this.#Ho.get(t):t;if(r){s&&this.#Wo(r,s);i&&DrawLayer.#Go(r,i);if(n){const{classList:t}=r;for(const[e,s]of Object.entries(n))t.toggle(e,s)}if(a){const t=r.firstChild;const e=t.firstChild;this.#Wo(e,a)}}}updateParent(t,e){if(e===this)return;const s=this.#Ho.get(t);if(s){e.#rn.append(s);this.#Ho.delete(t);e.#Ho.set(t,s)}}remove(t){this.#zo.delete(t);if(this.#rn!==null){this.#Ho.get(t).remove();this.#Ho.delete(t)}}destroy(){this.#rn=null;for(const t of this.#Ho.values())t.remove();this.#Ho.clear();this.#zo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:HighlightOutliner};var ht=e.AbortException;var ct=e.AnnotationEditorLayer;var dt=e.AnnotationEditorParamsType;var ut=e.AnnotationEditorType;var pt=e.AnnotationEditorUIManager;var gt=e.AnnotationLayer;var ft=e.AnnotationMode;var mt=e.AnnotationType;var bt=e.ColorPicker;var At=e.DOMSVGFactory;var wt=e.DrawLayer;var vt=e.FeatureTest;var yt=e.GlobalWorkerOptions;var Et=e.ImageKind;var _t=e.InvalidPDFException;var xt=e.MathClamp;var St=e.OPS;var Ct=e.OutputScale;
3var Tt=e.PDFDataRangeTransport;var Mt=e.PDFDateString;var Dt=e.PDFWorker;var Pt=e.PasswordResponses;var It=e.PermissionFlag;var kt=e.PixelsPerInch;var Rt=e.RenderingCancelledException;var Lt=e.ResponseException;var Ft=e.SignatureExtractor;var Ot=e.SupportedImageMimeTypes;var Nt=e.TextLayer;var Bt=e.TouchManager;var Ut=e.Util;var Ht=e.VerbosityLevel;var zt=e.XfaLayer;var Gt=e.build;var Vt=e.createValidAbsoluteUrl;var $t=e.fetchData;var Wt=e.getDocument;var jt=e.getFilenameFromUrl;var qt=e.getPdfFilenameFromUrl;var Xt=e.getUuid;var Kt=e.getXfaPageViewport;var Yt=e.isDataScheme;var Qt=e.isPdfFile;var Jt=e.isValidExplicitDest;var Zt=e.noContextMenu;var te=e.normalizeUnicode;var ee=e.setLayerDimensions;var se=e.shadow;var ie=e.stopEvent;var ne=e.version;export{ht as AbortException,ct as AnnotationEditorLayer,dt as AnnotationEditorParamsType,ut as AnnotationEditorType,pt as AnnotationEditorUIManager,gt as AnnotationLayer,ft as AnnotationMode,mt as AnnotationType,bt as ColorPicker,At as DOMSVGFactory,wt as DrawLayer,vt as FeatureTest,yt as GlobalWorkerOptions,Et as ImageKind,_t as InvalidPDFException,xt as MathClamp,St as OPS,Ct as OutputScale,Tt as PDFDataRangeTransport,Mt as PDFDateString,Dt as PDFWorker,Pt as PasswordResponses,It as PermissionFlag,kt as PixelsPerInch,Rt as RenderingCancelledException,Lt as ResponseException,Ft as SignatureExtractor,Ot as SupportedImageMimeTypes,Nt as TextLayer,Bt as TouchManager,Ut as Util,Ht as VerbosityLevel,zt as XfaLayer,Gt as build,Vt as createValidAbsoluteUrl,$t as fetchData,Wt as getDocument,jt as getFilenameFromUrl,qt as getPdfFilenameFromUrl,Xt as getUuid,Kt as getXfaPageViewport,Yt as isDataScheme,Qt as isPdfFile,Jt as isValidExplicitDest,Zt as noContextMenu,te as normalizeUnicode,ee as setLayerDimensions,se as shadow,ie as stopEvent,ne as version}; 4
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.