pdfjs-viewer-element 3.0.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ const t='/**\n * @licstart The following is the entire license notice for the\n * JavaScript code in this page\n *\n * Copyright 2024 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @licend The above is the entire license notice for the\n * JavaScript code in this page\n */var __webpack_require__={d:(t,e)=>{for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e)},__webpack_exports__={};const isNodeJS=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),FONT_IDENTITY_MATRIX=[.001,0,0,.001,0,0],LINE_FACTOR=1.35,LINE_DESCENT_FACTOR=.35,BASELINE_FACTOR=.35/1.35,RenderingIntentFlag={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},AnnotationMode={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},AnnotationEditorPrefix="pdfjs_internal_editor_",AnnotationEditorType={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},AnnotationEditorParamsType={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},PermissionFlag={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},MeshFigureType={TRIANGLES:1,LATTICE:2,PATCH:3},TextRenderingMode={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},util_ImageKind={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},AnnotationType={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},AnnotationReplyType={GROUP:"Group",REPLY:"R"},AnnotationFlag={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},AnnotationFieldFlag={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},AnnotationBorderStyleType={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},AnnotationActionEventType={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},DocumentActionEventType={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},PageActionEventType={O:"PageOpen",C:"PageClose"},VerbosityLevel={ERRORS:0,WARNINGS:1,INFOS:5},OPS={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},DrawOPS={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},PasswordResponses={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let verbosity=VerbosityLevel.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(verbosity=t)}function getVerbosityLevel(){return verbosity}function info(t){verbosity>=VerbosityLevel.INFOS&&console.info(`Info: ${t}`)}function warn(t){verbosity>=VerbosityLevel.WARNINGS&&console.warn(`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!0;default:return!1}}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=stringToUTF8String(t)}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return _isValidProtocol(n)?n:null}function updateUrlHash(t,e,i=!1){const n=URL.parse(t);return n?(n.hash=e,n.href):i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function shadow(t,e,i,n=!1){return Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1}),i}const BaseException=function(){function t(t,e){this.message=t,this.name=e}return t.prototype=new Error,t.constructor=t,t}();class PasswordException extends BaseException{constructor(t,e){super(t,"PasswordException"),this.code=e}}class UnknownErrorException extends BaseException{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class InvalidPDFException extends BaseException{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends BaseException{constructor(t,e,i){super(t,"ResponseException"),this.status=e,this.missing=i}}class FormatError extends BaseException{constructor(t){super(t,"FormatError")}}class AbortException extends BaseException{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const a=Math.min(s+i,e),r=t.subarray(s,a);n.push(String.fromCharCode.apply(null,r))}return n.join("")}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function objectSize(t){return Object.keys(t).length}function isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return 1===new Uint32Array(t.buffer,0,1)[0]}function isEvalSupported(){try{return new Function(""),!0}catch{return!1}}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","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return shadow(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const hexNumbers=Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0"));class Util{static makeHexColor(t,e,i){return`#${hexNumbers[t]}${hexNumbers[e]}${hexNumbers[i]}`}static domMatrixToTransform(t){return[t.a,t.b,t.c,t.d,t.e,t.f]}static scaleMinMax(t,e){let i;t[0]?(t[0]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[3],e[3]*=t[3]):(i=e[0],e[0]=e[1],e[1]=i,i=e[2],e[2]=e[3],e[3]=i,t[1]<0&&(i=e[1],e[1]=e[3],e[3]=i),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(i=e[0],e[0]=e[2],e[2]=i),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4],t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],a=e[2],r=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],d=t[i+e+1];t[i+e]=h*n+d*a+o,t[i+e+1]=h*s+d*r+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s,t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],a=e[2],r=e[3],o=e[4],l=e[5],h=t[0],d=t[1],c=t[2],u=t[3];let p=n*h+o,g=p,m=n*c+o,f=m,b=r*d+l,A=b,y=r*u+l,w=y;if(0!==s||0!==a){const t=s*h,e=s*c,i=a*d,n=a*u;p+=i,f+=i,m+=n,g+=n,b+=t,w+=t,y+=e,A+=e}i[0]=Math.min(i[0],p,m,g,f),i[1]=Math.min(i[1],b,y,A,w),i[2]=Math.max(i[2],p,m,g,f),i[3]=Math.max(i[3],b,y,A,w)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],a=t[3],r=i**2+n**2,o=i*s+n*a,l=s**2+a**2,h=(r+l)/2,d=Math.sqrt(h**2-(r*l-o**2));e[0]=Math.sqrt(h+d||1),e[1]=Math.sqrt(h-d||1)}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>a?null:[i,s,n,a]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t),i[1]=Math.min(i[1],e),i[2]=Math.max(i[2],t),i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i),s[1]=Math.min(s[1],e,n),s[2]=Math.max(s[2],t,i),s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,a,r,o,l,h){if(l<=0||l>=1)return;const d=1-l,c=l*l,u=c*l,p=d*(d*(d*t+3*l*e)+3*c*i)+u*n,g=d*(d*(d*s+3*l*a)+3*c*r)+u*o;h[0]=Math.min(h[0],p),h[1]=Math.min(h[1],g),h[2]=Math.max(h[2],p),h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,a,r,o,l,h,d,c){if(Math.abs(l)<1e-12)return void(Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,a,r,o,-d/h,c));const u=h**2-4*d*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,a,r,o,(-h+p)/g,c),this.#t(t,e,i,n,s,a,r,o,(-h-p)/g,c)}static bezierBoundingBox(t,e,i,n,s,a,r,o,l){l[0]=Math.min(l[0],t,r),l[1]=Math.min(l[1],e,o),l[2]=Math.max(l[2],t,r),l[3]=Math.max(l[3],e,o),this.#e(t,i,s,r,e,n,a,o,3*(3*(i-s)-t+r),6*(t-2*i+s),3*(i-t),l),this.#e(t,i,s,r,e,n,a,o,3*(3*(n-a)-e+o),6*(e-2*n+a),3*(n-e),l)}}const PDFStringTranslateTable=null;function stringToPDFString(t,e=!1){if(t[0]>="ï"){let i;if("þ"===t[0]&&"ÿ"===t[1]?(i="utf-16be",t.length%2==1&&(t=t.slice(0,-1))):"ÿ"===t[0]&&"þ"===t[1]?(i="utf-16le",t.length%2==1&&(t=t.slice(0,-1))):"ï"===t[0]&&"»"===t[1]&&"¿"===t[2]&&(i="utf-8"),i)try{const n=new TextDecoder(i,{fatal:!0}),s=stringToBytes(t),a=n.decode(s);return e||!a.includes("")?a:a.replaceAll(/\\x1b[^\\x1b]*(?:\\x1b|$)/g,"")}catch(t){warn(`stringToPDFString: "${t}".`)}}const i=[];for(let n=0,s=t.length;n<s;n++){const a=t.charCodeAt(n);if(!e&&27===a){for(;++n<s&&27!==t.charCodeAt(n););continue}const r=null[a];i.push(r?String.fromCharCode(r):t.charAt(n))}return i.join("")}function stringToUTF8String(t){return decodeURIComponent(escape(t))}function utf8StringToString(t){return unescape(encodeURIComponent(t))}function isArrayEqual(t,e){if(t.length!==e.length)return!1;for(let i=0,n=t.length;i<n;i++)if(t[i]!==e[i])return!1;return!0}function getModificationDate(t=new Date){t instanceof Date||(t=new Date(t));return[t.getUTCFullYear().toString(),(t.getUTCMonth()+1).toString().padStart(2,"0"),t.getUTCDate().toString().padStart(2,"0"),t.getUTCHours().toString().padStart(2,"0"),t.getUTCMinutes().toString().padStart(2,"0"),t.getUTCSeconds().toString().padStart(2,"0")].join("")}let NormalizeRegex=null,NormalizationMap=null;function normalizeUnicode(t){return NormalizeRegex||(NormalizeRegex=/([\\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,NormalizationMap=new Map([["ſt","ſt"]])),t.replaceAll(NormalizeRegex,(t,e,i)=>e?e.normalize("NFKC"):NormalizationMap.get(i))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);return crypto.getRandomValues(t),bytesToString(t)}const AnnotationPrefix="pdfjs_internal_id_";function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...a]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const r=a.length;let o=!0;switch(s.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;o=!1;break;default:return!1}for(const t of a)if(!("number"==typeof t||o&&null===t))return!1;return!0}function MathClamp(t,e,i){return Math.min(Math.max(t,e),i)}"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(t){return t.reduce((t,e)=>t+e,0)});class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};return function t(i){if(!i)return;let n=null;const s=i.name;if("#text"===s)n=i.value;else{if(!XfaText.shouldBuildText(s))return;i?.attributes?.textContent?n=i.attributes.textContent:i.value&&(n=i.value)}if(null!==n&&e.push({str:n}),i.children)for(const e of i.children)t(e)}(t),i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class XfaLayer{static setupStorage(t,e,i,n,s){const a=n.getValue(e,{value:null});switch(i.name){case"textarea":if(null!==a.value&&(t.textContent=a.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){if(a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked"),"print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{if(null!==a.value&&t.setAttribute("value",a.value),"print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${n}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&s.addLinkAttributes(t,a.href,a.newWindow),i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",a=document.createElement(n.name);n.attributes&&this.setAttributes({html:a,element:n,intent:s,linkService:i});const r="richText"!==s,o=t.div;if(o.append(a),t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);a.append(t),r&&XfaText.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,a]];for(;h.length>0;){const[t,n,a]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:d}=o;if("#text"===d){const t=document.createTextNode(o.value);l.push(t),a.append(t);continue}const c=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,d):document.createElement(d);if(a.append(c),o.attributes&&this.setAttributes({html:c,element:o,storage:e,intent:s,linkService:i}),o.children?.length>0)h.push([o,-1,c]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(d)&&l.push(t),c.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const SVG_NS="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":return void i(s.response)}i(s.responseText)}},s.send(null)})}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t,this.userUnit=e,this.scale=i,this.rotation=n,this.offsetX=s,this.offsetY=a,i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,d,c,u,p,g,m,f;switch((n%=360)<0&&(n+=360),n){case 180:h=-1,d=0,c=0,u=1;break;case 90:h=0,d=1,c=1,u=0;break;case 270:h=0,d=-1,c=-1,u=0;break;case 0:h=1,d=0,c=0,u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}r&&(c=-c,u=-u),0===h?(p=Math.abs(l-t[1])*i+s,g=Math.abs(o-t[0])*i+a,m=(t[3]-t[1])*i,f=(t[2]-t[0])*i):(p=Math.abs(o-t[0])*i+s,g=Math.abs(l-t[1])*i+a,m=(t[2]-t[0])*i,f=(t[3]-t[1])*i),this.transform=[h*i,d*i,c*i,u*i,p-h*i*o-c*i*l,g-d*i*o-u*i*l],this.width=m,this.height=f}get rawDims(){const t=this.viewBox;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];return Util.applyTransform(i,this.transform),i}convertToViewportRectangle(t){const e=[t[0],t[1]];Util.applyTransform(e,this.transform);const i=[t[2],t[3]];return Util.applyTransform(i,this.transform),[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){const i=[t,e];return Util.applyInverseTransform(i,this.transform),i}}class RenderingCancelledException extends BaseException{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\\.pdf$/i.test(t)}function getFilenameFromUrl(t){return[t]=t.split(/[#?]/,1),t.substring(t.lastIndexOf("/")+1)}function getPdfFilenameFromUrl(t,e="document.pdf"){if("string"!=typeof t)return e;if(isDataScheme(t))return warn(\'getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.\'),e;const i=(t=>{try{return new URL(t)}catch{try{return new URL(decodeURIComponent(t))}catch{try{return new URL(t,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{return null}}}}})(t);if(!i)return e;const n=t=>{try{let e=decodeURIComponent(t);return e.includes("/")?(e=e.split("/").at(-1),e.test(/^\\.pdf$/i)?e:t):e}catch{return t}},s=/\\.pdf$/i,a=i.pathname.split("/").at(-1);if(s.test(a))return n(a);if(i.searchParams.size>0){const t=Array.from(i.searchParams.values()).reverse();for(const e of t)if(s.test(e))return n(e);const e=Array.from(i.searchParams.keys()).reverse();for(const t of e)if(s.test(t))return n(t)}if(i.hash){const t=/[^/?#=]+\\.pdf\\b(?!.*\\.pdf\\b)/i.exec(i.hash);if(t)return n(t[0])}return e}class StatTimer{started=Object.create(null);times=[];time(t){t in this.started&&warn(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||warn(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:t}of this.times)e=Math.max(t.length,e);for(const{name:i,start:n,end:s}of this.times)t.push(`${i.padEnd(e)} ${s-n}ms\\n`);return t.join("")}}function isValidFetchUrl(t,e){const i=e?URL.parse(t,e):URL.parse(t);return"http:"===i?.protocol||"https:"===i?.protocol}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault(),t.stopPropagation()}function deprecated(t){console.log("Deprecated API usage: "+t)}class PDFDateString{static#i;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#i||=new RegExp("^D:(\\\\d{4})(\\\\d{2})?(\\\\d{2})?(\\\\d{2})?(\\\\d{2})?(\\\\d{2})?([Z|+|-])?(\\\\d{2})?\'?(\\\\d{2})?\'?");const e=this.#i.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s: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 d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,"-"===l?(a+=h,r+=d):"+"===l&&(a-=h,r-=d),new Date(Date.UTC(i,n,s,a,r,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style,a=[0,0,parseInt(n),parseInt(s)];return new PageViewport({viewBox:a,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}return t.startsWith("rgb(")?t.slice(4,-1).split(",").map(t=>parseInt(t)):t.startsWith("rgba(")?t.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(warn(`Not a valid color format: "${t}"`),[0,0,0])}function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,getRGB(n))}e.remove()}function getCurrentTransform(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform();return[e,i,n,s,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform().invertSelf();return[e,i,n,s,a,r]}function setLayerDimensions(t,e,i=!1,n=!0){if(e instanceof PageViewport){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:a}=t,r=util_FeatureTest.isCSSRoundSupported,o=`var(--total-scale-factor) * ${n}px`,l=`var(--total-scale-factor) * ${s}px`,h=r?`round(down, ${o}, var(--scale-round-x))`:`calc(${o})`,d=r?`round(down, ${l}, var(--scale-round-y))`:`calc(${l})`;i&&e.rotation%180!=0?(a.width=d,a.height=h):(a.width=h,a.height=d)}n&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;this.sx=t,this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let a=1/0,r=1/0,o=1/0;(i=OutputScale.capPixels(i,s))>0&&(a=Math.sqrt(i/(t*e))),-1!==n&&(r=n/t,o=n/e);const l=Math.min(a,r,o);return(this.sx>l||this.sy>l)&&(this.sx=l,this.sy=l,!0)}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const SupportedImageMimeTypes=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ColorScheme{static get isDarkMode(){return shadow(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class CSSConstants{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0",e.display="none",e.color="var(--comment-fg-color)",document.body.append(t);const{color:i}=window.getComputedStyle(t);return t.remove(),shadow(this,"commentForegroundColor",getRGB(i))}}function applyOpacity(t,e,i,n){const s=255*(1-(n=Math.min(Math.max(n??1,0),1)));return[t=Math.round(t*n+s),e=Math.round(e*n+s),i=Math.round(i*n+s)]}function RGBToHSL(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,a=Math.max(i,n,s),r=Math.min(i,n,s),o=(a+r)/2;if(a===r)e[0]=e[1]=0;else{const t=a-r;switch(e[1]=o<.5?t/(a+r):t/(2-a-r),a){case i:e[0]=60*((n-s)/t+(n<s?6:0));break;case n:e[0]=60*((s-i)/t+2);break;case s:e[0]=60*((i-n)/t+4)}}e[2]=o}function HSLToRGB(t,e){const i=t[0],n=t[1],s=t[2],a=(1-Math.abs(2*s-1))*n,r=a*(1-Math.abs(i/60%2-1)),o=s-a/2;switch(Math.floor(i/60)){case 0:e[0]=a+o,e[1]=r+o,e[2]=o;break;case 1:e[0]=r+o,e[1]=a+o,e[2]=o;break;case 2:e[0]=o,e[1]=a+o,e[2]=r+o;break;case 3:e[0]=o,e[1]=r+o,e[2]=a+o;break;case 4:e[0]=r+o,e[1]=o,e[2]=a+o;break;case 5:case 6:e[0]=a+o,e[1]=o,e[2]=r+o}}function computeLuminance(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function contrastRatio(t,e,i){HSLToRGB(t,i),i.map(computeLuminance);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];HSLToRGB(e,i),i.map(computeLuminance);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];return n>s?(n+.05)/(s+.05):(s+.05)/(n+.05)}const contrastCache=new Map;function findContrastColor(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=contrastCache.get(i);if(n)return n;const s=new Float32Array(9),a=s.subarray(0,3),r=s.subarray(3,6);RGBToHSL(t,r);const o=s.subarray(6,9);RGBToHSL(e,o);const l=o[2]<.5,h=l?12:4.5;if(r[2]=l?Math.sqrt(r[2]):1-Math.sqrt(1-r[2]),contrastRatio(r,o,a)<h){let t,e;l?(t=r[2],e=1):(t=0,e=r[2]);const i=.005;for(;e-t>i;){const i=r[2]=(t+e)/2;l===contrastRatio(r,o,a)<h?t=i:e=i}r[2]=l?e:t}return HSLToRGB(r,a),n=Util.makeHexColor(Math.round(255*a[0]),Math.round(255*a[1]),Math.round(255*a[2])),contrastCache.set(i,n),n}function renderRichText({html:t,dir:e,className:i},n){const s=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const n=t.split(/(?:\\r\\n?|\\n)/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s)),t<e-1&&i.append(document.createElement("br"))}s.append(i)}else XfaLayer.render({xfaHtml:t,div:s,intent:"richText"});s.firstElementChild.classList.add("richText",i),n.append(s)}function makePathFromDrawOPS(t){const e=new Path2D;if(!t)return e;for(let i=0,n=t.length;i<n;)switch(t[i++]){case DrawOPS.moveTo:e.moveTo(t[i++],t[i++]);break;case DrawOPS.lineTo:e.lineTo(t[i++],t[i++]);break;case DrawOPS.curveTo:e.bezierCurveTo(t[i++],t[i++],t[i++],t[i++],t[i++],t[i++]);break;case DrawOPS.quadraticCurveTo:e.quadraticCurveTo(t[i++],t[i++],t[i++],t[i++]);break;case DrawOPS.closePath:e.closePath();break;default:warn(`Unrecognized drawing path operator: ${t[i-1]}`)}return e}class PagesMapper{static#n=null;static#s=null;static#a=null;static#r=0;static#o=[];get pagesNumber(){return PagesMapper.#r}set pagesNumber(t){PagesMapper.#r!==t&&(PagesMapper.#r=t,0===t&&(PagesMapper.#s=null,PagesMapper.#n=null))}addListener(t){PagesMapper.#o.push(t)}removeListener(t){const e=PagesMapper.#o.indexOf(t);e>=0&&PagesMapper.#o.splice(e,1)}#l(){for(const t of PagesMapper.#o)t()}#h(t){if(PagesMapper.#s)return;const e=PagesMapper.#r,i=new Uint32Array(3*e),n=PagesMapper.#s=i.subarray(0,e),s=PagesMapper.#n=i.subarray(e,2*e);if(t)for(let t=0;t<e;t++)n[t]=s[t]=t+1;PagesMapper.#a=i.subarray(2*e)}movePages(t,e,i){this.#h(!0);const n=PagesMapper.#s,s=PagesMapper.#n;PagesMapper.#a.set(s);const a=e.length,r=new Uint32Array(a);let o=0;for(let t=0;t<a;t++){const s=e[t]-1;r[t]=n[s],s<i&&(o+=1)}const l=PagesMapper.#r;let h=i-o;const d=l-a;h=MathClamp(h,0,d);for(let e=0,i=0;e<l;e++)t.has(e+1)||(n[i++]=n[e]);n.copyWithin(h+a,h,d),n.set(r,h);let c=!1;for(let t=0,e=l;t<e;t++){const e=n[t];c||=e!==t+1,s[e-1]=t+1}this.#l(),c||(this.pagesNumber=0)}hasBeenAltered(){return null!==PagesMapper.#s}getPageMappingForSaving(){return{pageIndices:PagesMapper.#n?PagesMapper.#n.map(t=>t-1):null}}getPrevPageNumber(t){return PagesMapper.#a[PagesMapper.#s[t-1]-1]}getPageNumber(t){return PagesMapper.#n?.[t-1]??t}getPageId(t){return PagesMapper.#s?.[t-1]??t}static get instance(){return shadow(this,"instance",new PagesMapper)}getMapping(){return PagesMapper.#s.subarray(0,this.pagesNumber)}}class EditorToolbar{#d=null;#c=null;#u;#p=null;#g=null;#m=null;#f=null;#b=null;static#A=null;constructor(t){this.#u=t,EditorToolbar.#A||=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.#d=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#u._uiManager._signal;e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("contextmenu",noContextMenu,{signal:e}),t.addEventListener("pointerdown",EditorToolbar.#y,{signal:e}));const i=this.#p=document.createElement("div");i.className="buttons",t.append(i);const n=this.#u.toolbarPosition;if(n){const{style:e}=t,i="ltr"===this.#u._uiManager.direction?1-n[0]:n[0];e.insetInlineEnd=100*i+"%",e.top=`calc(${100*n[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#d}static#y(t){t.stopPropagation()}#w(t){this.#u._focusEventsAllowed=!1,stopEvent(t)}#v(t){this.#u._focusEventsAllowed=!0,stopEvent(t)}#E(t){const e=this.#u._uiManager._signal;return e instanceof AbortSignal&&!e.aborted&&(t.addEventListener("focusin",this.#w.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#v.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",noContextMenu,{signal:e}),!0)}hide(){this.#d.classList.add("hidden"),this.#c?.hideDropdown()}show(){this.#d.classList.remove("hidden"),this.#g?.shown(),this.#m?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#u,i=document.createElement("button");i.classList.add("basic","deleteButton"),i.tabIndex=0,i.setAttribute("data-l10n-id",EditorToolbar.#A[t]),this.#E(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal}),this.#p.append(i)}get#x(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#E(e),this.#p.append(e,this.#x),this.#g=t}addComment(t,e=null){if(this.#m)return;const i=t.renderForToolbar();if(!i)return;this.#E(i);const n=this.#f=this.#x;e?(this.#p.insertBefore(i,e),this.#p.insertBefore(n,e)):this.#p.append(i,n),this.#m=t,t.toolbar=this}addColorPicker(t){if(this.#c)return;this.#c=t;const e=t.renderButton();this.#E(e),this.#p.append(e,this.#x)}async addEditSignatureButton(t){const e=this.#b=await t.renderEditButton(this.#u);this.#E(e),this.#p.append(e,this.#x)}removeButton(t){if("comment"===t)this.#m?.removeToolbarCommentButton(),this.#m=null,this.#f?.remove(),this.#f=null}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;const n=this.#p.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#b&&(this.#b.title=t)}remove(){this.#d.remove(),this.#c?.destroy(),this.#c=null}}class FloatingToolbar{#p=null;#d=null;#T;constructor(t){this.#T=t}#S(){const t=this.#d=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar");const e=this.#T._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#p=document.createElement("div");return i.className="buttons",t.append(i),this.#T.hasCommentManager()&&this.#C("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#T.commentSelection("floating_button")}),this.#C("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#T.highlightSelection("floating_button")}),t}#_(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const a=s.x+(e?s.width:0);t>i?(n=a,i=t):e?a>n&&(n=a):a<n&&(n=a)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#_(e,i),{style:a}=this.#d||=this.#S();t.append(this.#d),a.insetInlineEnd=100*n+"%",a.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#d.remove()}#C(t,e,i,n){const s=document.createElement("button");s.classList.add("basic",t),s.tabIndex=0,s.setAttribute("data-l10n-id",e);const a=document.createElement("span");s.append(a),a.className="visuallyHidden",a.setAttribute("data-l10n-id",i);const r=this.#T._signal;r instanceof AbortSignal&&!r.aborted&&(s.addEventListener("contextmenu",noContextMenu,{signal:r}),s.addEventListener("click",n,{signal:r})),this.#p.append(s)}}function bindEvents(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class CurrentPointers{static#P=NaN;static#D=null;static#M=NaN;static#I=null;static initializeAndAddPointerId(t){(CurrentPointers.#D||=new Set).add(t)}static setPointer(t,e){CurrentPointers.#P||=e,CurrentPointers.#I??=t}static setTimeStamp(t){CurrentPointers.#M=t}static isSamePointerId(t){return CurrentPointers.#P===t}static isSamePointerIdOrRemove(t){return CurrentPointers.#P===t||(CurrentPointers.#D?.delete(t),!1)}static isSamePointerType(t){return CurrentPointers.#I===t}static isInitializedAndDifferentPointerType(t){return null!==CurrentPointers.#I&&!CurrentPointers.isSamePointerType(t)}static isSameTimeStamp(t){return CurrentPointers.#M===t}static isUsingMultiplePointers(){return CurrentPointers.#D?.size>=1}static clearPointerType(){CurrentPointers.#I=null}static clearPointerIds(){CurrentPointers.#P=NaN,CurrentPointers.#D=null}static clearTimeStamp(){CurrentPointers.#M=NaN}}class IdManager{#k=0;get id(){return`${AnnotationEditorPrefix}${this.#k++}`}}class ImageManager{#F=getUuid();#k=0;#R=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src=\'data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>\';return shadow(this,"_isSVGFittingCanvas",e.decode().then(()=>(t.drawImage(e,0,0,1,1,0,0,1,3),0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0])))}async#L(t,e){this.#R||=new Map;let i=this.#R.get(t);if(null===i)return null;if(i?.bitmap)return i.refCounter+=1,i;try{let t;if(i||={bitmap:null,id:`image_${this.#F}_${this.#k++}`,refCounter:0,isSvg:!1},"string"==typeof e?(i.url=e,t=await fetchData(e,"blob")):e instanceof File?t=i.file=e:e instanceof Blob&&(t=e),"image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,n=new FileReader,s=new Image,a=new Promise((t,a)=>{s.onload=()=>{i.bitmap=s,i.isSvg=!0,t()},n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t},s.onerror=n.onerror=a});n.readAsDataURL(t),await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t),i=null}return this.#R.set(t,i),i&&this.#R.set(i.id,i),i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#L(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#L(t,t)}async getFromBlob(t,e){const i=await e;return this.#L(t,i)}async getFromId(t){this.#R||=new Map;const e=this.#R.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;return delete e.blobPromise,this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#R||=new Map;let i=this.#R.get(t);if(i?.bitmap)return i.refCounter+=1,i;const n=new OffscreenCanvas(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),i={bitmap:n.transferToImageBitmap(),id:`image_${this.#F}_${this.#k++}`,refCounter:1,isSvg:!1},this.#R.set(t,i),this.#R.set(i.id,i),i}getSvgUrl(t){const e=this.#R.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#R||=new Map;const e=this.#R.get(t);if(!e)return;if(e.refCounter-=1,0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i),e.blobPromise=t.convertToBlob()}i.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#F}_`)}}class CommandManager{#B=[];#O=!1;#N;#U=-1;constructor(t=128){this.#N=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){if(n&&t(),this.#O)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#U)return this.#B.length>0&&(this.#B.length=0),this.#U=0,void this.#B.push(o);if(a&&this.#B[this.#U].type===s)return r&&(o.undo=this.#B[this.#U].undo),void(this.#B[this.#U]=o);const l=this.#U+1;l===this.#N?this.#B.splice(0,1):(this.#U=l,l<this.#B.length&&this.#B.splice(l)),this.#B.push(o)}undo(){if(-1===this.#U)return;this.#O=!0;const{undo:t,post:e}=this.#B[this.#U];t(),e?.(),this.#O=!1,this.#U-=1}redo(){if(this.#U<this.#B.length-1){this.#U+=1,this.#O=!0;const{cmd:t,post:e}=this.#B[this.#U];t(),e?.(),this.#O=!1}}hasSomethingToUndo(){return-1!==this.#U}hasSomethingToRedo(){return this.#U<this.#B.length-1}cleanType(t){if(-1!==this.#U){for(let e=this.#U;e>=0;e--)if(this.#B[e].type!==t)return this.#B.splice(e+1,this.#U-e),void(this.#U=e);this.#B.length=0,this.#U=-1}}destroy(){this.#B=null}}class KeyboardManager{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,n,s={}]of t)for(const t of i){const i=t.startsWith("mac+");e&&i?(this.callbacks.set(t.slice(4),{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1))):e||i||(this.callbacks.set(t,{callback:n,options:s}),this.allKeys.add(t.split("+").at(-1)))}}#H(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#H(e));if(!i)return;const{callback:n,options:{bubbles:s=!1,args:a=[],checker:r=null}}=i;r&&!r(t,e)||(n.bind(t,...a,e)(),s||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]]);return getColorValues(t),shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#G=new AbortController;#z=null;#V=null;#W=new Map;#j=new Map;#$=null;#K=null;#X=null;#Y=new CommandManager;#q=null;#J=null;#Q=null;#Z=0;#tt=new Set;#et=null;#it=null;#nt=new Set;_editorUndoBar=null;#st=!1;#at=!1;#rt=!1;#ot=null;#lt=null;#ht=null;#dt=null;#ct=!1;#ut=null;#pt=new IdManager;#gt=!1;#mt=!1;#ft=!1;#bt=null;#At=null;#yt=null;#wt=null;#vt=null;#Et=AnnotationEditorType.NONE;#xt=new Set;#Tt=null;#St=null;#Ct=null;#_t=null;#Pt=null;#Dt={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Mt=[0,0];#It=null;#kt=null;#Ft=null;#Rt=null;#Lt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,e=t=>t.#kt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),i=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},n=this.TRANSLATE_SMALL,s=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:i}],[["ctrl+z","mac+meta+z"],t.undo,{checker:i}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:i}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:i}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#kt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#kt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-s,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[s,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-s],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,s],checker:e}]]))}constructor(t,e,i,n,s,a,r,o,l,h,d,c,u,p,g,m){const f=this._signal=this.#G.signal;this.#kt=t,this.#Ft=e,this.#Rt=i,this.#$=n,this.#q=s,this.#St=a,this.#Pt=o,this._eventBus=r,r._on("editingaction",this.onEditingAction.bind(this),{signal:f}),r._on("pagechanging",this.onPageChanging.bind(this),{signal:f}),r._on("scalechanging",this.onScaleChanging.bind(this),{signal:f}),r._on("rotationchanging",this.onRotationChanging.bind(this),{signal:f}),r._on("setpreference",this.onSetPreference.bind(this),{signal:f}),r._on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),{signal:f}),r._on("pagesedited",this.onPagesEdited.bind(this),{signal:f}),window.addEventListener("pointerdown",()=>{this.#mt=!0},{capture:!0,signal:f}),window.addEventListener("pointerup",()=>{this.#mt=!1},{capture:!0,signal:f}),this.#Bt(),this.#Ot(),this.#Nt(),this.#K=o.annotationStorage,this.#ot=o.filterFactory,this.#Ct=l,this.#dt=h||null,this.#st=d,this.#at=c,this.#rt=u,this.#vt=p||null,this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=g||null,this._supportsPinchToZoom=!1!==m,s?.setSidebarUiManager(this)}destroy(){this.#Lt?.resolve(),this.#Lt=null,this.#G?.abort(),this.#G=null,this._signal=null;for(const t of this.#j.values())t.destroy();this.#j.clear(),this.#W.clear(),this.#nt.clear(),this.#wt?.clear(),this.#z=null,this.#xt.clear(),this.#Y.destroy(),this.#$?.destroy(),this.#q?.destroy(),this.#St?.destroy(),this.#ut?.hide(),this.#ut=null,this.#yt?.destroy(),this.#yt=null,this.#V=null,this.#lt&&(clearTimeout(this.#lt),this.#lt=null),this.#It&&(clearTimeout(this.#It),this.#It=null),this._editorUndoBar?.destroy(),this.#Pt=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#vt}get useNewAltTextFlow(){return this.#at}get useNewAltTextWhenAddingImage(){return this.#rt}get hcmFilter(){return shadow(this,"hcmFilter",this.#Ct?this.#ot.addHCMFilter(this.#Ct.foreground,this.#Ct.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#kt).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#dt?new Map(this.#dt.split(",").map(t=>((t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase(),t))):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return shadow(this,"highlightColors",null);const e=new Map,i=!!this.#Ct;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return shadow(this,"highlightColors",e)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#Q=t}setMainHighlightColorPicker(t){this.#yt=t}editAltText(t,e=!1){this.#$?.editAltText(this,t,e)}hasCommentManager(){return!!this.#q}editComment(t,e,i,n){this.#q?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#j.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#q?.updateComment(t.getData())}updatePopupColor(t){this.#q?.updatePopupColor(t)}removeComment(t){this.#q?.removeComments([t.uid])}deleteComment(t,e){const i=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,"comment"),this.toggleComment(null),t.comment=null},undo:i,mustExec:!0})}toggleComment(t,e,i=void 0){this.#q?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#q?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#q?.dialogElement||null}async waitForEditorsRendered(t){if(this.#j.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),n=i=>{i.pageNumber===t&&(this._eventBus._off("editorsrendered",n),e())};this._eventBus.on("editorsrendered",n),await i}getSignature(t){this.#St?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#St}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#rt=e}onPagesEdited({pagesMapper:t}){for(const e of this.#W.values())e.updatePageIndex(t.getPrevPageNumber(e.pageIndex+1)-1);const e=this.#j,i=this.#j=new Map;for(const[n,s]of e){const e=t.getPrevPageNumber(n+1)-1;-1!==e?(i.set(e,s),s.updatePageIndex(e)):s.destroy()}}onPageChanging({pageNumber:t}){this.#Z=t-1}focusMainContainer(){this.#kt.focus()}findParent(t,e){for(const i of this.#j.values()){const{x:n,y:s,width:a,height:r}=i.div.getBoundingClientRect();if(t>=n&&t<=n+a&&e>=s&&e<=s+r)return i}return null}disableUserSelect(t=!1){this.#Ft.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#nt.add(t)}removeShouldRescale(t){this.#nt.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#nt)t.onScaleChanging();this.#Q?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#Ut({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Ht(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#j.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r}=i,o=i.toString(),l=this.#Ut(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const d=this.#Ht(l),c=this.#Et===AnnotationEditorType.NONE,u=()=>{const i=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r,text:o});c&&this.showAllEditors("highlight",!0,!0),e&&i?.editComment()};c?this.switchToMode(AnnotationEditorType.HIGHLIGHT,u):u()}commentSelection(t=""){this.highlightSelection(t,!0)}#Gt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Ut(t).closest(".textLayer"),i=this.getSelectionBoxes(e);i&&(this.#ut||=new FloatingToolbar(this),this.#ut.show(e,i,"ltr"===this.direction))}getAndRemoveDataFromAnnotationStorage(t){if(!this.#K)return null;const e=`${AnnotationEditorPrefix}${t}`,i=this.#K.getRawValue(e);return i&&this.#K.remove(e),i}addToAnnotationStorage(t){t.isEmpty()||!this.#K||this.#K.has(t.id)||this.#K.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Rt;i&&(i.setAttribute("data-l10n-id",t),e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args"))}#zt(){const t=document.getSelection();if(!t||t.isCollapsed)return void(this.#Tt&&(this.#ut?.hide(),this.#Tt=null,this.#Vt({hasSelectedText:!1})));const{anchorNode:e}=t;if(e===this.#Tt)return;const i=this.#Ut(t).closest(".textLayer");if(i){if(this.#ut?.hide(),this.#Tt=e,this.#Vt({hasSelectedText:!0}),(this.#Et===AnnotationEditorType.HIGHLIGHT||this.#Et===AnnotationEditorType.NONE)&&(this.#Et===AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#ct=this.isShiftKeyDown,!this.isShiftKeyDown)){const t=this.#Et===AnnotationEditorType.HIGHLIGHT?this.#Ht(i):null;if(t?.toggleDrawing(),this.#mt){const e=new AbortController,i=this.combinedSignal(e),n=i=>{"pointerup"===i.type&&0!==i.button||(e.abort(),t?.toggleDrawing(!0),"pointerup"===i.type&&this.#Wt("main_toolbar"))};window.addEventListener("pointerup",n,{signal:i}),window.addEventListener("blur",n,{signal:i})}else t?.toggleDrawing(!0),this.#Wt("main_toolbar")}}else this.#Tt&&(this.#ut?.hide(),this.#Tt=null,this.#Vt({hasSelectedText:!1}))}#Wt(t=""){this.#Et===AnnotationEditorType.HIGHLIGHT?this.highlightSelection(t):this.#st&&this.#Gt()}#Bt(){document.addEventListener("selectionchange",this.#zt.bind(this),{signal:this._signal})}#jt(){if(this.#ht)return;this.#ht=new AbortController;const t=this.combinedSignal(this.#ht);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#$t(){this.#ht?.abort(),this.#ht=null}blur(){if(this.isShiftKeyDown=!1,this.#ct&&(this.#ct=!1,this.#Wt("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#xt)if(e.div.contains(t)){this.#At=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#At)return;const[t,e]=this.#At;this.#At=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#Nt(){if(this.#bt)return;this.#bt=new AbortController;const t=this.combinedSignal(this.#bt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Kt(){this.#bt?.abort(),this.#bt=null}#Xt(){if(this.#J)return;this.#J=new AbortController;const t=this.combinedSignal(this.#J);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})}#Yt(){this.#J?.abort(),this.#J=null}#Ot(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Nt(),this.setEditingState(!0)}removeEditListeners(){this.#Kt(),this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#it)if(i.isHandlingMimeForPasting(e))return t.dataTransfer.dropEffect="copy",void t.preventDefault()}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#it)if(i.isHandlingMimeForPasting(e.type))return i.paste(e,this.currentLayer),void t.preventDefault()}copy(t){if(t.preventDefault(),this.#z?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const t of this.#xt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#it)if(e.isHandlingMimeForPasting(t.type))return void e.paste(t,this.currentLayer);let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){return void warn(`paste: "${t.message}".`)}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const e=()=>{for(const e of t)this.#qt(e);this.#Jt(t)},s=()=>{for(const e of t)e.remove()};this.addCommands({cmd:e,undo:s,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0),this.#Et===AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&"Shift"===t.key&&(this.isShiftKeyDown=!1,this.#ct&&(this.#ct=!1,this.#Wt("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}#Vt(t){Object.entries(t).some(([t,e])=>this.#Dt[t]!==e)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#Dt,t)}),this.#Et===AnnotationEditorType.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Qt([[AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#Qt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#jt(),this.#Xt(),this.#Vt({isEditing:this.#Et!==AnnotationEditorType.NONE,isEmpty:this.#Zt(),hasSomethingToUndo:this.#Y.hasSomethingToUndo(),hasSomethingToRedo:this.#Y.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#$t(),this.#Yt(),this.#Vt({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#it){this.#it=t;for(const t of this.#it)this.#Qt(t.defaultPropertiesToUpdate)}}getId(){return this.#pt.id}get currentLayer(){return this.#j.get(this.#Z)}getLayer(t){return this.#j.get(t)}get currentPageIndex(){return this.#Z}addLayer(t){this.#j.set(t.pageIndex,t),this.#gt?t.enable():t.disable()}removeLayer(t){this.#j.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1,a=!1){if(this.#Et!==t&&(!this.#Lt||(await this.#Lt.promise,this.#Lt))){if(this.#Lt=Promise.withResolvers(),this.#Q?.commitOrRemove(),this.#Et===AnnotationEditorType.POPUP&&this.#q?.hideSidebar(),this.#q?.destroyPopup(),this.#Et=t,t===AnnotationEditorType.NONE){this.setEditingState(!1),this.#te();for(const t of this.#W.values())t.hideStandaloneCommentButton();return this._editorUndoBar?.hide(),this.toggleComment(null),void this.#Lt.resolve()}for(const t of this.#W.values())t.addStandaloneCommentButton();t===AnnotationEditorType.SIGNATURE&&await(this.#St?.loadSignatures()),i&&CurrentPointers.clearPointerType(),this.setEditingState(!0),await this.#ee(),this.unselectAll();for(const e of this.#j.values())e.updateMode(t);if(t===AnnotationEditorType.POPUP){this.#V||=await this.#Pt.getAnnotationsByType(new Set(this.#it.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#W.values()){const{annotationElementId:n,hasComment:s,deleted:a}=i;n&&t.add(n),s&&!a&&e.push(i.getData())}for(const i of this.#V){const{id:n,popupRef:s,contentsObj:a}=i;s&&a?.str&&!t.has(n)&&!this.#tt.has(n)&&e.push(i)}this.#q?.showSidebar(e)}if(!e)return n&&this.addNewEditorFromKeyboard(),void this.#Lt.resolve();for(const t of this.#W.values())t.uid===e?(this.setSelected(t),a?t.editComment():s?t.enterInEditMode():t.focus()):t.unselect();this.#Lt.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#Et&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#it){switch(t){case AnnotationEditorParamsType.CREATE:return void this.currentLayer.addNewEditor(e);case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#_t||=new Map).set(t,e),this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#xt)i.updateParams(t,e);else for(const i of this.#it)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#W.values())i.editorType===t&&i.show(e);(this.#_t?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Qt([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#ft!==t){this.#ft=t;for(const e of this.#j.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ee(){if(!this.#gt){this.#gt=!0;const t=[];for(const e of this.#j.values())t.push(e.enable());await Promise.all(t);for(const t of this.#W.values())t.enable()}}#te(){if(this.unselectAll(),this.#gt){this.#gt=!1;for(const t of this.#j.values())t.disable();for(const t of this.#W.values())t.disable()}}*getEditors(t){for(const e of this.#W.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#W.get(t)}addEditor(t){this.#W.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#lt&&clearTimeout(this.#lt),this.#lt=setTimeout(()=>{this.focusMainContainer(),this.#lt=null},0)),this.#W.delete(t.id),t.annotationElementId&&this.#wt?.delete(t.annotationElementId),this.unselect(t),t.annotationElementId&&this.#tt.has(t.annotationElementId)||this.#K?.remove(t.id)}addDeletedAnnotationElement(t){this.#tt.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#tt.has(t)}removeDeletedAnnotationElement(t){this.#tt.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#qt(t){const e=this.#j.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#z!==t&&(this.#z=t,t&&this.#Qt(t.propertiesToUpdate))}get#ie(){let t=null;for(t of this.#xt);return t}updateUI(t){this.#ie===t&&this.#Qt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Qt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#xt.has(t))return this.#xt.delete(t),t.unselect(),void this.#Vt({hasSelectedEditor:this.hasSelection});this.#xt.add(t),t.select(),this.#Qt(t.propertiesToUpdate),this.#Vt({hasSelectedEditor:!0})}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid}),this.#Q?.commitOrRemove();for(const e of this.#xt)e!==t&&e.unselect();this.#xt.clear(),this.#xt.add(t),t.select(),this.#Qt(t.propertiesToUpdate),this.#Vt({hasSelectedEditor:!0})}isSelected(t){return this.#xt.has(t)}get firstSelectedEditor(){return this.#xt.values().next().value}unselect(t){t.unselect(),this.#xt.delete(t),this.#Vt({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#xt.size}get isEnterHandled(){return 1===this.#xt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#Y.undo(),this.#Vt({hasSomethingToUndo:this.#Y.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Zt()}),this._editorUndoBar?.hide()}redo(){this.#Y.redo(),this.#Vt({hasSomethingToUndo:!0,hasSomethingToRedo:this.#Y.hasSomethingToRedo(),isEmpty:this.#Zt()})}addCommands(t){this.#Y.add(t),this.#Vt({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Zt()})}cleanUndoStack(t){this.#Y.cleanType(t)}#Zt(){if(0===this.#W.size)return!0;if(1===this.#W.size)for(const t of this.#W.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#xt],i=()=>{for(const t of e)this.#qt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(i,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo:i,mustExec:!0})}commitOrRemove(){this.#z?.commitOrRemove()}hasSomethingToControl(){return this.#z||this.hasSelection}#Jt(t){for(const t of this.#xt)t.unselect();this.#xt.clear();for(const e of t)e.isEmpty()||(this.#xt.add(e),e.select());this.#Vt({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#xt)t.commit();this.#Jt(this.#W.values())}unselectAll(){if((!this.#z||(this.#z.commitOrRemove(),this.#Et===AnnotationEditorType.NONE))&&!this.#Q?.commitOrRemove()&&this.hasSelection){for(const t of this.#xt)t.unselect();this.#xt.clear(),this.#Vt({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){if(i||this.commitOrRemove(),!this.hasSelection)return;this.#Mt[0]+=t,this.#Mt[1]+=e;const[n,s]=this.#Mt,a=[...this.#xt];this.#It&&clearTimeout(this.#It),this.#It=setTimeout(()=>{this.#It=null,this.#Mt[0]=this.#Mt[1]=0,this.addCommands({cmd:()=>{for(const t of a)this.#W.has(t.id)&&(t.translateInPage(n,s),t.translationDone())},undo:()=>{for(const t of a)this.#W.has(t.id)&&(t.translateInPage(-n,-s),t.translationDone())},mustExec:!1})},1e3);for(const i of a)i.translateInPage(t,e),i.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#et=new Map;for(const t of this.#xt)this.#et.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#et)return!1;this.disableUserSelect(!1);const t=this.#et;this.#et=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},a]of t)a.newX=i,a.newY=n,a.newPageIndex=s,e||=i!==a.savedX||n!==a.savedY||s!==a.savedPageIndex;if(!e)return!1;const i=(t,e,i,n)=>{if(this.#W.has(t.id)){const s=this.#j.get(n);s?t._setParentAndPosition(s,e,i):(t.pageIndex=n,t.x=e,t.y=i)}};return this.addCommands({cmd:()=>{for(const[e,{newX:n,newY:s,newPageIndex:a}]of t)i(e,n,s,a)},undo:()=>{for(const[e,{savedX:n,savedY:s,savedPageIndex:a}]of t)i(e,n,s,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#et)for(const i of this.#et.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#xt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#z===t}getActive(){return this.#z}getMode(){return this.#Et}isEditingMode(){return this.#Et!==AnnotationEditorType.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-n)/a,y:1-(t+r-i)/s,width:o/a,height:r/s});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/s,y:1-(e+o-n)/a,width:r/s,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-n)/a,y:(t-i)/s,width:o/a,height:r/s});break;default:r=(t,e,r,o)=>({x:(t-i)/s,y:(e-n)/a,width:r/s,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(r(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#X||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#X?.delete(t)}renderAnnotationElement(t){const e=this.#X?.get(t.data.id);if(!e)return;const i=this.#K.getRawValue(e);i&&(this.#Et!==AnnotationEditorType.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const n=this.#wt?.get(t);n&&(n.setCanvas(e,i),this.#wt.delete(t))}addMissingCanvas(t,e){(this.#wt||=new Map).set(t,e)}}class AltText{#g=null;#ne=!1;#se=null;#ae=null;#re=null;#oe=null;#le=!1;#he=null;#u=null;#de=null;#ce=null;#ue=!1;static#pe=null;static _l10n=null;constructor(t){this.#u=t,this.#ue=t._uiManager.useNewAltTextFlow,AltText.#pe||=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.#se=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#ae=document.createElement("span");t.append(e),this.#ue?(t.classList.add("new"),t.setAttribute("data-l10n-id",AltText.#pe.missing),e.setAttribute("data-l10n-id",AltText.#pe["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const i=this.#u._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:i}),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=t=>{t.preventDefault(),this.#u._uiManager.editAltText(this.#u),this.#ue&&this.#u._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#ge}})};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#le=!0,n(e))},{signal:i}),await this.#me(),t}get#ge(){return(this.#g?"added":null===this.#g&&this.guessedText&&"review")||"missing"}finish(){this.#se&&(this.#se.focus({focusVisible:this.#le}),this.#le=!1)}isEmpty(){return this.#ue?null===this.#g:!this.#g&&!this.#ne}hasData(){return this.#ue?null!==this.#g||!!this.#de:this.isEmpty()}get guessedText(){return this.#de}async setGuessedText(t){null===this.#g&&(this.#de=t,this.#ce=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#me())}toggleAltTextBadge(t=!1){if(!this.#ue||this.#g)return this.#he?.remove(),void(this.#he=null);if(!this.#he){const t=this.#he=document.createElement("div");t.className="noAltTextBadge",this.#u.div.append(t)}this.#he.classList.toggle("hidden",!t)}serialize(t){let e=this.#g;return t||this.#de!==e||(e=this.#ce),{altText:e,decorative:this.#ne,guessedText:this.#de,textWithDisclaimer:this.#ce}}get data(){return{altText:this.#g,decorative:this.#ne}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){i&&(this.#de=i,this.#ce=n),this.#g===t&&this.#ne===e||(s||(this.#g=t,this.#ne=e),this.#me())}toggle(t=!1){this.#se&&(!t&&this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#se.disabled=!t)}shown(){this.#u._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#ge}})}destroy(){this.#se?.remove(),this.#se=null,this.#ae=null,this.#re=null,this.#he?.remove(),this.#he=null}async#me(){const t=this.#se;if(!t)return;if(this.#ue){if(t.classList.toggle("done",!!this.#g),t.setAttribute("data-l10n-id",AltText.#pe[this.#ge]),this.#ae?.setAttribute("data-l10n-id",AltText.#pe[`${this.#ge}-label`]),!this.#g)return void this.#re?.remove()}else{if(!this.#g&&!this.#ne)return t.classList.remove("done"),void this.#re?.remove();t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#re;if(!e){this.#re=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#u.id}`;const i=100,n=this.#u._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#oe),this.#oe=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#oe=setTimeout(()=>{this.#oe=null,this.#re.classList.add("show"),this.#u._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#oe&&(clearTimeout(this.#oe),this.#oe=null),this.#re?.classList.remove("show")},{signal:n})}this.#ne?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#g),e.parentNode||t.append(e);const i=this.#u.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#fe=null;#be=null;#Ae=!1;#u=null;#ye=null;#we=null;#ve=null;#Ee=null;#xe=!1;#Te=null;constructor(t){this.#u=t}renderForToolbar(){const t=this.#be=document.createElement("button");return t.className="comment",this.#S(t,!1)}renderForStandalone(){const t=this.#fe=document.createElement("button");t.className="annotationCommentButton";const e=this.#u.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#u._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`,i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#u.commentButtonColor;n&&(i.backgroundColor=n)}return this.#S(t,!0)}focusButton(){setTimeout(()=>{(this.#fe??this.#be)?.focus()},0)}onUpdatedColor(){if(!this.#fe)return;const t=this.#u.commentButtonColor;t&&(this.#fe.style.backgroundColor=t),this.#u._uiManager.updatePopupColor(this.#u)}get commentButtonWidth(){return(this.#fe?.getBoundingClientRect().width??0)/this.#u.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#Te)return this.#Te;if(!this.#fe)return null;const{x:t,y:e,height:i}=this.#fe.getBoundingClientRect(),{x:n,y:s,width:a,height:r}=this.#u.parent.boundingClientRect;return[(t-n)/a,(e+i-s)/r]}set commentPopupPositionInLayer(t){this.#Te=t}hasDefaultPopupPosition(){return null===this.#Te}removeStandaloneCommentButton(){this.#fe?.remove(),this.#fe=null}removeToolbarCommentButton(){this.#be?.remove(),this.#be=null}setCommentButtonStates({selected:t,hasPopup:e}){this.#fe&&(this.#fe.classList.toggle("selected",t),this.#fe.ariaExpanded=e)}#S(t,e){if(!this.#u._uiManager.hasCommentManager())return null;t.tabIndex="0",t.ariaHasPopup="dialog",e?(t.ariaControls="commentPopup",t.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(t.ariaControlsElements=[this.#u._uiManager.getCommentDialogElement()],t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const i=this.#u._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i}),e&&(t.addEventListener("focusin",t=>{this.#u._focusEventsAllowed=!1,stopEvent(t)},{capture:!0,signal:i}),t.addEventListener("focusout",t=>{this.#u._focusEventsAllowed=!0,stopEvent(t)},{capture:!0,signal:i})),t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const n=e=>{e.preventDefault(),t===this.#be?this.edit():this.#u.toggleComment(!0)};return t.addEventListener("click",n,{capture:!0,signal:i}),t.addEventListener("keydown",e=>{e.target===t&&"Enter"===e.key&&(this.#Ae=!0,n(e))},{signal:i}),t.addEventListener("pointerenter",()=>{this.#u.toggleComment(!1,!0)},{signal:i}),t.addEventListener("pointerleave",()=>{this.#u.toggleComment(!1,!1)},{signal:i}),t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#u.commentButtonPosition;const{width:t,height:e,x:s,y:a}=this.#u;i=s+i*t,n=a+n*e}const s=this.#u.parent.boundingClientRect,{x:a,y:r,width:o,height:l}=s;this.#u._uiManager.editComment(this.#u,a+i*o,r+n*l,{...t,parentDimensions:s})}finish(){this.#be&&(this.#be.focus({focusVisible:this.#Ae}),this.#Ae=!1)}isDeleted(){return this.#xe||""===this.#ve}isEmpty(){return null===this.#ve}hasBeenEdited(){return this.isDeleted()||this.#ve!==this.#ye}serialize(){return this.data}get data(){return{text:this.#ve,richText:this.#we,date:this.#Ee,deleted:this.isDeleted()}}set data(t){if(t!==this.#ve&&(this.#we=null),null===t)return this.#ve="",void(this.#xe=!0);this.#ve=t,this.#Ee=new Date,this.#xe=!1}restoreData({text:t,richText:e,date:i}){this.#ve=t,this.#we=e,this.#Ee=i,this.#xe=!1}setInitialText(t,e=null){this.#ye=t,this.data=t,this.#Ee=null,this.#we=e}shown(){}destroy(){this.#be?.remove(),this.#be=null,this.#fe?.remove(),this.#fe=null,this.#ve="",this.#we=null,this.#Ee=null,this.#u=null,this.#Ae=!1,this.#xe=!1}}class TouchManager{#kt;#Se=!1;#Ce=null;#_e;#Pe;#De;#Me;#Ie=null;#ke;#Fe=null;#Re;#Le=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:a=null,signal:r}){this.#kt=t,this.#Ce=i,this.#_e=e,this.#Pe=n,this.#De=s,this.#Me=a,this.#Re=new AbortController,this.#ke=AbortSignal.any([r,this.#Re.signal]),t.addEventListener("touchstart",this.#Be.bind(this),{passive:!1,signal:this.#ke})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#Be(t){if(this.#_e?.())return;if(1===t.touches.length){if(this.#Ie)return;const t=this.#Ie=new AbortController,e=AbortSignal.any([this.#ke,t.signal]),i=this.#kt,n={capture:!0,signal:e,passive:!1},s=t=>{"touch"===t.pointerType&&(this.#Ie?.abort(),this.#Ie=null)};return i.addEventListener("pointerdown",t=>{"touch"===t.pointerType&&(stopEvent(t),s(t))},n),i.addEventListener("pointerup",s,n),void i.addEventListener("pointercancel",s,n)}if(!this.#Le){this.#Le=new AbortController;const t=AbortSignal.any([this.#ke,this.#Le.signal]),e=this.#kt,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Oe.bind(this),i);const n=this.#Ne.bind(this);e.addEventListener("touchend",n,i),e.addEventListener("touchcancel",n,i),i.capture=!0,e.addEventListener("pointerdown",stopEvent,i),e.addEventListener("pointermove",stopEvent,i),e.addEventListener("pointercancel",stopEvent,i),e.addEventListener("pointerup",stopEvent,i),this.#Pe?.()}if(stopEvent(t),2!==t.touches.length||this.#Ce?.())return void(this.#Fe=null);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]),this.#Fe={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Oe(t){if(!this.#Fe||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:a,screenY:r}=i,o=this.#Fe,{touch0X:l,touch0Y:h,touch1X:d,touch1Y:c}=o,u=d-l,p=c-h,g=a-n,m=r-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#Se&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(o.touch0X=n,o.touch0Y=s,o.touch1X=a,o.touch1Y=r,!this.#Se)return void(this.#Se=!0);const A=[(n+a)/2,(s+r)/2];this.#De?.(A,b,f)}#Ne(t){t.touches.length>=2||(this.#Le&&(this.#Le.abort(),this.#Le=null,this.#Me?.()),this.#Fe&&(stopEvent(t),this.#Fe=null,this.#Se=!1))}destroy(){this.#Re?.abort(),this.#Re=null,this.#Ie?.abort(),this.#Ie=null}}class AnnotationEditor{#Ue=null;#He=null;#g=null;#m=null;#fe=null;#Ge=!1;#ze=null;#Ve="";#We=null;#je=null;#$e=null;#Ke=null;#Xe=null;#Ye="";#qe=!1;#Je=null;#Qe=!1;#Ze=!1;#ti=!1;#ei=null;#ii=0;#ni=0;#si=null;#ai=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#ri=!1;#oi=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null,this.annotationElementId=t.annotationElementId||null,this.creationDate=t.creationDate||new Date,this.modificationDate=t.modificationDate||null,this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:a}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[i,n],this.pageTranslation=[s,a];const[r,o]=this.parentDimensions;this.x=t.x/r,this.y=t.y/o,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(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"}),-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ri}set _isDraggable(t){this.#ri=t,this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t),this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t),this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#oi}setParent(t){null!==t?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):(this.#li(),this.#Ke?.remove(),this.#Ke=null),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#qe?this.#qe=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;e?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,a]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n),this.x=(t+i)/s,this.y=(e+n)/a,this.fixAndSetPosition()}_moveAfterPaste(t,e){const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n),this._onTranslated()}#hi([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n),this.x+=i/t,this.y+=n/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#hi(this.parentDimensions,t,e)}translateInPage(t,e){this.#Je||=[this.x,this.y,this.width,this.height],this.#hi(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Je||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;if(this.x+=t/n,this.y+=e/s,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();this.parent.findNewParent(this,t,e)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o,r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`,h.top=`${(100*r).toFixed(2)}%`,this._onTranslating(a,r),i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Je&&(this.#Je[0]!==this.x||this.#Je[1]!==this.y)}get _hasBeenResized(){return!!this.#Je&&(this.#Je[2]!==this.width||this.#Je[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:a,width:r,height:o}=this;if(r*=i,o*=n,s*=i,a*=n,this._mustFixPosition)switch(t){case 0:s=MathClamp(s,0,i-r),a=MathClamp(a,0,n-o);break;case 90:s=MathClamp(s,0,i-o),a=MathClamp(a,r,n);break;case 180:s=MathClamp(s,r,i),a=MathClamp(a,o,n);break;case 270:s=MathClamp(s,o,i),a=MathClamp(a,0,n-r)}this.x=s/=i,this.y=a/=n;const[l,h]=this.getBaseTranslation();s+=l,a+=h,e.left=`${(100*s).toFixed(2)}%`,e.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#di(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#di(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#di(t,e,360-this.parentRotation)}#ci(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`,t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#ui(){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"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#We.append(t),t.classList.add("resizer",i),t.setAttribute("data-resizer-name",i),t.addEventListener("pointerdown",this.#pi.bind(this,i),{signal:e}),t.addEventListener("contextmenu",noContextMenu,{signal:e}),t.tabIndex=-1}this.div.prepend(this.#We)}#pi(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#g?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1,this.#je=[e.screenX,e.screenY];const s=new AbortController,a=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#gi.bind(this,t),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a}),window.addEventListener("contextmenu",noContextMenu,{signal:a}),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{s.abort(),this.parent.togglePointerEvents(!0),this.#g?.toggle(!0),this._isDraggable=n,this.parent.div.style.cursor=r,this.div.style.cursor=o,this.#mi()};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}#fi(t,e,i,n){this.width=i,this.height=n,this.x=t,this.y=e,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#mi(){if(!this.#$e)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#$e;this.#$e=null;const s=this.x,a=this.y,r=this.width,o=this.height;s===t&&a===e&&r===i&&o===n||this.addCommands({cmd:this.#fi.bind(this,s,a,r,o),undo:this.#fi.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#gi(t,e){const[i,n]=this.parentDimensions,s=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/n,d=this.#ci(this.rotation),c=(t,e)=>[d[0]*t+d[2]*e,d[1]*t+d[3]*e],u=this.#ci(360-this.rotation);let p,g,m=!1,f=!1;switch(t){case"topLeft":m=!0,p=(t,e)=>[0,0],g=(t,e)=>[t,e];break;case"topMiddle":p=(t,e)=>[t/2,0],g=(t,e)=>[t/2,e];break;case"topRight":m=!0,p=(t,e)=>[t,0],g=(t,e)=>[0,e];break;case"middleRight":f=!0,p=(t,e)=>[t,e/2],g=(t,e)=>[0,e/2];break;case"bottomRight":m=!0,p=(t,e)=>[t,e],g=(t,e)=>[0,0];break;case"bottomMiddle":p=(t,e)=>[t/2,e],g=(t,e)=>[t/2,0];break;case"bottomLeft":m=!0,p=(t,e)=>[0,e],g=(t,e)=>[t,0];break;case"middleLeft":f=!0,p=(t,e)=>[0,e/2],g=(t,e)=>[t,e/2]}const b=p(r,o),A=g(r,o);let y=c(...A);const w=AnnotationEditor._round(s+y[0]),v=AnnotationEditor._round(a+y[1]);let E,x,T=1,S=1;if(e.fromKeyboard)({deltaX:E,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#je;[E,x]=this.screenToPageTranslation(t-n,i-s),this.#je[0]=t,this.#je[1]=i}var C,_;if([E,x]=(C=E/i,_=x/n,[u[0]*C+u[2]*_,u[1]*C+u[3]*_]),m){const t=Math.hypot(r,o);T=S=Math.max(Math.min(Math.hypot(A[0]-b[0]-E,A[1]-b[1]-x)/t,1/r,1/o),l/r,h/o)}else f?T=MathClamp(Math.abs(A[0]-b[0]-E),l,1)/r:S=MathClamp(Math.abs(A[1]-b[1]-x),h,1)/o;const P=AnnotationEditor._round(r*T),D=AnnotationEditor._round(o*S);y=c(...g(P,D));const M=w-y[0],I=v-y[1];this.#Je||=[this.x,this.y,this.width,this.height],this.width=P,this.height=D,this.x=M,this.y=I,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#g?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#Ze)return this._editToolbar;this._editToolbar=new EditorToolbar(this),this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#g?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#g||(AltText.initialize(AnnotationEditor._l10n),this.#g=new AltText(this),this.#Ue&&(this.#g.data=this.#Ue,this.#Ue=null)),this.#g}get altTextData(){return this.#g?.data}set altTextData(t){this.#g&&(this.#g.data=t)}get guessedAltText(){return this.#g?.guessedText}async setGuessedAltText(t){await(this.#g?.setGuessedText(t))}serializeAltText(t){return this.#g?.serialize(t)}hasAltText(){return!!this.#g&&!this.#g.isEmpty()}hasAltTextData(){return this.#g?.hasData()??!1}focusCommentButton(){this.#m?.focusButton()}addCommentButton(){return this.canAddComment?this.#m||=new Comment(this):null}addStandaloneCommentButton(){this._uiManager.hasCommentManager()&&(this.#fe?this._uiManager.isEditingMode()&&this.#fe.classList.remove("hidden"):this.hasComment&&(this.#fe=this.#m.renderForStandalone(),this.div.append(this.#fe)))}removeStandaloneCommentButton(){this.#m.removeStandaloneCommentButton(),this.#fe=null}hideStandaloneCommentButton(){this.#fe?.classList.add("hidden")}get comment(){if(!this.#m)return null;const{data:{richText:t,text:e,date:i,deleted:n}}=this.#m;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#m||=new Comment(this),"object"==typeof t&&null!==t?this.#m.restoreData(t):this.#m.data=t,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;if(this.#m||=new Comment(this),this.#m.setInitialText(t,i),!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#m?.hasBeenEdited()}get hasDeletedComment(){return this.#m?.isDeleted()}get hasComment(){return!!this.#m&&!this.#m.isEmpty()&&!this.#m.isDeleted()}async editComment(t){this.#m||=new Comment(this),this.#m.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#m.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[a]=this.pageTranslation,r=a+s+1,o=n-i,l=r+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[r,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#m.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360),t.className=this.name,t.setAttribute("id",this.id),t.tabIndex=this.#Ge?-1:0,t.setAttribute("role","application"),this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||t.classList.add("hidden"),this.setInForeground(),this.#bi();const[e,i]=this.parentDimensions;this.parentRotation%180!=0&&(t.style.maxWidth=`${(100*i/e).toFixed(2)}%`,t.style.maxHeight=`${(100*e/i).toFixed(2)}%`);const[n,s]=this.getInitialTranslation();return this.translate(n,s),bindEvents(this,t,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ai||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#Ai.bind(this),onPinching:this.#yi.bind(this),onPinchEnd:this.#wi.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),t}#Ai(){this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#g?.toggle(!1),this.parent.togglePointerEvents(!1)}#yi(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#ci(this.rotation),a=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[r,o]=this.parentDimensions,l=this.x,h=this.y,d=this.width,c=this.height,u=AnnotationEditor.MIN_SIZE/r,p=AnnotationEditor.MIN_SIZE/o;n=Math.max(Math.min(n,1/d,1/c),u/d,p/c);const g=AnnotationEditor._round(d*n),m=AnnotationEditor._round(c*n);if(g===d&&m===c)return;this.#Je||=[l,h,d,c];const f=a(d/2,c/2),b=AnnotationEditor._round(l+f[0]),A=AnnotationEditor._round(h+f[1]),y=a(g/2,m/2);this.x=b-y[0],this.y=A-y[1],this.width=g,this.height=m,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#wi(){this.#g?.toggle(!0),this.parent.togglePointerEvents(!0),this.#mi()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;0!==t.button||t.ctrlKey&&e?t.preventDefault():(this.#qe=!0,this._isDraggable?this.#vi(t):this.#Ei(t))}#Ei(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#vi(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),a={capture:!0,passive:!1,signal:s},r=t=>{n.abort(),this.#ze=null,this.#qe=!1,this._uiManager.endDragSession()||this.#Ei(t),i&&this._onStopDragging()};e&&(this.#ii=t.clientX,this.#ni=t.clientY,this.#ze=t.pointerId,this.#Ve=t.pointerType,window.addEventListener("pointermove",t=>{i||(i=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#ze)return void stopEvent(t);const[a,r]=this.screenToPageTranslation(e-this.#ii,n-this.#ni);this.#ii=e,this.#ni=n,this._uiManager.dragSelectedEditors(a,r)},a),window.addEventListener("touchmove",stopEvent,a),window.addEventListener("pointerdown",t=>{t.pointerType===this.#Ve&&(this.#ai||t.isPrimary)&&r(t),stopEvent(t)},a));const o=t=>{this.#ze&&this.#ze!==t.pointerId?stopEvent(t):r(t)};window.addEventListener("pointerup",o,{signal:s}),window.addEventListener("blur",o,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#ei&&clearTimeout(this.#ei),this.#ei=setTimeout(()=>{this.#ei=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this),this.x=e,this.y=i,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/n,h=e/n,d=this.x*s,c=this.y*a,u=this.width*s,p=this.height*a;switch(i){case 0:return[d+l+r,a-c-h-p+o,d+l+u+r,a-c-h+o];case 90:return[d+h+r,a-c+l+o,d+h+p+r,a-c+l+u+o];case 180:return[d-l-u+r,a-c+h+o,d-l+r,a-c+h+p+o];case 270:return[d-h-p+r,a-c-l-u+o,d-h+r,a-c-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,a]=t,r=s-i,o=a-n;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-n,o,r];case 180:return[s,e-n,r,o];case 270:return[s,e-a,o,r];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#m?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:a},uid:r,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:r,pageIndex:o,rect:this.getPDFRect(),richText:a,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#Ze=!0,!0)}disableEditMode(){return!!this.isInEditMode()&&(this.parent.setEditingState(!0),this.#Ze=!1,!0)}isInEditMode(){return this.#Ze}shouldGetKeyboardEvents(){return this.#ti}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:a}=window;return e<a&&n>0&&t<s&&i>0}#bi(){if(this.#Xe||!this.div)return;this.#Xe=new AbortController;const t=this._uiManager.combinedSignal(this.#Xe);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#bi()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation,n.#Ue=t.accessibilityData,n._isCopy=t.isCopy||!1;const[s,a]=n.pageDimensions,[r,o,l,h]=n.getRectInCurrentCoords(t.rect,a);return n.x=r/s,n.y=o/a,n.width=l/s,n.height=h/a,n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){if(this.#Xe?.abort(),this.#Xe=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#ei&&(clearTimeout(this.#ei),this.#ei=null),this.#li(),this.removeEditToolbar(),this.#si){for(const t of this.#si.values())clearTimeout(t);this.#si=null}this.parent=null,this.#ai?.destroy(),this.#ai=null,this.#Ke?.remove(),this.#Ke=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#ui(),this.#We.classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,a]=this.getPDFRect();return[AnnotationEditor._round(i+(s-i)*t),AnnotationEditor._round(n+(a-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#m.commentPopupPositionInLayer}set commentPopupPosition(t){this.#m.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#m.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#m.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#m?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this),this.#$e={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#We.children;if(!this.#He){this.#He=Array.from(e);const t=this.#xi.bind(this),i=this.#Ti.bind(this),n=this._uiManager._signal;for(const e of this.#He){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton"),e.addEventListener("keydown",t,{signal:n}),e.addEventListener("blur",i,{signal:n}),e.addEventListener("focus",this.#Si.bind(this,s),{signal:n}),e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[s])}}const i=this.#He[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#He.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#We.append(this.#We.firstElementChild);else if(s>n)for(let t=0;t<s-n;t++)this.#We.firstElementChild.before(this.#We.lastElementChild);let t=0;for(const i of e){const e=this.#He[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[e])}}this.#Ci(0),this.#ti=!0,this.#We.firstElementChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#xi(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#Ti(t){this.#ti&&t.relatedTarget?.parentNode!==this.#We&&this.#li()}#Si(t){this.#Ye=this.#ti?t:""}#Ci(t){if(this.#He)for(const e of this.#He)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#ti&&this.#gi(this.#Ye,{deltaX:t,deltaY:e,fromKeyboard:!0})}#li(){this.#ti=!1,this.#Ci(-1),this.#mi()}_stopResizingWithKeyboard(){this.#li(),this.div.focus()}select(){this.isSelected&&this._editToolbar?this._editToolbar.show():(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),this._editToolbar?(this._editToolbar?.show(),this.#g?.toggleAltTextBadge(!1)):this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#We?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#g?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(t){"BUTTON"!==t.target.nodeName&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#Qe}set isEditing(t){this.#Qe=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#si||=new Map;const{action:e}=t;let i=this.#si.get(e);return i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#si.delete(e),0===this.#si.size&&(this.#si=null)},AnnotationEditor._telemetryTimeout),void this.#si.set(e,i)}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#Ge=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#Ge=!0}updateFakeAnnotationElement(t){if(this.#Ke||this.deleted)return this.deleted?(this.#Ke.remove(),void(this.#Ke=null)):void((this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Ke.updateEdited({rect:this.getPDFRect(),popup:this.comment}));this.#Ke=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.before(e)}}else e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const SEED=3285377520,MASK_HIGH=4294901760,MASK_LOW=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:SEED,this.h2=t?4294967295&t:SEED}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length),i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);s<=255?e[i++]=s:(e[i++]=s>>>8,e[i++]=255&s)}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice(),i=e.byteLength}const n=i>>2,s=i-4*n,a=new Uint32Array(e.buffer,0,n);let r=0,o=0,l=this.h1,h=this.h2;const d=3432918353,c=461845907,u=11601,p=13715;for(let t=0;t<n;t++)1&t?(r=a[t],r=r*d&MASK_HIGH|r*u&65535,r=r<<15|r>>>17,r=r*c&MASK_HIGH|r*p&65535,l^=r,l=l<<13|l>>>19,l=5*l+3864292196):(o=a[t],o=o*d&MASK_HIGH|o*u&65535,o=o<<15|o>>>17,o=o*c&MASK_HIGH|o*p&65535,h^=o,h=h<<13|h>>>19,h=5*h+3864292196);switch(r=0,s){case 3:r^=e[4*n+2]<<16;case 2:r^=e[4*n+1]<<8;case 1:r^=e[4*n],r=r*d&MASK_HIGH|r*u&65535,r=r<<15|r>>>17,r=r*c&MASK_HIGH|r*p&65535,1&n?l^=r:h^=r}this.h1=l,this.h2=h}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=3981806797*t&MASK_HIGH|36045*t&65535,e=4283543511*e&MASK_HIGH|(2950163797*(e<<16|t>>>16)&MASK_HIGH)>>>16,t^=e>>>1,t=444984403*t&MASK_HIGH|60499*t&65535,e=3301882366*e&MASK_HIGH|(3120437893*(e<<16|t>>>16)&MASK_HIGH)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const SerializableEmpty=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#_i=!1;#Pi=null;#Di=null;#Mi=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const i=this.#Mi.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Mi.get(t)}remove(t){const e=this.#Mi.get(t);if(void 0!==e&&(e instanceof AnnotationEditor&&this.#Di.delete(e.annotationElementId),this.#Mi.delete(t),0===this.#Mi.size&&this.resetModified(),"function"==typeof this.onAnnotationEditor)){for(const t of this.#Mi.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Mi.get(t);let n=!1;if(void 0!==i)for(const[t,s]of Object.entries(e))i[t]!==s&&(n=!0,i[t]=s);else n=!0,this.#Mi.set(t,e);n&&this.#Ii(),e instanceof AnnotationEditor&&((this.#Di||=new Map).set(e.annotationElementId,e),"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type))}has(t){return this.#Mi.has(t)}get size(){return this.#Mi.size}#Ii(){this.#_i||(this.#_i=!0,"function"==typeof this.onSetModified&&this.onSetModified())}resetModified(){this.#_i&&(this.#_i=!1,"function"==typeof this.onResetModified&&this.onResetModified())}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Mi.size)return SerializableEmpty;const t=new Map,e=new MurmurHash3_64,i=[],n=Object.create(null);let s=!1;for(const[i,a]of this.#Mi){const r=a instanceof AnnotationEditor?a.serialize(!1,n):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),r&&(t.set(i,r),e.update(`${i}:${JSON.stringify(r)}`),s||=!!r.bitmap)}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:SerializableEmpty}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#Mi.values()){if(!(s instanceof AnnotationEditor)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const a=s.telemetryFinalData;if(!a)continue;const{type:r}=a;e.has(r)||e.set(r,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const o=t[r]||=new Map;for(const[t,e]of Object.entries(a)){if("type"===t)continue;let i=o.get(t);i||(i=new Map,o.set(t,i));const n=i.get(e)??0;i.set(e,n+1)}}if((n>0||i>0)&&(t||=Object.create(null),t.comments={deleted:n,edited:i}),!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Pi=null}updateEditor(t,e){const i=this.#Di?.get(t);return!!i&&(i.updateFromAnnotationLayer(e),!0)}getEditor(t){return this.#Di?.get(t)||null}get modifiedIds(){if(this.#Pi)return this.#Pi;const t=[];if(this.#Di)for(const e of this.#Di.values())e.serialize()&&t.push(e.annotationElementId);return this.#Pi={ids:new Set(t),hash:t.join(",")}}[Symbol.iterator](){return this.#Mi.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#ki;constructor(t){super();const{map:e,hash:i,transfer:n}=t.serializable,s=structuredClone(e,n?{transfer:n}:null);this.#ki={map:s,hash:i,transfer:n}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ki}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#Fi=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#Fi.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#Fi.has(t.loadedName)){if(assert(!e,"loadSystemFont shouldn\'t be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,a=new FontFace(e,n,s);this.addNativeFontFace(a);try{await a.load(),this.#Fi.add(e),i?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo)return void await this.loadSystemFont(t);if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){throw warn(`Failed to load font \'${e.family}\': \'${i}\'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",isNodeJS||util_FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function(){for(assert(!i.done,"completeRequest() cannot be called twice."),i.done=!0;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};return e.push(i),i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function i(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function n(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let s,a;const r=this._document.createElement("canvas");r.width=1,r.height=1;const o=r.getContext("2d");let l=0;const h=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=n(d,976,h.length,h);const c=1482184792;let u=i(d,16);for(s=0,a=h.length-3;s<a;s+=4)u=u-c+i(h,s)|0;s<h.length&&(u=u-c+i(h+"XXX",s)|0),d=n(d,16,4,string32(u));const p=`@font-face {font-family:"${h}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(p);const g=this._document.createElement("div");g.style.visibility="hidden",g.style.width=g.style.height="10px",g.style.position="absolute",g.style.top=g.style.left="0px";for(const e of[t.loadedName,h]){const t=this._document.createElement("span");t.textContent="Hi",t.style.fontFamily=e,g.append(t)}this._document.body.append(g),function t(e,i){if(++l>30)return warn("Load test font never loaded."),void i();o.font="30px "+e,o.fillText(".",0,20),o.getImageData(0,0,1,1).data[3]>0?i():setTimeout(t.bind(null,e,i))}(h,()=>{g.remove(),e.complete()})}}class FontFaceObject{#Ri;constructor(t,e=null,i,n){this.compiledGlyphs=Object.create(null),this.#Ri=t,this._inspectFont=e,i&&Object.assign(this,i),n&&(this.charProcOperatorList=n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const s=makePathFromDrawOPS(n?.path);return this.fontExtraProperties||t.delete(i),this.compiledGlyphs[e]=s}get black(){return this.#Ri.black}get bold(){return this.#Ri.bold}get disableFontFace(){return this.#Ri.disableFontFace??!1}set disableFontFace(t){shadow(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#Ri.fontExtraProperties??!1}get isInvalidPDFjsFont(){return this.#Ri.isInvalidPDFjsFont}get isType3Font(){return this.#Ri.isType3Font}get italic(){return this.#Ri.italic}get missingFile(){return this.#Ri.missingFile}get remeasure(){return this.#Ri.remeasure}get vertical(){return this.#Ri.vertical}get ascent(){return this.#Ri.ascent}get defaultWidth(){return this.#Ri.defaultWidth}get descent(){return this.#Ri.descent}get bbox(){return this.#Ri.bbox}set bbox(t){shadow(this,"bbox",t)}get fontMatrix(){return this.#Ri.fontMatrix}get fallbackName(){return this.#Ri.fallbackName}get loadedName(){return this.#Ri.loadedName}get mimetype(){return this.#Ri.mimetype}get name(){return this.#Ri.name}get data(){return this.#Ri.data}clearData(){this.#Ri.clearData()}get cssFontInfo(){return this.#Ri.cssFontInfo}get systemFontInfo(){return this.#Ri.systemFontInfo}get defaultVMetrics(){return this.#Ri.defaultVMetrics}}class CssFontInfo{#Li;#Bi;#Oi;static strings=["fontFamily","fontWeight","italicAngle"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of CssFontInfo.strings){const a=e.encode(t[s]);i[s]=a,n+=4+a.length}const s=new ArrayBuffer(n),a=new Uint8Array(s),r=new DataView(s);let o=0;for(const t of CssFontInfo.strings){const e=i[t],n=e.length;r.setUint32(o,n),a.set(e,o+4),o+=4+n}return assert(o===s.byteLength,"CssFontInfo.write: Buffer overflow"),s}constructor(t){this.#Li=t,this.#Bi=new DataView(this.#Li),this.#Oi=new TextDecoder}#Ni(t){assert(t<CssFontInfo.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#Bi.getUint32(e)+4;const i=this.#Bi.getUint32(e);return this.#Oi.decode(new Uint8Array(this.#Li,e+4,i))}get fontFamily(){return this.#Ni(0)}get fontWeight(){return this.#Ni(1)}get italicAngle(){return this.#Ni(2)}}class SystemFontInfo{#Li;#Bi;#Oi;static strings=["css","loadedName","baseFontName","src"];static write(t){const e=new TextEncoder,i={};let n=0;for(const s of SystemFontInfo.strings){const a=e.encode(t[s]);i[s]=a,n+=4+a.length}n+=4;let s,a,r=1+n;t.style&&(s=e.encode(t.style.style),a=e.encode(t.style.weight),r+=4+s.length+4+a.length);const o=new ArrayBuffer(r),l=new Uint8Array(o),h=new DataView(o);let d=0;h.setUint8(d++,t.guessFallback?1:0),h.setUint32(d,0),d+=4,n=0;for(const t of SystemFontInfo.strings){const e=i[t],s=e.length;n+=4+s,h.setUint32(d,s),l.set(e,d+4),d+=4+s}return h.setUint32(d-n-4,n),t.style&&(h.setUint32(d,s.length),l.set(s,d+4),d+=4+s.length,h.setUint32(d,a.length),l.set(a,d+4),d+=4+a.length),assert(d<=o.byteLength,"SubstitionInfo.write: Buffer overflow"),o.transferToFixedLength(d)}constructor(t){this.#Li=t,this.#Bi=new DataView(this.#Li),this.#Oi=new TextDecoder}get guessFallback(){return 0!==this.#Bi.getUint8(0)}#Ni(t){assert(t<SystemFontInfo.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#Bi.getUint32(e)+4;const i=this.#Bi.getUint32(e);return this.#Oi.decode(new Uint8Array(this.#Li,e+4,i))}get css(){return this.#Ni(0)}get loadedName(){return this.#Ni(1)}get baseFontName(){return this.#Ni(2)}get src(){return this.#Ni(3)}get style(){let t=1;t+=4+this.#Bi.getUint32(t);const e=this.#Bi.getUint32(t),i=this.#Oi.decode(new Uint8Array(this.#Li,t+4,e));t+=4+e;const n=this.#Bi.getUint32(t);return{style:i,weight:this.#Oi.decode(new Uint8Array(this.#Li,t+4,n))}}}class FontInfo{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static#Ui=Math.ceil(2*this.bools.length/8);static#Hi=this.#Ui+8*this.numbers.length;static#Gi=this.#Hi+1+8;static#zi=this.#Gi+1+48;static#Vi=this.#zi+1+6;#Li;#Oi;#Bi;constructor({data:t,extra:e}){this.#Li=t,this.#Oi=new TextDecoder,this.#Bi=new DataView(this.#Li),e&&Object.assign(this,e)}#Wi(t){assert(t<FontInfo.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,n=this.#Bi.getUint8(e)>>i&3;return 0===n?void 0:2===n}get black(){return this.#Wi(0)}get bold(){return this.#Wi(1)}get disableFontFace(){return this.#Wi(2)}get fontExtraProperties(){return this.#Wi(3)}get isInvalidPDFjsFont(){return this.#Wi(4)}get isType3Font(){return this.#Wi(5)}get italic(){return this.#Wi(6)}get missingFile(){return this.#Wi(7)}get remeasure(){return this.#Wi(8)}get vertical(){return this.#Wi(9)}#ji(t){return assert(t<FontInfo.numbers.length,"Invalid number index"),this.#Bi.getFloat64(FontInfo.#Ui+8*t)}get ascent(){return this.#ji(0)}get defaultWidth(){return this.#ji(1)}get descent(){return this.#ji(2)}get bbox(){let t=FontInfo.#Hi;if(0===this.#Bi.getUint8(t))return;t+=1;const e=[];for(let i=0;i<4;i++)e.push(this.#Bi.getInt16(t,!0)),t+=2;return e}get fontMatrix(){let t=FontInfo.#Gi;if(0===this.#Bi.getUint8(t))return;t+=1;const e=[];for(let i=0;i<6;i++)e.push(this.#Bi.getFloat64(t,!0)),t+=8;return e}get defaultVMetrics(){let t=FontInfo.#zi;if(0===this.#Bi.getUint8(t))return;t+=1;const e=[];for(let i=0;i<3;i++)e.push(this.#Bi.getInt16(t,!0)),t+=2;return e}#Ni(t){assert(t<FontInfo.strings.length,"Invalid string index");let e=FontInfo.#Vi+4;for(let i=0;i<t;i++)e+=this.#Bi.getUint32(e)+4;const i=this.#Bi.getUint32(e),n=new Uint8Array(i);return n.set(new Uint8Array(this.#Li,e+4,i)),this.#Oi.decode(n)}get fallbackName(){return this.#Ni(0)}get loadedName(){return this.#Ni(1)}get mimetype(){return this.#Ni(2)}get name(){return this.#Ni(3)}get data(){let t=FontInfo.#Vi;t+=4+this.#Bi.getUint32(t);t+=4+this.#Bi.getUint32(t);t+=4+this.#Bi.getUint32(t);const e=this.#Bi.getUint32(t);if(0!==e)return new Uint8Array(this.#Li,t+4,e)}clearData(){let t=FontInfo.#Vi;t+=4+this.#Bi.getUint32(t);t+=4+this.#Bi.getUint32(t);t+=4+this.#Bi.getUint32(t);const e=this.#Bi.getUint32(t);new Uint8Array(this.#Li,t+4,e).fill(0),this.#Bi.setUint32(t,0)}get cssFontInfo(){let t=FontInfo.#Vi;t+=4+this.#Bi.getUint32(t);t+=4+this.#Bi.getUint32(t);const e=this.#Bi.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#Li,t+4,e)),new CssFontInfo(i.buffer)}get systemFontInfo(){let t=FontInfo.#Vi;t+=4+this.#Bi.getUint32(t);const e=this.#Bi.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);return i.set(new Uint8Array(this.#Li,t+4,e)),new SystemFontInfo(i.buffer)}static write(t){const e=t.systemFontInfo?SystemFontInfo.write(t.systemFontInfo):null,i=t.cssFontInfo?CssFontInfo.write(t.cssFontInfo):null,n=new TextEncoder,s={};let a=0;for(const e of FontInfo.strings)s[e]=n.encode(t[e]),a+=4+s[e].length;const r=FontInfo.#Vi+4+a+4+(e?e.byteLength:0)+4+(i?i.byteLength:0)+4+(t.data?t.data.length:0),o=new ArrayBuffer(r),l=new Uint8Array(o),h=new DataView(o);let d=0;const c=FontInfo.bools.length;let u=0,p=0;for(let e=0;e<c;e++){const i=t[FontInfo.bools[e]];u|=(void 0===i?0:i?2:1)<<p,p+=2,8!==p&&e!==c-1||(h.setUint8(d++,u),u=0,p=0)}assert(d===FontInfo.#Ui,"FontInfo.write: Boolean properties offset mismatch");for(const e of FontInfo.numbers)h.setFloat64(d,t[e]),d+=8;if(assert(d===FontInfo.#Hi,"FontInfo.write: Number properties offset mismatch"),t.bbox){h.setUint8(d++,4);for(const e of t.bbox)h.setInt16(d,e,!0),d+=2}else h.setUint8(d++,0),d+=8;if(assert(d===FontInfo.#Gi,"FontInfo.write: BBox properties offset mismatch"),t.fontMatrix){h.setUint8(d++,6);for(const e of t.fontMatrix)h.setFloat64(d,e,!0),d+=8}else h.setUint8(d++,0),d+=48;if(assert(d===FontInfo.#zi,"FontInfo.write: FontMatrix properties offset mismatch"),t.defaultVMetrics){h.setUint8(d++,1);for(const e of t.defaultVMetrics)h.setInt16(d,e,!0),d+=2}else h.setUint8(d++,0),d+=6;assert(d===FontInfo.#Vi,"FontInfo.write: DefaultVMetrics properties offset mismatch"),h.setUint32(FontInfo.#Vi,0),d+=4;for(const t of FontInfo.strings){const e=s[t],i=e.length;h.setUint32(d,i),l.set(e,d+4),d+=4+i}if(h.setUint32(FontInfo.#Vi,d-FontInfo.#Vi-4),e){const t=e.byteLength;h.setUint32(d,t),assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at systemFontInfo"),l.set(new Uint8Array(e),d+4),d+=4+t}else h.setUint32(d,0),d+=4;if(i){const t=i.byteLength;h.setUint32(d,t),assert(d+4+t<=o.byteLength,"FontInfo.write: Buffer overflow at cssFontInfo"),l.set(new Uint8Array(i),d+4),d+=4+t}else h.setUint32(d,0),d+=4;return void 0===t.data?(h.setUint32(d,0),d+=4):(h.setUint32(d,t.data.length),l.set(t.data,d+4),d+=4+t.data.length),assert(d<=o.byteLength,"FontInfo.write: Buffer overflow"),o.transferToFixedLength(d)}}class PatternInfo{static#$i=0;static#Ki=1;static#Xi=2;static#Yi=3;static#qi=4;static#Ji=8;static#Qi=12;static#Zi=16;constructor(t){this.buffer=t,this.view=new DataView(t),this.data=new Uint8Array(t)}static write(t){let e,i=null,n=[],s=[],a=[],r=[],o=null,l=null;switch(t[0]){case"RadialAxial":e="axial"===t[1]?1:2,i=t[2],a=t[3],1===e?n.push(...t[4],...t[5]):n.push(t[4][0],t[4][1],t[6],t[5][0],t[5][1],t[7]);break;case"Mesh":e=3,o=t[1],n=t[2],s=t[3],r=t[4]||[],i=t[6],l=t[7];break;default:throw new Error(`Unsupported pattern type: ${t[0]}`)}const h=Math.floor(n.length/2),d=Math.floor(s.length/3),c=a.length,u=r.length;let p=0;for(const t of r)p+=1,p=4*Math.ceil(p/4),p+=4+4*t.coords.length,p+=4+4*t.colors.length,void 0!==t.verticesPerRow&&(p+=4);const g=new ArrayBuffer(20+8*h+3*d+8*c+(i?16:0)+(l?3:0)+p),m=new DataView(g),f=new Uint8Array(g);m.setUint8(PatternInfo.#$i,e),m.setUint8(PatternInfo.#Ki,i?1:0),m.setUint8(PatternInfo.#Xi,l?1:0),m.setUint8(PatternInfo.#Yi,o),m.setUint32(PatternInfo.#qi,h,!0),m.setUint32(PatternInfo.#Ji,d,!0),m.setUint32(PatternInfo.#Qi,c,!0),m.setUint32(PatternInfo.#Zi,u,!0);let b=20;new Float32Array(g,b,2*h).set(n),b+=8*h,f.set(s,b),b+=3*d;for(const[t,e]of a)m.setFloat32(b,t,!0),b+=4,m.setUint32(b,parseInt(e.slice(1),16),!0),b+=4;if(i)for(const t of i)m.setFloat32(b,t,!0),b+=4;l&&(f.set(l,b),b+=3);for(let t=0;t<r.length;t++){const e=r[t];m.setUint8(b,e.type),b+=1,b=4*Math.ceil(b/4),m.setUint32(b,e.coords.length,!0),b+=4;new Int32Array(g,b,e.coords.length).set(e.coords),b+=4*e.coords.length,m.setUint32(b,e.colors.length,!0),b+=4;new Int32Array(g,b,e.colors.length).set(e.colors),b+=4*e.colors.length,void 0!==e.verticesPerRow&&(m.setUint32(b,e.verticesPerRow,!0),b+=4)}return g}getIR(){const t=this.view,e=this.data[PatternInfo.#$i],i=!!this.data[PatternInfo.#Ki],n=!!this.data[PatternInfo.#Xi],s=t.getUint32(PatternInfo.#qi,!0),a=t.getUint32(PatternInfo.#Ji,!0),r=t.getUint32(PatternInfo.#Qi,!0),o=t.getUint32(PatternInfo.#Zi,!0);let l=20;const h=new Float32Array(this.buffer,l,2*s);l+=8*s;const d=new Uint8Array(this.buffer,l,3*a);l+=3*a;const c=[];for(let e=0;e<r;++e){const e=t.getFloat32(l,!0);l+=4;const i=t.getUint32(l,!0);l+=4,c.push([e,`#${i.toString(16).padStart(6,"0")}`])}let u=null;if(i){u=[];for(let e=0;e<4;++e)u.push(t.getFloat32(l,!0)),l+=4}let p=null;n&&(p=new Uint8Array(this.buffer,l,3),l+=3);const g=[];for(let e=0;e<o;++e){const e=t.getUint8(l);l+=1,l=4*Math.ceil(l/4);const i=t.getUint32(l,!0);l+=4;const n=new Int32Array(this.buffer,l,i);l+=4*i;const s=t.getUint32(l,!0);l+=4;const a=new Int32Array(this.buffer,l,s);l+=4*s;const r={type:e,coords:n,colors:a};e===MeshFigureType.LATTICE&&(r.verticesPerRow=t.getUint32(l,!0),l+=4),g.push(r)}if(1===e)return["RadialAxial","axial",u,c,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===e)return["RadialAxial","radial",u,c,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===e){const t=this.data[PatternInfo.#Yi];let e=null;if(h.length>0){let t=h[0],i=h[0],n=h[1],s=h[1];for(let e=0;e<h.length;e+=2){const a=h[e],r=h[e+1];t=t>a?a:t,n=n>r?r:n,i=i<a?a:i,s=s<r?r:s}e=[t,n,i,s]}return["Mesh",t,h,d,g,e,u,p]}throw new Error(`Unsupported pattern kind: ${e}`)}}class FontPathInfo{static write(t){let e,i;return util_FeatureTest.isFloat16ArraySupported?(i=new ArrayBuffer(2*t.length),e=new Float16Array(i)):(i=new ArrayBuffer(4*t.length),e=new Float32Array(i)),e.set(t),i}#Li;constructor(t){this.#Li=t}get path(){return util_FeatureTest.isFloat16ArraySupported?new Float16Array(this.#Li):new Float32Array(this.#Li)}}function getUrlProp(t){if(t instanceof URL)return t.href;if("string"==typeof t){if(isNodeJS)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(isNodeJS&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function getFactoryUrlProp(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const isRefProxy=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,isNameProxy=t=>"object"==typeof t&&"string"==typeof t?.name,isValidExplicitDest=_isValidExplicitDest.bind(null,isRefProxy,isNameProxy);class LoopbackPort{#o=new Map;#tn=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#tn.then(()=>{for(const[t]of this.#o)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted)return void warn("LoopbackPort - cannot use an `aborted` signal.");const a=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",a),s.addEventListener("abort",a)}this.#o.set(e,n)}removeEventListener(t,e){const i=this.#o.get(e);i?.(),this.#o.delete(e)}terminate(){for(const[,t]of this.#o)t?.();this.#o.clear()}}const CallbackKind={DATA:1,ERROR:2},StreamKind={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;switch(t instanceof Error||"object"==typeof t&&null!==t||unreachable(\'wrapReason: Expected "reason" to be a (possibly cloned) Error.\'),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{#en=new AbortController;constructor(t,e,i){this.sourceName=t,this.targetName=e,this.comObj=i,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),i.addEventListener("message",this.#in.bind(this),{signal:this.#en.signal})}#in({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream)return void this.#nn(t);if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);if(delete this.callbackCapabilities[e],t.callback===CallbackKind.DATA)i.resolve(t.data);else{if(t.callback!==CallbackKind.ERROR)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;return void Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:CallbackKind.DATA,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:CallbackKind.ERROR,callbackId:t.callbackId,reason:wrapReason(e)})})}t.streamId?this.#sn(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();return this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1},o.postMessage({sourceName:a,targetName:r,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n),l.promise},pull:t=>{const e=Promise.withResolvers();return this.streamControllers[s].pullCall=e,o.postMessage({sourceName:a,targetName:r,stream:StreamKind.PULL,streamId:s,desiredSize:t.desiredSize}),e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();return this.streamControllers[s].cancelCall=e,this.streamControllers[s].isClosed=!0,o.postMessage({sourceName:a,targetName:r,stream:StreamKind.CANCEL,streamId:s,reason:wrapReason(t)}),e.promise}},i)}#sn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a,o>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),s.postMessage({sourceName:i,targetName:n,stream:StreamKind.ENQUEUE,streamId:e,chunk:t},r)},close(){this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:StreamKind.CLOSE,streamId:e}),delete a.streamSinks[e])},error(t){assert(t instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,s.postMessage({sourceName:i,targetName:n,stream:StreamKind.ERROR,streamId:e,reason:wrapReason(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve(),o.ready=o.sinkCapability.promise,this.streamSinks[e]=o,Promise.try(r,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.START_COMPLETE,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.START_COMPLETE,streamId:e,reason:wrapReason(t)})})}#nn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case StreamKind.START_COMPLETE:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case StreamKind.PULL_COMPLETE:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case StreamKind.PULL:if(!r){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.PULL_COMPLETE,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve(),r.desiredSize=t.desiredSize,Promise.try(r.onPull||onFn).then(function(){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.PULL_COMPLETE,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.PULL_COMPLETE,streamId:e,reason:wrapReason(t)})});break;case StreamKind.ENQUEUE:if(assert(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(t.chunk);break;case StreamKind.CLOSE:if(assert(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#an(a,e);break;case StreamKind.ERROR:assert(a,"error should have stream controller"),a.controller.error(wrapReason(t.reason)),this.#an(a,e);break;case StreamKind.CANCEL_COMPLETE:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason)),this.#an(a,e);break;case StreamKind.CANCEL:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.CANCEL_COMPLETE,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:StreamKind.CANCEL_COMPLETE,streamId:e,reason:wrapReason(t)})}),r.sinkCapability.reject(o),r.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#an(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#en?.abort(),this.#en=null}}class BaseCanvasFactory{#rn=!1;constructor({enableHWA:t=!1}){this.#rn=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#rn})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");return i.width=t,i.height=e,i}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(t=>({cMapData:t,isCompressed:this.isCompressed})).catch(t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#on;#ln;#hn;#dn;#cn;#un;#k=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#dn=t,this.#cn=e}get#R(){return this.#ln||=new Map}get#pn(){return this.#un||=new Map}get#gn(){if(!this.#hn){const t=this.#cn.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const i=this.#cn.createElementNS(SVG_NS,"svg");i.setAttribute("width",0),i.setAttribute("height",0),this.#hn=this.#cn.createElementNS(SVG_NS,"defs"),t.append(i),i.append(this.#hn),this.#cn.body.append(t)}return this.#hn}#mn(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++)s[t]=e[t]/255,a[t]=i[t]/255,r[t]=n[t]/255;return[s.join(","),a.join(","),r.join(",")]}#fn(t){if(void 0===this.#on){this.#on="";const t=this.#cn.URL;t!==this.#cn.baseURI&&(isDataScheme(t)?warn(\'#createUrl: ignore "data:"-URL for performance reasons.\'):this.#on=updateUrlHash(t,""))}return`url(${this.#on}#${t})`}addFilter(t){if(!t)return"none";let e=this.#R.get(t);if(e)return e;const[i,n,s]=this.#mn(t),a=1===t.length?i:`${i}${n}${s}`;if(e=this.#R.get(a),e)return this.#R.set(t,e),e;const r=`g_${this.#dn}_transfer_map_${this.#k++}`,o=this.#fn(r);this.#R.set(t,o),this.#R.set(a,o);const l=this.#bn(r);return this.#An(i,n,s,l),o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#pn.get(n);if(s?.key===i)return s.url;if(s?(s.filter?.remove(),s.key=i,s.url="none",s.filter=null):(s={key:i,url:"none",filter:null},this.#pn.set(n,s)),!t||!e)return s.url;const a=this.#yn(t);t=Util.makeHexColor(...a);const r=this.#yn(e);if(e=Util.makeHexColor(...r),this.#gn.style.color="","#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#dn}_hcm_filter`,d=s.filter=this.#bn(h);this.#An(l,l,l,d),this.#wn(d);const c=(t,e)=>{const i=a[t]/255,n=r[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};return this.#An(c(0,5),c(1,5),c(2,5),d),s.url=this.#fn(h),s.url}addAlphaFilter(t){let e=this.#R.get(t);if(e)return e;const[i]=this.#mn([t]),n=`alpha_${i}`;if(e=this.#R.get(n),e)return this.#R.set(t,e),e;const s=`g_${this.#dn}_alpha_map_${this.#k++}`,a=this.#fn(s);this.#R.set(t,a),this.#R.set(n,a);const r=this.#bn(s);return this.#vn(i,r),a}addLuminosityFilter(t){let e,i,n=this.#R.get(t||"luminosity");if(n)return n;if(t?([e]=this.#mn([t]),i=`luminosity_${e}`):i="luminosity",n=this.#R.get(i),n)return this.#R.set(t,n),n;const s=`g_${this.#dn}_luminosity_map_${this.#k++}`,a=this.#fn(s);this.#R.set(t,a),this.#R.set(i,a);const r=this.#bn(s);return this.#En(r),t&&this.#vn(e,r),a}addHighlightHCMFilter(t,e,i,n,s){const a=`${e}-${i}-${n}-${s}`;let r=this.#pn.get(t);if(r?.key===a)return r.url;if(r?(r.filter?.remove(),r.key=a,r.url="none",r.filter=null):(r={key:a,url:"none",filter:null},this.#pn.set(t,r)),!e||!i)return r.url;const[o,l]=[e,i].map(this.#yn.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[c,u]=[n,s].map(this.#yn.bind(this));d<h&&([h,d,c,u]=[d,h,u,c]),this.#gn.style.color="";const p=(t,e,i)=>{const n=new Array(256),s=(d-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=a+t*r;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},g=`g_${this.#dn}_hcm_${t}_filter`,m=r.filter=this.#bn(g);return this.#wn(m),this.#An(p(c[0],u[0],5),p(c[1],u[1],5),p(c[2],u[2],5),m),r.url=this.#fn(g),r.url}destroy(t=!1){t&&this.#un?.size||(this.#hn?.parentNode.parentNode.remove(),this.#hn=null,this.#ln?.clear(),this.#ln=null,this.#un?.clear(),this.#un=null,this.#k=0)}#En(t){const e=this.#cn.createElementNS(SVG_NS,"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)}#wn(t){const e=this.#cn.createElementNS(SVG_NS,"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)}#bn(t){const e=this.#cn.createElementNS(SVG_NS,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#gn.append(e),e}#xn(t,e,i){const n=this.#cn.createElementNS(SVG_NS,e);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),t.append(n)}#An(t,e,i,n){const s=this.#cn.createElementNS(SVG_NS,"feComponentTransfer");n.append(s),this.#xn(s,"feFuncR",t),this.#xn(s,"feFuncG",e),this.#xn(s,"feFuncB",i)}#vn(t,e){const i=this.#cn.createElementNS(SVG_NS,"feComponentTransfer");e.append(i),this.#xn(i,"feFuncA",t)}#yn(t){return this.#gn.style.color=t,getRGB(getComputedStyle(this.#gn).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)}}async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}isNodeJS&&warn("Please use the `legacy` build in Node.js environments.");class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}class NodeWasmFactory extends BaseWasmFactory{async _fetch(t){return node_utils_fetchData(t)}}const FORCED_DEPENDENCY_LABEL="__forcedDependency",{floor:floor,ceil:ceil}=Math;function expandBBox(t,e,i,n,s,a){t[4*e+0]=Math.min(t[4*e+0],i),t[4*e+1]=Math.min(t[4*e+1],n),t[4*e+2]=Math.max(t[4*e+2],s),t[4*e+3]=Math.max(t[4*e+3],a)}const EMPTY_BBOX=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Tn;#Sn;constructor(t,e){this.#Tn=t,this.#Sn=e}get length(){return this.#Tn.length}isEmpty(t){return this.#Tn[t]===EMPTY_BBOX}minX(t){return this.#Sn[4*t+0]/256}minY(t){return this.#Sn[4*t+1]/256}maxX(t){return(this.#Sn[4*t+2]+1)/256}maxY(t){return(this.#Sn[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>{if(!t)return;let i=t.get(e);return i||(i={dependencies:new Set,isRenderingOperation:!1},t.set(e,i)),i};class CanvasDependencyTracker{#Cn={__proto__:null};#_n={__proto__:null,transform:[],moveText:[],sameLineText:[],[FORCED_DEPENDENCY_LABEL]:[]};#Pn=new Map;#Dn=[];#Mn=[];#In=[[1,0,0,1,0,0]];#kn=[-1/0,-1/0,1/0,1/0];#Fn=new Float64Array([1/0,1/0,-1/0,-1/0]);#Rn=-1;#Ln=new Set;#Bn=new Map;#On=new Map;#Nn;#Un;#Hn;#Tn;#Gn;constructor(t,e,i=!1){this.#Nn=t.width,this.#Un=t.height,this.#zn(e),i&&(this.#Gn=new Map)}growOperationsCount(t){t>=this.#Tn.length&&this.#zn(t,this.#Tn)}#zn(t,e){const i=new ArrayBuffer(4*t);this.#Hn=new Uint8ClampedArray(i),this.#Tn=new Uint32Array(i),e&&e.length>0?(this.#Tn.set(e),this.#Tn.fill(EMPTY_BBOX,e.length)):this.#Tn.fill(EMPTY_BBOX)}save(t){return this.#Cn={__proto__:this.#Cn},this.#_n={__proto__:this.#_n,transform:{__proto__:this.#_n.transform},moveText:{__proto__:this.#_n.moveText},sameLineText:{__proto__:this.#_n.sameLineText},[FORCED_DEPENDENCY_LABEL]:{__proto__:this.#_n.__forcedDependency}},this.#kn={__proto__:this.#kn},this.#Dn.push(t),this}restore(t){const e=Object.getPrototypeOf(this.#Cn);if(null===e)return this;this.#Cn=e,this.#_n=Object.getPrototypeOf(this.#_n),this.#kn=Object.getPrototypeOf(this.#kn);const i=this.#Dn.pop();return void 0!==i&&(ensureDebugMetadata(this.#Gn,t)?.dependencies.add(i),this.#Tn[t]=this.#Tn[i]),this}recordOpenMarker(t){return this.#Dn.push(t),this}getOpenMarker(){return 0===this.#Dn.length?null:this.#Dn.at(-1)}recordCloseMarker(t){const e=this.#Dn.pop();return void 0!==e&&(ensureDebugMetadata(this.#Gn,t)?.dependencies.add(e),this.#Tn[t]=this.#Tn[e]),this}beginMarkedContent(t){return this.#Mn.push(t),this}endMarkedContent(t){const e=this.#Mn.pop();return void 0!==e&&(ensureDebugMetadata(this.#Gn,t)?.dependencies.add(e),this.#Tn[t]=this.#Tn[e]),this}pushBaseTransform(t){return this.#In.push(Util.multiplyByDOMMatrix(this.#In.at(-1),t.getTransform())),this}popBaseTransform(){return this.#In.length>1&&this.#In.pop(),this}recordSimpleData(t,e){return this.#Cn[t]=e,this}recordIncrementalData(t,e){return this.#_n[t].push(e),this}resetIncrementalData(t,e){return this.#_n[t].length=0,this}recordNamedData(t,e){return this.#Pn.set(t,e),this}recordSimpleDataFromNamed(t,e,i){this.#Cn[t]=this.#Pn.get(e)??i}recordFutureForcedDependency(t,e){return this.recordIncrementalData("__forcedDependency",e),this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Cn&&this.recordFutureForcedDependency(e,this.#Cn[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Ln)this.recordFutureForcedDependency("__forcedDependency",t);return this}resetBBox(t){return this.#Rn!==t&&(this.#Rn=t,this.#Fn[0]=1/0,this.#Fn[1]=1/0,this.#Fn[2]=-1/0,this.#Fn[3]=-1/0),this}recordClipBox(t,e,i,n,s,a){const r=Util.multiplyByDOMMatrix(this.#In.at(-1),e.getTransform()),o=[1/0,1/0,-1/0,-1/0];Util.axialAlignedBoundingBox([i,s,n,a],r,o);const l=Util.intersect(this.#kn,o);return l?(this.#kn[0]=l[0],this.#kn[1]=l[1],this.#kn[2]=l[2],this.#kn[3]=l[3]):(this.#kn[0]=this.#kn[1]=1/0,this.#kn[2]=this.#kn[3]=-1/0),this}recordBBox(t,e,i,n,s,a){const r=this.#kn;if(r[0]===1/0)return this;const o=Util.multiplyByDOMMatrix(this.#In.at(-1),e.getTransform());if(r[0]===-1/0)return Util.axialAlignedBoundingBox([i,s,n,a],o,this.#Fn),this;const l=[1/0,1/0,-1/0,-1/0];return Util.axialAlignedBoundingBox([i,s,n,a],o,l),this.#Fn[0]=Math.min(this.#Fn[0],Math.max(l[0],r[0])),this.#Fn[1]=Math.min(this.#Fn[1],Math.max(l[1],r[1])),this.#Fn[2]=Math.max(this.#Fn[2],Math.min(l[2],r[2])),this.#Fn[3]=Math.max(this.#Fn[3],Math.min(l[3],r[3])),this}recordCharacterBBox(t,e,i,n=1,s=0,a=0,r){const o=i.bbox;let l,h;if(o&&(l=o[2]!==o[0]&&o[3]!==o[1]&&this.#On.get(i),!1!==l&&(h=[0,0,0,0],Util.axialAlignedBoundingBox(o,i.fontMatrix,h),1===n&&0===s&&0===a||Util.scaleMinMax([n,0,0,-n,s,a],h),l)))return this.recordBBox(t,e,h[0],h[2],h[1],h[3]);if(!r)return this.recordFullPageBBox(t);const d=r();return o&&h&&void 0===l&&(l=h[0]<=s-d.actualBoundingBoxLeft&&h[2]>=s+d.actualBoundingBoxRight&&h[1]<=a-d.actualBoundingBoxAscent&&h[3]>=a+d.actualBoundingBoxDescent,this.#On.set(i,l),l)?this.recordBBox(t,e,h[0],h[2],h[1],h[3]):this.recordBBox(t,e,s-d.actualBoundingBoxLeft,s+d.actualBoundingBoxRight,a-d.actualBoundingBoxAscent,a+d.actualBoundingBoxDescent)}recordFullPageBBox(t){return this.#Fn[0]=Math.max(0,this.#kn[0]),this.#Fn[1]=Math.max(0,this.#kn[1]),this.#Fn[2]=Math.min(this.#Nn,this.#kn[2]),this.#Fn[3]=Math.min(this.#Un,this.#kn[3]),this}getSimpleIndex(t){return this.#Cn[t]}recordDependencies(t,e){const i=this.#Ln,n=this.#Cn,s=this.#_n;for(const t of e)t in this.#Cn?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){return this.#Pn.has(e)&&this.#Ln.add(this.#Pn.get(e)),this}recordOperation(t,e=!1){if(this.recordDependencies(t,["__forcedDependency"]),this.#Gn){const e=ensureDebugMetadata(this.#Gn,t),{dependencies:i}=e;this.#Ln.forEach(i.add,i),this.#Dn.forEach(i.add,i),this.#Mn.forEach(i.add,i),i.delete(t),e.isRenderingOperation=!0}if(this.#Rn===t){const i=floor(256*this.#Fn[0]/this.#Nn),n=floor(256*this.#Fn[1]/this.#Un),s=ceil(256*this.#Fn[2]/this.#Nn),a=ceil(256*this.#Fn[3]/this.#Un);expandBBox(this.#Hn,t,i,n,s,a);for(const e of this.#Ln)e!==t&&expandBBox(this.#Hn,e,i,n,s,a);for(const e of this.#Dn)e!==t&&expandBBox(this.#Hn,e,i,n,s,a);for(const e of this.#Mn)e!==t&&expandBBox(this.#Hn,e,i,n,s,a);e||(this.#Ln.clear(),this.#Rn=-1)}return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#Ln);this.recordOperation(t,e),this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){return this.#Rn===t&&(this.#Rn=-1,this.#kn[0]=Math.max(this.#kn[0],this.#Fn[0]),this.#kn[1]=Math.max(this.#kn[1],this.#Fn[1]),this.#kn[2]=Math.min(this.#kn[2],this.#Fn[2]),this.#kn[3]=Math.min(this.#kn[3],this.#Fn[3]),e||this.#Ln.clear()),this}_takePendingDependencies(){const t=this.#Ln;return this.#Ln=new Set,t}_extractOperation(t){const e=this.#Bn.get(t);return this.#Bn.delete(t),e}_pushPendingDependencies(t){for(const e of t)this.#Ln.add(e)}take(){return this.#On.clear(),new BBoxReader(this.#Tn,this.#Hn)}takeDebugMetadata(){return this.#Gn}}class CanvasNestedDependencyTracker{#Vn;#Wn;#jn;#$n=0;#Kn=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#jn===!!i)return t;this.#Vn=t,this.#Wn=e,this.#jn=!!i}growOperationsCount(){throw new Error("Unreachable")}save(t){return this.#Kn++,this.#Vn.save(this.#Wn),this}restore(t){return this.#Kn>0&&(this.#Vn.restore(this.#Wn),this.#Kn--),this}recordOpenMarker(t){return this.#$n++,this}getOpenMarker(){return this.#$n>0?this.#Wn:this.#Vn.getOpenMarker()}recordCloseMarker(t){return this.#$n--,this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){return this.#Vn.pushBaseTransform(t),this}popBaseTransform(){return this.#Vn.popBaseTransform(),this}recordSimpleData(t,e){return this.#Vn.recordSimpleData(t,this.#Wn),this}recordIncrementalData(t,e){return this.#Vn.recordIncrementalData(t,this.#Wn),this}resetIncrementalData(t,e){return this.#Vn.resetIncrementalData(t,this.#Wn),this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this.#Vn.recordSimpleDataFromNamed(t,e,this.#Wn),this}recordFutureForcedDependency(t,e){return this.#Vn.recordFutureForcedDependency(t,this.#Wn),this}inheritSimpleDataAsFutureForcedDependencies(t){return this.#Vn.inheritSimpleDataAsFutureForcedDependencies(t),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#Vn.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(t){return this.#jn||this.#Vn.resetBBox(this.#Wn),this}recordClipBox(t,e,i,n,s,a){return this.#jn||this.#Vn.recordClipBox(this.#Wn,e,i,n,s,a),this}recordBBox(t,e,i,n,s,a){return this.#jn||this.#Vn.recordBBox(this.#Wn,e,i,n,s,a),this}recordCharacterBBox(t,e,i,n,s,a,r){return this.#jn||this.#Vn.recordCharacterBBox(this.#Wn,e,i,n,s,a,r),this}recordFullPageBBox(t){return this.#jn||this.#Vn.recordFullPageBBox(this.#Wn),this}getSimpleIndex(t){return this.#Vn.getSimpleIndex(t)}recordDependencies(t,e){return this.#Vn.recordDependencies(this.#Wn,e),this}recordNamedDependency(t,e){return this.#Vn.recordNamedDependency(this.#Wn,e),this}recordOperation(t){return this.#Vn.recordOperation(this.#Wn,!0),this}recordShowTextOperation(t){return this.#Vn.recordShowTextOperation(this.#Wn,!0),this}bboxToClipBoxDropOperation(t){return this.#jn||this.#Vn.bboxToClipBoxDropOperation(this.#Wn,!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const Dependencies={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]},PathType={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n),t.clip(s)}class BaseShadingPattern{isModifyingCurrentTransform(){return!1}getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}_createGradient(t,e=null){let i,n=this._p0,s=this._p1;if(e&&(n=n.slice(),s=s.slice(),Util.applyTransform(n,e),Util.applyTransform(s,e)),"axial"===this._type)i=t.createLinearGradient(n[0],n[1],s[0],s[1]);else if("radial"===this._type){let a=this._r0,r=this._r1;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t),a*=t[0],r*=t[0]}i=t.createRadialGradient(n[0],n[1],a,s[0],s[1],r)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}getPattern(t,e,i,n){let s;if(n===PathType.STROKE||n===PathType.FILL){if(this.isOriginBased()){let n=Util.transform(i,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix));const s=.001,a=Math.hypot(n[0],n[1]),r=Math.hypot(n[2],n[3]),o=(n[0]*n[2]+n[1]*n[3])/(a*r);if(Math.abs(o)<s){if(!this.isRadial())return this._createGradient(t,n);if(Math.abs(a-r)<s)return this._createGradient(t,n)}}const a=e.current.getClippedPathBoundingBox(n,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.cachedCanvases.getCanvas("pattern",r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-a[0],-a[1]),i=Util.transform(i,[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(),s=t.createPattern(l.canvas,"no-repeat");const d=new DOMMatrix(i);s.setTransform(d)}else applyBoundingBox(t,this._bbox),s=this._createGradient(t);return s}}function drawTriangle(t,e,i,n,s,a,r,o){const l=e.coords,h=e.colors,d=t.data,c=4*t.width;let u;l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=a,a=r,r=u),l[n+1]>l[s+1]&&(u=n,n=s,s=u,u=r,r=o,o=u),l[i+1]>l[n+1]&&(u=i,i=n,n=u,u=a,a=r,r=u);const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[s]+e.offsetX)*e.scaleX,A=(l[s+1]+e.offsetY)*e.scaleY;if(g>=A)return;const y=h[a],w=h[a+1],v=h[a+2],E=h[r],x=h[r+1],T=h[r+2],S=h[o],C=h[o+1],_=h[o+2],P=Math.round(g),D=Math.round(A);let M,I,k,F,R,L,B,O;for(let t=P;t<=D;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);M=p-(p-m)*e,I=y-(y-E)*e,k=w-(w-x)*e,F=v-(v-T)*e}else{let e;e=t>A?1:f===A?0:(f-t)/(f-A),M=m-(m-b)*e,I=E-(E-S)*e,k=x-(x-C)*e,F=T-(T-_)*e}let e;e=t<g?0:t>A?1:(g-t)/(g-A),R=p-(p-b)*e,L=y-(y-S)*e,B=w-(w-C)*e,O=v-(v-_)*e;const i=Math.round(Math.min(M,R)),n=Math.round(Math.max(M,R));let s=c*t+4*i;for(let t=i;t<=n;t++)e=(M-t)/(M-R),e<0?e=0:e>1&&(e=1),d[s++]=I-(I-L)*e|0,d[s++]=k-(k-B)*e|0,d[s++]=F-(F-O)*e|0,d[s++]=255}}function drawFigure(t,e,i){const n=e.coords,s=e.colors;let a,r;switch(e.type){case MeshFigureType.LATTICE:const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,h=o-1;for(a=0;a<l;a++){let e=a*o;for(let a=0;a<h;a++,e++)drawTriangle(t,i,n[e],n[e+1],n[e+o],s[e],s[e+1],s[e+o]),drawTriangle(t,i,n[e+o+1],n[e+1],n[e+o],s[e+o+1],s[e+1],s[e+o])}break;case MeshFigureType.TRIANGLES:for(a=0,r=n.length;a<r;a+=3)drawTriangle(t,i,n[a],n[a+1],n[a+2],s[a],s[a+1],s[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,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-n,r=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3),l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3),h=a/o,d=r/l,c={coords:this._coords,colors:this._colors,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/d},u=o+4,p=l+4,g=i.getCanvas("mesh",u,p),m=g.context,f=m.createImageData(o,l);if(e){const t=f.data;for(let i=0,n=t.length;i<n;i+=4)t[i]=e[0],t[i+1]=e[1],t[i+2]=e[2],t[i+3]=255}for(const t of this._figures)drawFigure(f,t,c);m.putImageData(f,2,2);return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*d,scaleX:h,scaleY:d}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,n){applyBoundingBox(t,this._bbox);const s=new Float32Array(2);if(n===PathType.SHADING)Util.singularValueDecompose2dScale(getCurrentTransform(t),s);else if(this.matrix){Util.singularValueDecompose2dScale(this.matrix,s);const[t,i]=s;Util.singularValueDecompose2dScale(e.baseTransform,s),s[0]*=t,s[1]*=i}else Util.singularValueDecompose2dScale(e.baseTransform,s);const a=this._createMeshCanvas(s,n===PathType.SHADING?null:this._background,e.cachedCanvases);return n!==PathType.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(a.offsetX,a.offsetY),t.scale(a.scaleX,a.scaleY),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 PaintType={COLORED:1,UNCOLORED:2};class TilingPattern{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n){this.color=t[1],this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.ctx=e,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t,e){const{bbox:i,operatorList:n,paintType:s,tilingType:a,color:r,canvasGraphicsFactory:o}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),info("TilingType: "+a);const d=i[0],c=i[1],u=i[2],p=i[3],g=u-d,m=p-c,f=new Float32Array(2);Util.singularValueDecompose2dScale(this.matrix,f);const[b,A]=f;Util.singularValueDecompose2dScale(this.baseTransform,f);const y=b*f[0],w=A*f[1];let v=g,E=m,x=!1,T=!1;const S=Math.ceil(l*y),C=Math.ceil(h*w);S>=Math.ceil(g*y)?v=l:x=!0,C>=Math.ceil(m*w)?E=h:T=!0;const _=this.getSizeAndScale(v,this.ctx.canvas.width,y),P=this.getSizeAndScale(E,this.ctx.canvas.height,w),D=t.cachedCanvases.getCanvas("pattern",_.size,P.size),M=D.context,I=o.createCanvasGraphics(M,e);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,s,r),M.translate(-_.scale*d,-P.scale*c),I.transform(0,_.scale,0,0,P.scale,0,0),M.save(),I.dependencyTracker?.save(),this.clipBbox(I,d,c,u,p),I.baseTransform=getCurrentTransform(I.ctx),I.executeOperatorList(n),I.endDrawing(),I.dependencyTracker?.restore(),M.restore(),x||T){const e=D.canvas;x&&(v=l),T&&(E=h);const i=this.getSizeAndScale(v,this.ctx.canvas.width,y),n=this.getSizeAndScale(E,this.ctx.canvas.height,w),s=i.size,a=n.size,r=t.cachedCanvases.getCanvas("pattern-workaround",s,a),o=r.context,u=x?Math.floor(g/l):0,p=T?Math.floor(m/h):0;for(let t=0;t<=u;t++)for(let i=0;i<=p;i++)o.drawImage(e,s*t,a*i,s,a,0,0,s,a);return{canvas:r.canvas,scaleX:i.scale,scaleY:n.scale,offsetX:d,offsetY:c}}return{canvas:D.canvas,scaleX:_.scale,scaleY:P.scale,offsetX:d,offsetY:c}}getSizeAndScale(t,e,i){const n=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);return s>=n?s=n:i=s/t,{scale:i,size:s}}clipBbox(t,e,i,n,s){const a=n-e,r=s-i;t.ctx.rect(e,i,a,r),Util.axialAlignedBoundingBox([e,i,n,s],getCurrentTransform(t.ctx),t.current.minMax),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;switch(e){case PaintType.COLORED:const{fillStyle:t,strokeStyle:a}=this.ctx;n.fillStyle=s.fillColor=t,n.strokeStyle=s.strokeColor=a;break;case PaintType.UNCOLORED:n.fillStyle=n.strokeStyle=i,s.fillColor=s.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){let a=i;n!==PathType.SHADING&&(a=Util.transform(a,e.baseTransform),this.matrix&&(a=Util.transform(a,this.matrix)));const r=this.createPatternCanvas(e,s);let o=new DOMMatrix(a);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");return l.setTransform(o),l}}function convertToRGBA(t){switch(t.kind){case ImageKind.GRAYSCALE_1BPP:return convertBlackAndWhiteToRGBA(t);case ImageKind.RGB_24BPP:return convertRGBToRGBA(t)}return null}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],d=n>>3,c=7&n,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let n=0;n<s;n++){for(const n=e+d;e<n;e++){const n=e<u?t[e]:255;i[p++]=128&n?h:l,i[p++]=64&n?h:l,i[p++]=32&n?h:l,i[p++]=16&n?h:l,i[p++]=8&n?h:l,i[p++]=4&n?h:l,i[p++]=2&n?h:l,i[p++]=1&n?h:l}if(0===c)continue;const n=e<u?t[e++]:255;for(let t=0;t<c;t++)i[p++]=n&1<<7-t?h:l}return{srcPos:e,destPos:p}}function convertRGBToRGBA({src:t,srcPos:e=0,dest:i,destPos:n=0,width:s,height:a}){let r=0;const o=s*a*3,l=o>>2,h=new Uint32Array(t.buffer,e,l);if(FeatureTest.isLittleEndian){for(;r<l-2;r+=3,n+=4){const t=h[r],e=h[r+1],s=h[r+2];i[n]=4278190080|t,i[n+1]=t>>>24|e<<8|4278190080,i[n+2]=e>>>16|s<<16|4278190080,i[n+3]=s>>>8|4278190080}for(let s=4*r,a=e+o;s<a;s+=3)i[n++]=t[s]|t[s+1]<<8|t[s+2]<<16|4278190080}else{for(;r<l-2;r+=3,n+=4){const t=h[r],e=h[r+1],s=h[r+2];i[n]=255|t,i[n+1]=t<<24|e>>>8|255,i[n+2]=e<<16|s>>>16|255,i[n+3]=s<<8|255}for(let s=4*r,a=e+o;s<a;s+=3)i[n++]=t[s]<<24|t[s+1]<<16|t[s+2]<<8|255}return{srcPos:e+o,destPos:n}}function grayToRGBA(t,e){if(FeatureTest.isLittleEndian)for(let i=0,n=t.length;i<n;i++)e[i]=65793*t[i]|4278190080;else for(let i=0,n=t.length;i<n;i++)e[i]=16843008*t[i]|255}const MIN_FONT_SIZE=16,MAX_FONT_SIZE=100,EXECUTION_TIME=15,EXECUTION_STEPS=10,FULL_CHUNK_HEIGHT=16,SCALE_MATRIX=new DOMMatrix,XY=new Float32Array(2),MIN_MAX_INIT=new Float32Array([1/0,1/0,-1/0,-1/0]);function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save,t.__originalRestore=t.restore,t.__originalRotate=t.rotate,t.__originalScale=t.scale,t.__originalTranslate=t.translate,t.__originalTransform=t.transform,t.__originalSetTransform=t.setTransform,t.__originalResetTransform=t.resetTransform,t.__originalClip=t.clip,t.__originalMoveTo=t.moveTo,t.__originalLineTo=t.lineTo,t.__originalBezierCurveTo=t.bezierCurveTo,t.__originalRect=t.rect,t.__originalClosePath=t.closePath,t.__originalBeginPath=t.beginPath,t._removeMirroring=()=>{t.save=t.__originalSave,t.restore=t.__originalRestore,t.rotate=t.__originalRotate,t.scale=t.__originalScale,t.translate=t.__originalTranslate,t.transform=t.__originalTransform,t.setTransform=t.__originalSetTransform,t.resetTransform=t.__originalResetTransform,t.clip=t.__originalClip,t.moveTo=t.__originalMoveTo,t.lineTo=t.__originalLineTo,t.bezierCurveTo=t.__originalBezierCurveTo,t.rect=t.__originalRect,t.closePath=t.__originalClosePath,t.beginPath=t.__originalBeginPath,delete t._removeMirroring},t.save=function(){e.save(),this.__originalSave()},t.restore=function(){e.restore(),this.__originalRestore()},t.translate=function(t,i){e.translate(t,i),this.__originalTranslate(t,i)},t.scale=function(t,i){e.scale(t,i),this.__originalScale(t,i)},t.transform=function(t,i,n,s,a,r){e.transform(t,i,n,s,a,r),this.__originalTransform(t,i,n,s,a,r)},t.setTransform=function(t,i,n,s,a,r){e.setTransform(t,i,n,s,a,r),this.__originalSetTransform(t,i,n,s,a,r)},t.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},t.rotate=function(t){e.rotate(t),this.__originalRotate(t)},t.clip=function(t){e.clip(t),this.__originalClip(t)},t.moveTo=function(t,i){e.moveTo(t,i),this.__originalMoveTo(t,i)},t.lineTo=function(t,i){e.lineTo(t,i),this.__originalLineTo(t,i)},t.bezierCurveTo=function(t,i,n,s,a,r){e.bezierCurveTo(t,i,n,s,a,r),this.__originalBezierCurveTo(t,i,n,s,a,r)},t.rect=function(t,i,n,s){e.rect(t,i,n,s),this.__originalRect(t,i,n,s)},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,i){let n;return void 0!==this.cache[t]?(n=this.cache[t],this.canvasFactory.reset(n,e,i)):(n=this.canvasFactory.create(e,i),this.cache[t]=n),n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,i,n,s,a,r,o,l,h){const[d,c,u,p,g,m]=getCurrentTransform(t);if(0===c&&0===u){const f=r*d+g,b=Math.round(f),A=o*p+m,y=Math.round(A),w=(r+l)*d+g,v=Math.abs(Math.round(w)-b)||1,E=(o+h)*p+m,x=Math.abs(Math.round(E)-y)||1;return t.setTransform(Math.sign(d),0,0,Math.sign(p),b,y),t.drawImage(e,i,n,s,a,0,0,v,x),t.setTransform(d,c,u,p,g,m),[v,x]}if(0===d&&0===p){const f=o*u+g,b=Math.round(f),A=r*c+m,y=Math.round(A),w=(o+h)*u+g,v=Math.abs(Math.round(w)-b)||1,E=(r+l)*c+m,x=Math.abs(Math.round(E)-y)||1;return t.setTransform(0,Math.sign(c),Math.sign(u),0,b,y),t.drawImage(e,i,n,s,a,0,0,x,v),t.setTransform(d,c,u,p,g,m),[x,v]}t.drawImage(e,i,n,s,a,r,o,l,h);return[Math.hypot(d,c)*l,Math.hypot(u,p)*h]}class CanvasExtraState{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=FONT_IDENTITY_MATRIX;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=TextRenderingMode.FILL;textRise=0;fillColor="#000000";strokeColor="#000000";patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";constructor(t,e,i){i?.(this),this.clipBox=new Float32Array([0,0,t,e]),this.minMax=MIN_MAX_INIT.slice()}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t.minMax=this.minMax.slice(),t}getPathBoundingBox(t=PathType.FILL,e=null){const i=this.minMax.slice();if(t===PathType.STROKE){e||unreachable("Stroke bounding box must include transform."),Util.singularValueDecompose2dScale(e,XY);const t=XY[0]*this.lineWidth/2,n=XY[1]*this.lineWidth/2;i[0]-=t,i[1]-=n,i[2]+=t,i[3]+=n}return i}updateClipFromPath(){const t=Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0),this.minMax.set(MIN_MAX_INIT,0)}getClippedPathBoundingBox(t=PathType.FILL,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){if(e instanceof ImageData)return void t.putImageData(e,0,0);const i=e.height,n=e.width,s=i%16,a=(i-s)/16,r=0===s?a:a+1,o=t.createImageData(n,16);let l,h=0;const d=e.data,c=o.data;let u,p,g,m;if(e.kind===util_ImageKind.GRAYSCALE_1BPP){const e=d.byteLength,i=new Uint32Array(c.buffer,0,c.byteLength>>2),m=i.length,f=n+7>>3,b=4294967295,A=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;u<r;u++){for(g=u<a?16:s,l=0,p=0;p<g;p++){const t=e-h;let s=0;const a=t>f?n:8*t-7,r=-8&a;let o=0,c=0;for(;s<r;s+=8)c=d[h++],i[l++]=128&c?b:A,i[l++]=64&c?b:A,i[l++]=32&c?b:A,i[l++]=16&c?b:A,i[l++]=8&c?b:A,i[l++]=4&c?b:A,i[l++]=2&c?b:A,i[l++]=1&c?b:A;for(;s<a;s++)0===o&&(c=d[h++],o=128),i[l++]=c&o?b:A,o>>=1}for(;l<m;)i[l++]=0;t.putImageData(o,0,16*u)}}else if(e.kind===util_ImageKind.RGBA_32BPP){for(p=0,m=16*n*4,u=0;u<a;u++)c.set(d.subarray(h,h+m)),h+=m,t.putImageData(o,0,p),p+=16;u<r&&(m=n*s*4,c.set(d.subarray(h,h+m)),t.putImageData(o,0,p))}else{if(e.kind!==util_ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${e.kind}`);for(g=16,m=n*g,u=0;u<r;u++){for(u>=a&&(g=s,m=n*g),l=0,p=m;p--;)c[l++]=d[h++],c[l++]=d[h++],c[l++]=d[h++],c[l++]=255;t.putImageData(o,0,16*u)}}}function putBinaryImageMask(t,e){if(e.bitmap)return void t.drawImage(e.bitmap,0,0);const i=e.height,n=e.width,s=i%16,a=(i-s)/16,r=0===s?a:a+1,o=t.createImageData(n,16);let l=0;const h=e.data,d=o.data;for(let e=0;e<r;e++){const i=e<a?16:s;({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:d,width:n,height:i,nonBlackColor:0})),t.putImageData(o,0,16*e)}}function copyCtxState(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function resetCtxToDefault(t){t.strokeStyle=t.fillStyle="#000000",t.fillRule="nonzero",t.globalAlpha=1,t.lineWidth=1,t.lineCap="butt",t.lineJoin="miter",t.miterLimit=10,t.globalCompositeOperation="source-over",t.font="10px sans-serif",void 0!==t.setLineDash&&(t.setLineDash([]),t.lineDashOffset=0);const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function getImageSmoothingEnabled(t,e){if(e)return!0;Util.singularValueDecompose2dScale(t,XY);const i=Math.fround(OutputScale.pixelRatio*PixelsPerInch.PDF_TO_CSS_UNITS);return XY[0]<=i&&XY[1]<=i}const LINE_CAP_STYLES=["butt","round","square"],LINE_JOIN_STYLES=["miter","round","bevel"],NORMAL_CLIP={},EO_CLIP={};class CanvasGraphics{constructor(t,e,i,n,s,{optionalContentConfig:a,markedContentStack:r=null},o,l,h){this.ctx=t,this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=i,this.canvasFactory=n,this.filterFactory=s,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=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,this.dependencyTracker=h??null}getObject(t,e,i=null){return"string"==typeof e?(this.dependencyTracker?.recordNamedDependency(t,e),e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)):i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const s=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;if(this.ctx.fillStyle=n||"#ffffff",this.ctx.fillRect(0,0,s,a),this.ctx.fillStyle=r,i){const t=this.cachedCanvases.getCanvas("transparent",s,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),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=getCurrentTransform(this.ctx)}executeOperatorList(t,e,i,n,s){const a=t.argsArray,r=t.fnArray;let o=e||0;const l=a.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,d=h?Date.now()+15:0;let c=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n&&o===n.nextBreakPoint)return n.breakIt(o,i),o;if(!s||s(o))if(g=r[o],m=a[o]??null,g!==OPS.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t))return e.get(t,i),o}if(o++,o===l)return o;if(h&&++c>10){if(Date.now()>d)return i(),o;c=0}}}#Xn(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#Xn(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#Yn()}#Yn(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight;let s,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=n,d="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;r>2&&l>1&&(e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2),r/=l/e),o>2&&h>1&&(i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,o/=h/i),s=this.cachedCanvases.getCanvas(d,e,i),a=s.context,a.clearRect(0,0,e,i),a.drawImage(t,0,0,l,h,0,0,e,i),t=s.canvas,l=e,h=i,d="prescale1"===d?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t,e){const i=this.ctx,{width:n,height:s}=e,a=this.current.fillColor,r=this.current.patternFill,o=getCurrentTransform(i);let l,h,d,c;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;h=JSON.stringify(r?o:[o.slice(0,4),a]),l=this._cachedBitmapsMap.get(i),l||(l=new Map,this._cachedBitmapsMap.set(i,l));const n=l.get(h);if(n&&!r){const e=Math.round(Math.min(o[0],o[2])+o[4]),i=Math.round(Math.min(o[1],o[3])+o[5]);return this.dependencyTracker?.recordDependencies(t,Dependencies.transformAndFill),{canvas:n,offsetX:e,offsetY:i}}d=n}d||(c=this.cachedCanvases.getCanvas("maskCanvas",n,s),putBinaryImageMask(c.context,e));let u=Util.transform(o,[1/n,0,0,-1/s,0,0]);u=Util.transform(u,[1,0,0,1,0,-s]);const p=MIN_MAX_INIT.slice();Util.axialAlignedBoundingBox([0,0,n,s],u,p);const[g,m,f,b]=p,A=Math.round(f-g)||1,y=Math.round(b-m)||1,w=this.cachedCanvases.getCanvas("fillCanvas",A,y),v=w.context,E=g,x=m;v.translate(-E,-x),v.transform(...u),d||(d=this._scaleImage(c.canvas,getCurrentTransformInverse(v)),d=d.img,l&&r&&l.set(h,d)),v.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(v),e.interpolate),drawImageAtIntegerCoords(v,d,0,0,d.width,d.height,0,0,n,s),v.globalCompositeOperation="source-in";const T=Util.transform(getCurrentTransformInverse(v),[1,0,0,1,-E,-x]);return v.fillStyle=r?a.getPattern(i,this,T,PathType.FILL,t):a,v.fillRect(0,0,n,s),l&&!r&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,w.canvas)),this.dependencyTracker?.recordDependencies(t,Dependencies.transformAndFill),{canvas:w.canvas,offsetX:Math.round(E),offsetY:Math.round(x)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t),e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t),this.ctx.lineCap=LINE_CAP_STYLES[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t),this.ctx.lineJoin=LINE_JOIN_STYLES[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t),this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;void 0!==n.setLineDash&&(n.setLineDash(e),n.lineDashOffset=i)}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t),this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t),this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t),this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t),this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,i=this.ctx.canvas.height,n="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(n,e,i);this.suspendedCtx=this.ctx;const a=this.ctx=s.context;a.setTransform(this.suspendedCtx.getTransform()),copyCtxState(this.suspendedCtx,a),mirrorContextOperations(a,this.suspendedCtx),this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),copyCtxState(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,i,n){const s=n[0],a=n[1],r=n[2]-s,o=n[3]-a;0!==r&&0!==o&&(this.genericComposeSMask(e.context,i,r,o,e.subtype,e.backdrop,e.transferMap,s,a,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(i.canvas,0,0),t.restore())}genericComposeSMask(t,e,i,n,s,a,r,o,l,h,d){let c=t.canvas,u=o-h,p=l-d;if(a)if(u<0||p<0||u+i>c.width||p+n>c.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,n),e=t.context;e.drawImage(c,-u,-p),e.globalCompositeOperation="destination-atop",e.fillStyle=a,e.fillRect(0,0,i,n),e.globalCompositeOperation="source-over",c=t.canvas,u=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const e=new Path2D;e.rect(u,p,i,n),t.clip(e),t.globalCompositeOperation="destination-atop",t.fillStyle=a,t.fillRect(u,p,i,n),t.restore()}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),"Alpha"===s&&r?e.filter=this.filterFactory.addAlphaFilter(r):"Luminosity"===s&&(e.filter=this.filterFactory.addLuminosityFilter(r));const g=new Path2D;g.rect(o,l,i,n),e.clip(g),e.globalCompositeOperation="destination-in",e.drawImage(c,u,p,i,n,o,l,i,n),e.restore()}save(t){this.inSMaskMode&&copyCtxState(this.ctx,this.suspendedCtx),this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone(),this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t),0!==this.stateStack.length?(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&copyCtxState(this.suspendedCtx,this.ctx),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null):this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,a,r){this.dependencyTracker?.recordIncrementalData("transform",t),this.ctx.transform(e,i,n,s,a,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(!n)return s||=i[0]=new Path2D,void this[e](t,s);if(null!==this.dependencyTracker){const i=e===OPS.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}s instanceof Path2D||(s=i[0]=makePathFromDrawOPS(s)),Util.axialAlignedBoundingBox(n,getCurrentTransform(this.ctx),this.current.minMax),this[e](t,s),this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=this.ctx,s=this.current.strokeColor;if(n.globalAlpha=this.current.strokeAlpha,this.contentVisible)if("object"==typeof s&&s?.getPattern){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(n.save(),n.strokeStyle=s.getPattern(n,this,getCurrentTransformInverse(n),PathType.STROKE,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}this.rescaleAndStroke(e,!1),n.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,Dependencies.stroke),i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(PathType.STROKE,getCurrentTransform(this.ctx))),n.globalAlpha=this.current.fillAlpha}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=this.ctx,s=this.current.fillColor;let a=!1;if(this.current.patternFill){const i=s.isModifyingCurrentTransform()?n.getTransform():null;if(this.dependencyTracker?.save(t),n.save(),n.fillStyle=s.getPattern(n,this,getCurrentTransformInverse(n),PathType.FILL,t),i){const t=new Path2D;t.addPath(e,n.getTransform().invertSelf().multiplySelf(i)),e=t}a=!0}const r=this.current.getClippedPathBoundingBox();this.contentVisible&&null!==r&&(this.pendingEOFill?(n.fill(e,"evenodd"),this.pendingEOFill=!1):n.fill(e)),this.dependencyTracker?.recordDependencies(t,Dependencies.fill),a&&(n.restore(),this.dependencyTracker?.restore(t)),i&&this.consumePath(t,e,r)}eoFill(t,e){this.pendingEOFill=!0,this.fill(t,e)}fillStroke(t,e){this.fill(t,e,!1),this.stroke(t,e,!1),this.consumePath(t,e)}eoFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0,this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){this.ctx.fill(e),this.dependencyTracker?.recordDependencies(t,Dependencies.rawFillPath).recordOperation(t)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=NORMAL_CLIP}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t),this.pendingClip=EO_CLIP}beginText(t){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t),i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:a,fontSize:r,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,a).scale(r,-r));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t),this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t),this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t),this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t),this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const n=this.commonObjs.get(e),s=this.current;if(!n)throw new Error(`Can\'t find font for ${e}`);if(s.fontMatrix=n.fontMatrix||FONT_IDENTITY_MATRIX,0!==s.fontMatrix[0]&&0!==s.fontMatrix[3]||warn("Invalid font matrix for font "+e),i<0?(i=-i,s.fontDirection=-1):s.fontDirection=1,this.current.font=n,this.current.fontSize=i,n.isType3Font)return;const a=n.loadedName||"sans-serif",r=n.systemFontInfo?.css||`"${a}", ${n.fallbackName}`;let o="normal";n.black?o="900":n.bold&&(o="bold");const l=n.italic?"italic":"normal";let h=i;i<16?h=16:i>100&&(h=100),this.current.fontSizeScale=i/h,this.ctx.font=`${l} ${o} ${h}px ${r}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t),this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t),this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t),this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i),this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e,i.textMatrixScale=Math.hypot(e[0],e[1]),i.x=i.lineX=0,i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#qn(t,e,i){const n=new Path2D;return n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e)),n}paintChar(t,e,i,n,s,a){const r=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,d=o.fontSize/o.fontSizeScale,c=h&TextRenderingMode.FILL_STROKE_MASK,u=!!(h&TextRenderingMode.ADD_TO_PATH_FLAG),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e)),m&&(l.disableFontFace||p||g)){let e;if(r.save(),r.translate(i,n),r.scale(d,-d),this.dependencyTracker?.recordCharacterBBox(t,r,l),c===TextRenderingMode.FILL||c===TextRenderingMode.FILL_STROKE)if(s){e=r.getTransform(),r.setTransform(...s);const t=this.#qn(m,e,s);r.fill(t)}else r.fill(m);if(c===TextRenderingMode.STROKE||c===TextRenderingMode.FILL_STROKE)if(a){e||=r.getTransform(),r.setTransform(...a);const{a:t,b:i,c:n,d:s}=e,o=Util.inverseTransform(a),l=Util.transform([t,i,n,s,0,0],o);Util.singularValueDecompose2dScale(l,XY),r.lineWidth*=Math.max(XY[0],XY[1])/d,r.stroke(this.#qn(m,e,a))}else r.lineWidth/=d,r.stroke(m);r.restore()}else c!==TextRenderingMode.FILL&&c!==TextRenderingMode.FILL_STROKE||(r.fillText(e,i,n),this.dependencyTracker?.recordCharacterBBox(t,r,l,d,i,n,()=>r.measureText(e))),c!==TextRenderingMode.STROKE&&c!==TextRenderingMode.FILL_STROKE||(this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,r,l,d,i,n,()=>r.measureText(e)).recordDependencies(t,Dependencies.stroke),r.strokeText(e,i,n));if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(r),x:i,y:n,fontSize:d,path:m}),this.dependencyTracker?.recordCharacterBBox(t,r,l,d,i,n)}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t<e.length;t+=4)if(e[t]>0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t,e){this.dependencyTracker&&(this.dependencyTracker.recordDependencies(t,Dependencies.showText).resetBBox(t),this.current.textRenderingMode&TextRenderingMode.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies());const i=this.current,n=i.font;if(n.isType3Font)return this.showType3Text(t,e),void this.dependencyTracker?.recordShowTextOperation(t);const s=i.fontSize;if(0===s)return void this.dependencyTracker?.recordOperation(t);const a=this.ctx,r=i.fontSizeScale,o=i.charSpacing,l=i.wordSpacing,h=i.fontDirection,d=i.textHScale*h,c=e.length,u=n.vertical,p=u?1:-1,g=n.defaultVMetrics,m=s*i.fontMatrix[0],f=i.textRenderingMode===TextRenderingMode.FILL&&!n.disableFontFace&&!i.patternFill;let b,A;a.save(),i.textMatrix&&a.transform(...i.textMatrix),a.translate(i.x,i.y+i.textRise),h>0?a.scale(d,-1):a.scale(d,1);const y=i.textRenderingMode&TextRenderingMode.FILL_STROKE_MASK,w=y===TextRenderingMode.STROKE||y===TextRenderingMode.FILL_STROKE;if((y===TextRenderingMode.FILL||y===TextRenderingMode.FILL_STROKE)&&i.patternFill){a.save();const e=i.fillColor.getPattern(a,this,getCurrentTransformInverse(a),PathType.FILL,t);b=getCurrentTransform(a),a.restore(),a.fillStyle=e}if(w&&i.patternStroke){a.save();const e=i.strokeColor.getPattern(a,this,getCurrentTransformInverse(a),PathType.STROKE,t);A=getCurrentTransform(a),a.restore(),a.strokeStyle=e}let v=i.lineWidth;const E=i.textMatrixScale;if(0===E||0===v?w&&(v=this.getSinglePixelWidth()):v/=E,1!==r&&(a.scale(r,r),v/=r),a.lineWidth=v,n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e)n.push(t.unicode),s+=t.width;const r=n.join("");if(a.fillText(r,0,0),null!==this.dependencyTracker){const e=a.measureText(r);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}return i.x+=s*m*d,a.restore(),void this.compose()}let x,T=0;for(x=0;x<c;++x){const i=e[x];if("number"==typeof i){T+=p*i*s/1e3;continue}let d=!1;const c=(i.isSpace?l:0)+o,y=i.fontChar,w=i.accent;let v,E,S,C=i.width;if(u){const t=i.vmetric||g,e=-(i.vmetric?t[1]:.5*C)*m,n=t[2]*m;C=t?-t[0]:C,v=e/r,E=(T+n)/r}else v=T/r,E=0;if(n.remeasure&&C>0){S=a.measureText(y);const t=1e3*S.width/s*r;if(C<t&&this.isFontSubpixelAAEnabled){const e=C/t;d=!0,a.save(),a.scale(e,1),v/=e}else C!==t&&(v+=(C-t)/2e3*s/r)}if(this.contentVisible&&(i.isInFont||n.missingFile))if(f&&!w)a.fillText(y,v,E),this.dependencyTracker?.recordCharacterBBox(t,a,S?{bbox:null}:n,s/r,v,E,()=>S??a.measureText(y));else if(this.paintChar(t,y,v,E,b,A),w){const e=v+s*w.offset.x/r,i=E-s*w.offset.y/r;this.paintChar(t,w.fontChar,e,i,b,A)}T+=u?C*m-c*h:C*m+c*h,d&&a.restore()}u?i.y-=T:i.x+=T*d,a.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(t)}showType3Text(t,e){const i=this.ctx,n=this.current,s=n.font,a=n.fontSize,r=n.fontDirection,o=s.vertical?1:-1,l=n.charSpacing,h=n.wordSpacing,d=n.textHScale*r,c=n.fontMatrix||FONT_IDENTITY_MATRIX,u=e.length;let p,g,m,f;if(n.textRenderingMode===TextRenderingMode.INVISIBLE||0===a)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,i.save(),n.textMatrix&&i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),i.scale(d,r);const b=this.dependencyTracker;for(this.dependencyTracker=b?new CanvasNestedDependencyTracker(b,t):null,p=0;p<u;++p){if(g=e[p],"number"==typeof g){f=o*g*a/1e3,this.ctx.translate(f,0),n.x+=f*d;continue}const t=(g.isSpace?h:0)+l,r=s.charProcOperatorList[g.operatorListId];r?this.contentVisible&&(this.save(),i.scale(a,a),i.transform(...c),this.executeOperatorList(r),this.restore()):warn(`Type3 character "${g.operatorListId}" is not available.`);const u=[g.width,0];Util.applyTransform(u,c),m=u[0]*a+t,i.translate(m,0),n.x+=m*d}i.restore(),b&&(this.dependencyTracker=b)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,n,s,a,r){const o=new Path2D;o.rect(n,s,a-n,r-s),this.ctx.clip(o),this.dependencyTracker?.recordBBox(t,this.ctx,n,a,s,r).recordClipBox(t,this.ctx,n,a,s,r),this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||getCurrentTransform(this.ctx),n={createCanvasGraphics:(t,e)=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new CanvasNestedDependencyTracker(this.dependencyTracker,e,!0):null)};i=new TilingPattern(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.current.strokeColor=this.getColorN_Pattern(t,e),this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.current.fillColor=this.getColorN_Pattern(t,e),this.current.patternFill=!0}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor=e,this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor=e,this.current.patternFill=!1}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e,i=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=getShadingPattern(this.getObject(t,e)),this.cachedPatterns.set(e,n)),i&&(n.matrix=i),n}shadingFill(t,e){if(!this.contentVisible)return;const i=this.ctx;this.save(t);const n=this._getPattern(t,e);i.fillStyle=n.getPattern(i,this,getCurrentTransformInverse(i),PathType.SHADING,t);const s=getCurrentTransformInverse(i);if(s){const{width:t,height:e}=i.canvas,n=MIN_MAX_INIT.slice();Util.axialAlignedBoundingBox([0,0,t,e],s,n);const[a,r,o,l]=n;this.ctx.fillRect(a,r,o-a,l-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,Dependencies.transform).recordDependencies(t,Dependencies.fill).recordOperation(t),this.compose(this.current.getClippedPathBoundingBox()),this.restore(t)}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible&&(this.save(t),this.baseTransformStack.push(this.baseTransform),e&&this.transform(t,...e),this.baseTransform=getCurrentTransform(this.ctx),i)){Util.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,a]=i,r=new Path2D;r.rect(e,n,s-e,a-n),this.ctx.clip(r),this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,a),this.endPath(t)}}paintFormXObjectEnd(t){this.contentVisible&&(this.restore(t),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t,e){if(!this.contentVisible)return;this.save(t),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;e.isolated||info("TODO: Support non-isolated groups."),e.knockout&&warn("Knockout groups not supported.");const n=getCurrentTransform(i);if(e.matrix&&i.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let s=MIN_MAX_INIT.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(i),s);const a=[0,0,i.canvas.width,i.canvas.height];s=Util.intersect(s,a)||[0,0,0,0];const r=Math.floor(s[0]),o=Math.floor(s[1]),l=Math.max(Math.ceil(s[2])-r,1),h=Math.max(Math.ceil(s[3])-o,1);this.current.startNewPathAndClipBox([0,0,l,h]);let d="groupAt"+this.groupLevel;e.smask&&(d+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(d,l,h),u=c.context;u.translate(-r,-o),u.transform(...n);let p=new Path2D;const[g,m,f,b]=e.bbox;if(p.rect(g,m,f-g,b-m),e.matrix){const t=new Path2D;t.addPath(p,new DOMMatrix(e.matrix)),p=t}u.clip(p),e.smask&&this.smaskStack.push({canvas:c.canvas,context:u,offsetX:r,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}),e.smask&&!this.dependencyTracker||(i.setTransform(1,0,0,1,0,0),i.translate(r,o),i.save()),copyCtxState(i,u),this.ctx=u,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(t,[["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(i),this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const i=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),e.smask)this.tempSMask=this.smaskStack.pop(),this.restore(t),this.dependencyTracker&&this.ctx.restore();else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t),this.ctx.save(),this.ctx.setTransform(...e);const n=MIN_MAX_INIT.slice();Util.axialAlignedBoundingBox([0,0,i.canvas.width,i.canvas.height],e,n),this.ctx.drawImage(i.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,i,n,s,a){if(this.#Xn(),resetCtxToDefault(this.ctx),this.ctx.save(),this.save(t),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),i){const s=i[2]-i[0],r=i[3]-i[1];if(a&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0],n[5]-=i[1],(i=i.slice())[0]=i[1]=0,i[2]=s,i[3]=r,Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),XY);const{viewportScale:t}=this,a=Math.ceil(s*this.outputScaleX*t),o=Math.ceil(r*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(a,o);const{canvas:l,context:h}=this.annotationCanvas;this.annotationCanvasMap.set(e,l),this.annotationCanvas.savedCtx=this.ctx,this.ctx=h,this.ctx.save(),this.ctx.setTransform(XY[0],0,0,-XY[1],0,r*XY[1]),resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx),this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,r),this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(t,...n),this.transform(t,...s)}endAnnotation(t){this.annotationCanvas&&(this.ctx.restore(),this.#Yn(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.ctx,s=this._createMaskCanvas(t,e),a=s.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,s.offsetX,s.offsetY),this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,s.offsetX,s.offsetX+a.width,s.offsetY,s.offsetY+a.height).recordOperation(t),n.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,a,r){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.ctx;o.save();const l=getCurrentTransform(o);o.transform(i,n,s,a,0,0);const h=this._createMaskCanvas(t,e);o.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]),this.dependencyTracker?.resetBBox(t);for(let e=0,d=r.length;e<d;e+=2){const d=Util.transform(l,[i,n,s,a,r[e],r[e+1]]);o.drawImage(h.canvas,d[4],d[5]),this.dependencyTracker?.recordBBox(t,this.ctx,d[4],d[4]+h.canvas.width,d[5],d[5]+h.canvas.height)}o.restore(),this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.ctx,n=this.current.fillColor,s=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,Dependencies.transformAndFill);for(const a of e){const{data:e,width:r,height:o,transform:l}=a,h=this.cachedCanvases.getCanvas("maskCanvas",r,o),d=h.context;d.save();putBinaryImageMask(d,this.getObject(t,e,a)),d.globalCompositeOperation="source-in",d.fillStyle=s?n.getPattern(d,this,getCurrentTransformInverse(i),PathType.FILL,t):n,d.fillRect(0,0,r,o),d.restore(),i.save(),i.transform(...l),i.scale(1,-1),drawImageAtIntegerCoords(i,h.canvas,0,0,r,o,0,-1,1,1),this.dependencyTracker?.recordBBox(t,i,0,r,0,o),i.restore()}this.compose(),this.dependencyTracker?.recordOperation(t)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):warn("Dependent image isn\'t ready yet")}paintImageXObjectRepeat(t,e,i,n,s){if(!this.contentVisible)return;const a=this.getObject(t,e);if(!a)return void warn("Dependent image isn\'t ready yet");const r=a.width,o=a.height,l=[];for(let t=0,e=s.length;t<e;t+=2)l.push({transform:[i,0,0,n,s[t],s[t+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(t,a,l)}applyTransferMapsToCanvas(t){return"none"!==this.current.transferMaps&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return t.bitmap;const{bitmap:e,width:i,height:n}=t,s=this.cachedCanvases.getCanvas("inlineImage",i,n),a=s.context;return a.filter=this.current.transferMaps,a.drawImage(e,0,0),a.filter="none",s.canvas}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,n=e.height,s=this.ctx;this.save(t);const{filter:a}=s;let r;if("none"!==a&&""!==a&&(s.filter="none"),s.scale(1/i,-1/n),e.bitmap)r=this.applyTransferMapsToBitmap(e);else if("function"==typeof HTMLElement&&e instanceof HTMLElement||!e.data)r=e;else{const t=this.cachedCanvases.getCanvas("inlineImage",i,n).context;putBinaryImageData(t,e),r=this.applyTransferMapsToCanvas(t)}const o=this._scaleImage(r,getCurrentTransformInverse(s));s.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(s),e.interpolate),this.dependencyTracker?.resetBBox(t).recordBBox(t,s,0,i,-n,0).recordDependencies(t,Dependencies.imageXObject).recordOperation(t),drawImageAtIntegerCoords(s,o.img,0,0,o.paintWidth,o.paintHeight,0,-n,i,n),this.compose(),this.restore(t)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const n=this.ctx;let s;if(e.bitmap)s=e.bitmap;else{const t=e.width,i=e.height,n=this.cachedCanvases.getCanvas("inlineImage",t,i).context;putBinaryImageData(n,e),s=this.applyTransferMapsToCanvas(n)}this.dependencyTracker?.resetBBox(t);for(const e of i)n.save(),n.transform(...e.transform),n.scale(1,-1),drawImageAtIntegerCoords(n,s,e.x,e.y,e.w,e.h,0,-1,1,1),this.dependencyTracker?.recordBBox(t,n,0,1,-1,0),n.restore();this.dependencyTracker?.recordOperation(t),this.compose()}paintSolidColorImageMask(t){this.contentVisible&&(this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,Dependencies.fill).recordOperation(t),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t),"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const n=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(i);const s=this.ctx;this.pendingClip?(n||(this.pendingClip===EO_CLIP?s.clip(e,"evenodd"):s.clip(e)),this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)):this.dependencyTracker?.recordOperation(t),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=getCurrentTransform(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let a,r;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t)a=1/i,r=1/n;else{const e=i*t,s=n*t;a=e<1?1/e:1,r=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t)a=h/o,r=l/o;else{const e=t*o;a=h>e?h/e:1,r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,a]=this.getScaleForStroking();if(s===a)return i.lineWidth=(n||1)*s,void i.stroke(t);const r=i.getLineDash();e&&i.save(),i.scale(s,a),SCALE_MATRIX.a=1/s,SCALE_MATRIX.d=1/a;const o=new Path2D;if(o.addPath(t,SCALE_MATRIX),r.length>0){const t=Math.max(s,a);i.setLineDash(r.map(e=>e/t)),i.lineDashOffset/=t}i.lineWidth=n||1,i.stroke(o),e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in OPS)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[OPS[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#Jn=null;static#Qn="";static get workerPort(){return this.#Jn}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#Jn=t}static get workerSrc(){return this.#Qn}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Qn=t}}class Metadata{#Zn;#ts;constructor({parsedData:t,rawData:e}){this.#Zn=t,this.#ts=e}getRaw(){return this.#ts}get(t){return this.#Zn.get(t)??null}[Symbol.iterator](){return this.#Zn.entries()}}const INTERNAL=Symbol("INTERNAL");class OptionalContentGroup{#es=!1;#is=!1;#ns=!1;#ss=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:s}){this.#es=!!(t&RenderingIntentFlag.DISPLAY),this.#is=!!(t&RenderingIntentFlag.PRINT),this.name=e,this.intent=i,this.usage=n,this.rbGroups=s}get visible(){if(this.#ns)return this.#ss;if(!this.#ss)return!1;const{print:t,view:e}=this.usage;return this.#es?"OFF"!==e?.viewState:!this.#is||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==INTERNAL&&unreachable("Internal method `_setVisible` called."),this.#ns=i,this.#ss=e}}class OptionalContentConfig{#as=null;#rs=new Map;#os=null;#ls=null;constructor(t,e=RenderingIntentFlag.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,null!==t){this.name=t.name,this.creator=t.creator,this.#ls=t.order;for(const i of t.groups)this.#rs.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#rs.values())t._setVisible(INTERNAL,!1);for(const e of t.on)this.#rs.get(e)._setVisible(INTERNAL,!0);for(const e of t.off)this.#rs.get(e)._setVisible(INTERNAL,!1);this.#os=this.getHash()}}#hs(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n<e;n++){const e=t[n];let s;if(Array.isArray(e))s=this.#hs(e);else{if(!this.#rs.has(e))return warn(`Optional content group not found: ${e}`),!0;s=this.#rs.get(e).visible}switch(i){case"And":if(!s)return!1;break;case"Or":if(s)return!0;break;case"Not":return!s;default:return!0}}return"And"===i}isVisible(t){if(0===this.#rs.size)return!0;if(!t)return info("Optional content group not defined."),!0;if("OCG"===t.type)return this.#rs.has(t.id)?this.#rs.get(t.id).visible:(warn(`Optional content group not found: ${t.id}`),!0);if("OCMD"===t.type){if(t.expression)return this.#hs(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#rs.has(e))return warn(`Optional content group not found: ${e}`),!0;if(this.#rs.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#rs.has(e))return warn(`Optional content group not found: ${e}`),!0;if(!this.#rs.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#rs.has(e))return warn(`Optional content group not found: ${e}`),!0;if(!this.#rs.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#rs.has(e))return warn(`Optional content group not found: ${e}`),!0;if(this.#rs.get(e).visible)return!1}return!0}return warn(`Unknown optional content policy ${t.policy}.`),!0}return warn(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,i=!0){const n=this.#rs.get(t);if(n){if(i&&e&&n.rbGroups.length)for(const e of n.rbGroups)for(const i of e)i!==t&&this.#rs.get(i)?._setVisible(INTERNAL,!1,!0);n._setVisible(INTERNAL,!!e,!0),this.#as=null}else warn(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#rs.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#as=null}get hasInitialVisibility(){return null===this.#os||this.getHash()===this.#os}getOrder(){return this.#rs.size?this.#ls?this.#ls.slice():[...this.#rs.keys()]:null}getGroup(t){return this.#rs.get(t)||null}getHash(){if(null!==this.#as)return this.#as;const t=new MurmurHash3_64;for(const[e,i]of this.#rs)t.update(`${e}:${i.visible}`);return this.#as=t.hexdigest()}[Symbol.iterator](){return this.#rs.entries()}}class BasePDFStream{#ds=null;#cs=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t,this.#ds=e,this.#cs=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return assert(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#ds(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new this.#cs(this,t,e);return this._rangeReaders.add(i),i}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class BasePDFStreamReader{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=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(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}class BasePDFStreamRangeReader{_stream=null;constructor(t,e,i){this._stream=t}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}function getArrayBuffer(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}class PDFDataTransportStream extends BasePDFStream{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,PDFDataTransportStreamReader,PDFDataTransportStreamRangeReader);const{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:n}=e;if(i?.length>0){const t=getArrayBuffer(i);this._queuedChunks.push(t)}this._progressiveDone=n,e.addRangeListener((t,e)=>{this.#us(t,e)}),e.addProgressListener((t,e)=>{void 0!==e&&this._fullReader?.onProgress?.({loaded:t,total:e})}),e.addProgressiveReadListener(t=>{this.#us(void 0,t)}),e.addProgressiveDoneListener(()=>{this._fullReader?.progressiveDone(),this._progressiveDone=!0}),e.transportReady()}#us(t,e){const i=getArrayBuffer(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);assert(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),e._enqueue(i)}}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,e){const i=super.getRangeReader(t,e);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,e)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader extends BasePDFStreamReader{_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:n}=t._source,{length:s,contentDispositionFilename:a}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone,this._contentLength=s,this._isStreamingSupported=!n,this._isRangeSupported=!i,isPdfFile(a)&&(this._filename=a),this._headersCapability.resolve()}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||=!0}}class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader{onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i),this._begin=e}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this.onDone?.()}}async read(){if(this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this.onDone?.()}}function getFilenameFromContentDispositionHeader(t){let e=!0,i=n("filename\\\\*","i").exec(t);if(i){i=i[1];let t=r(i);return t=unescape(t),t=o(t),t=l(t),a(t)}if(i=function(t){const e=[];let i;const s=n("filename\\\\*((?!0\\\\d)\\\\d+)(\\\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,n,s]=i;if(t=parseInt(t,10),t in e){if(0===t)break}else e[t]=[n,s]}const a=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=r(n),i&&(n=unescape(n),0===t&&(n=o(n))),a.push(n)}return a.join("")}(t),i){return a(l(i))}if(i=n("filename","i").exec(t),i){i=i[1];let t=r(i);return t=l(t),a(t)}function n(t,e){return new RegExp("(?:^|;)\\\\s*"+t+\'\\\\s*=\\\\s*([^";\\\\s][^;\\\\s]*|"(?:[^"\\\\\\\\]|\\\\\\\\"?)+"?)\',e)}function s(t,i){if(t){if(!/^[\\x00-\\xFF]+$/.test(i))return i;try{const n=new TextDecoder(t,{fatal:!0}),s=stringToBytes(i);i=n.decode(s),e=!1}catch{}}return i}function a(t){return e&&/[\\x80-\\xff]/.test(t)&&(t=s("utf-8",t),e&&(t=s("iso-8859-1",t))),t}function r(t){if(t.startsWith(\'"\')){const e=t.slice(1).split(\'\\\\"\');for(let t=0;t<e.length;++t){const i=e[t].indexOf(\'"\');-1!==i&&(e[t]=e[t].slice(0,i),e.length=t+1),e[t]=e[t].replaceAll(/\\\\(.)/g,"$1")}t=e.join(\'"\')}return t}function o(t){const e=t.indexOf("\'");if(-1===e)return t;return s(t.slice(0,e),t.slice(e+1).replace(/^[^\']*\'/,""))}function l(t){return!t.startsWith("=?")||/[\\x00-\\x19\\x80-\\xff]/.test(t)?t:t.replaceAll(/=\\?([\\w-]*)\\?([QqBb])\\?((?:[^?]|\\?(?!=))*)\\?=/g,function(t,e,i,n){if("q"===i||"Q"===i)return s(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{n=atob(n)}catch{}return s(e,n)})}return""}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return s;if(s.suggestedLength=a,a<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;return"identity"!==(t.get("Content-Encoding")||"identity")||(s.allowRangeRequests=!0),s}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,404===t||0===t&&e.startsWith("file:"))}function ensureResponseOrigin(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function fetchUrl(t,e,i,n){return fetch(t,{method:"GET",headers:e,signal:n.signal,mode:"cors",credentials:i?"include":"same-origin",redirect:"follow"})}function ensureResponseStatus(t,e){if(200!==t&&206!==t)throw createResponseError(t,e)}function fetch_stream_getArrayBuffer(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(warn(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class PDFFetchStream extends BasePDFStream{_responseOrigin=null;constructor(t){super(t,PDFFetchStreamReader,PDFFetchStreamRangeReader),this.isHttp=/^https?:/i.test(t.url),this.headers=createHeaders(this.isHttp,t.httpHeaders)}}class PDFFetchStreamReader extends BasePDFStreamReader{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,length:n,rangeChunkSize:s,url:a,withCredentials:r}=t._source;this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!e;const o=new Headers(t.headers);fetchUrl(a,o,r,this._abortController).then(i=>{t._responseOrigin=getResponseOrigin(i.url),ensureResponseStatus(i.status,a),this._reader=i.body.getReader();const n=i.headers,{allowRangeRequests:r,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:n,isHttp:t.isHttp,rangeChunkSize:s,disableRange:e});this._isRangeSupported=r,this._contentLength=o||this._contentLength,this._filename=extractFilenameFromHeader(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:fetch_stream_getArrayBuffer(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n,withCredentials:s}=t._source,a=new Headers(t.headers);a.append("Range",`bytes=${e}-${i-1}`),fetchUrl(n,a,s,this._abortController).then(e=>{ensureResponseOrigin(getResponseOrigin(e.url),t._responseOrigin),ensureResponseStatus(e.status,n),this._reader=e.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:fetch_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const OK_RESPONSE=200,PARTIAL_CONTENT_RESPONSE=206;function network_getArrayBuffer(t){return"string"!=typeof t?t:stringToBytes(t).buffer}class PDFNetworkStream extends BasePDFStream{#ps=new WeakMap;_responseOrigin=null;constructor(t){super(t,PDFNetworkStreamReader,PDFNetworkStreamRangeReader),this.url=t.url,this.isHttp=/^https?:/i.test(this.url),this.headers=createHeaders(this.isHttp,t.httpHeaders)}_request(t){const e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#ps.set(e,i),e.open("GET",this.url),e.withCredentials=this._source.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=t=>206===t||200===t):i.validateStatus=t=>200===t,e.responseType="arraybuffer",assert(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>t.onError(e.status),e.onreadystatechange=this.#gs.bind(this,e),e.onprogress=this.#ms.bind(this,e),e.send(null),e}#ms(t,e){const i=this.#ps.get(t);i?.onProgress?.(e)}#gs(t,e){const i=this.#ps.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),4!==t.readyState)return;if(!this.#ps.has(t))return;if(this.#ps.delete(t),0===t.status&&this.isHttp)return void i.onError(t.status);const n=t.status||200;if(!i.validateStatus(n))return void i.onError(t.status);const s=network_getArrayBuffer(t.response);if(206===n){const e=t.getResponseHeader("Content-Range");/bytes (\\d+)-(\\d+)\\/(\\d+)/.test(e)?i.onDone(s):(warn(\'Missing or invalid "Content-Range" header.\'),i.onError(0))}else s?i.onDone(s):i.onError(t.status)}_abortRequest(t){this.#ps.has(t)&&(this.#ps.delete(t),t.abort())}getRangeReader(t,e){const i=super.getRangeReader(t,e);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}class PDFNetworkStreamReader extends BasePDFStreamReader{_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t);const{length:e}=t._source;this._contentLength=e,this._fullRequestXhr=t._request({onHeadersReceived:this.#fs.bind(this),onDone:this.#bs.bind(this),onError:this.#As.bind(this),onProgress:this.#ms.bind(this)})}#fs(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,n=this._fullRequestXhr;t._responseOrigin=getResponseOrigin(n.responseURL);const s=n.getAllResponseHeaders(),a=new Headers(s?s.trimStart().replace(/[^\\S ]+$/,"").split(/[\\r\\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{allowRangeRequests:r,suggestedLength:o}=validateRangeRequestCapabilities({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});r&&(this._isRangeSupported=!0),this._contentLength=o||this._contentLength,this._filename=extractFilenameFromHeader(a),this._isRangeSupported&&t._abortRequest(n),this._headersCapability.resolve()}#bs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._cachedChunks.push(t);if(this._done=!0,!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}#As(t){this._storedError=createResponseError(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#ms(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader{onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i),this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#fs.bind(this),onDone:this.#bs.bind(this),onError:this.#As.bind(this),onProgress:null})}#fs(){const t=getResponseOrigin(this._requestXhr?.responseURL);try{ensureResponseOrigin(t,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#As(0)}}#bs(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this.onClosed?.()}#As(t){this._storedError??=createResponseError(t,this._stream.url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}const urlRegex=/^[a-z][a-z0-9\\-+.]+:/i;function parseUrlOrPath(t){if(urlRegex.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}function getReadableStream(t){const{Readable:e}=process.getBuiltinModule("stream");if("function"==typeof e.toWeb)return e.toWeb(t);return process.getBuiltinModule("module").createRequire(import.meta.url)("node-readable-to-web-readable-stream").makeDefaultReadableStreamFromNodeReadable(t)}function node_stream_getArrayBuffer(t){return t instanceof Uint8Array?t.buffer:t instanceof ArrayBuffer?t:(warn(`getArrayBuffer - unexpected data format: ${t}`),new Uint8Array(t).buffer)}class PDFNodeStream extends BasePDFStream{constructor(t){super(t,PDFNodeStreamReader,PDFNodeStreamRangeReader),this.url=parseUrlOrPath(t.url),assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.")}}class PDFNodeStreamReader extends BasePDFStreamReader{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,length:n,rangeChunkSize:s}=t._source;this._contentLength=n,this._isStreamingSupported=!i,this._isRangeSupported=!e;const a=t.url,r=process.getBuiltinModule("fs");r.promises.lstat(a).then(t=>{const e=getReadableStream(r.createReadStream(a));this._reader=e.getReader();const{size:i}=t;i<=2*s&&(this._isRangeSupported=!1),this._contentLength=i,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled.")),this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=createResponseError(0,a.href)),this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:node_stream_getArrayBuffer(t),done:!1})}cancel(t){this._reader?.cancel(t)}}class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const n=t.url,s=process.getBuiltinModule("fs");try{const t=getReadableStream(s.createReadStream(n,{start:e,end:i-1}));this._reader=t.getReader(),this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:node_stream_getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}const INITIAL_DATA=Symbol("INITIAL_DATA");class PDFObjects{#ys=Object.create(null);#ws(t){return this.#ys[t]||={...Promise.withResolvers(),data:INITIAL_DATA}}get(t,e=null){if(e){const i=this.#ws(t);return i.promise.then(()=>e(i.data)),null}const i=this.#ys[t];if(!i||i.data===INITIAL_DATA)throw new Error(`Requesting object that isn\'t resolved yet ${t}.`);return i.data}has(t){const e=this.#ys[t];return!!e&&e.data!==INITIAL_DATA}delete(t){const e=this.#ys[t];return!(!e||e.data===INITIAL_DATA)&&(delete this.#ys[t],!0)}resolve(t,e=null){const i=this.#ws(t);i.data=e,i.resolve()}clear(){for(const t in this.#ys){const{data:e}=this.#ys[t];e?.bitmap?.close()}this.#ys=Object.create(null)}*[Symbol.iterator](){for(const t in this.#ys){const{data:e}=this.#ys[t];e!==INITIAL_DATA&&(yield[t,e])}}}const MAX_TEXT_DIVS_TO_RENDER=1e5,DEFAULT_FONT_SIZE=30;class TextLayer{#vs=Promise.withResolvers();#kt=null;#Es=!1;#xs=!!globalThis.FontInspector?.enabled;#Ts=null;#Ss=null;#Cs=0;#_s=0;#Ps=null;#Ds=null;#Ms=0;#Is=0;#ks=Object.create(null);#Fs=[];#Rs=null;#Ls=[];#Bs=new WeakMap;#Os=null;static#Ns=new Map;static#Us=new Map;static#Hs=new WeakMap;static#Gs=null;static#zs=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Rs=t;else{if("object"!=typeof t)throw new Error(\'No "textContentSource" parameter specified.\');this.#Rs=new ReadableStream({start(e){e.enqueue(t),e.close()}})}this.#kt=this.#Ds=e,this.#Is=i.scale*OutputScale.pixelRatio,this.#Ms=i.rotation,this.#Ss={div:null,properties:null,ctx:null};const{pageWidth:n,pageHeight:s,pageX:a,pageY:r}=i.rawDims;this.#Os=[1,0,0,-1,-a,r+s],this.#_s=n,this.#Cs=s,TextLayer.#Vs(),e.style.setProperty("--min-font-size",TextLayer.#Gs),setLayerDimensions(e,i),this.#vs.promise.finally(()=>{TextLayer.#zs.delete(this),this.#Ss=null,this.#ks=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 t=()=>{this.#Ps.read().then(({value:e,done:i})=>{i?this.#vs.resolve():(this.#Ts??=e.lang,Object.assign(this.#ks,e.styles),this.#Ws(e.items),t())},this.#vs.reject)};return this.#Ps=this.#Rs.getReader(),TextLayer.#zs.add(this),t(),this.#vs.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,n=t.rotation;if(n!==this.#Ms&&(e?.(),this.#Ms=n,setLayerDimensions(this.#Ds,{rotation:n})),i!==this.#Is){e?.(),this.#Is=i;const t={div:null,properties:null,ctx:TextLayer.#js(this.#Ts)};for(const e of this.#Ls)t.properties=this.#Bs.get(e),t.div=e,this.#$s(t)}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ps?.cancel(t).catch(()=>{}),this.#Ps=null,this.#vs.reject(t)}get textDivs(){return this.#Ls}get textContentItemsStr(){return this.#Fs}#Ws(t){if(this.#Es)return;this.#Ss.ctx??=TextLayer.#js(this.#Ts);const e=this.#Ls,i=this.#Fs;for(const n of t){if(e.length>1e5)return warn("Ignoring additional textDivs for performance reasons."),void(this.#Es=!0);if(void 0!==n.str)i.push(n.str),this.#Ks(n);else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#kt;this.#kt=document.createElement("span"),this.#kt.classList.add("markedContent"),n.id&&this.#kt.setAttribute("id",`${n.id}`),"Artifact"===n.tag&&(this.#kt.ariaHidden=!0),t.append(this.#kt)}else"endMarkedContent"===n.type&&(this.#kt=this.#kt.parentNode)}}#Ks(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Ls.push(e);const n=Util.transform(this.#Os,t.transform);let s=Math.atan2(n[1],n[0]);const a=this.#ks[t.fontName];a.vertical&&(s+=Math.PI/2);let r=this.#xs&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(n[2],n[3]),l=o*TextLayer.#Xs(r,a,this.#Ts);let h,d;0===s?(h=n[4],d=n[5]-l):(h=n[4]+l*Math.sin(s),d=n[5]-l*Math.cos(s));const c=e.style;c.left=`${(100*h/this.#_s).toFixed(2)}%`,c.top=`${(100*d/this.#Cs).toFixed(2)}%`,c.setProperty("--font-height",`${o.toFixed(2)}px`),c.fontFamily=r,i.fontSize=o,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#xs&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName),0!==s&&(i.angle=s*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(u=!0)}if(u&&(i.canvasWidth=a.vertical?t.height:t.width),this.#Bs.set(e,i),this.#Ss.div=e,this.#Ss.properties=i,this.#$s(this.#Ss),i.hasText&&this.#kt.append(e),i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation"),this.#kt.append(t)}}#$s(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:a,fontSize:r}=i;TextLayer.#Ys(n,r*this.#Is,t);const{width:o}=n.measureText(e.textContent);o>0&&s.setProperty("--scale-x",a*this.#Is/o)}0!==i.angle&&s.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#zs.size>0)){this.#Ns.clear();for(const{canvas:t}of this.#Us.values())t.remove();this.#Us.clear()}}static#js(t=null){let e=this.#Us.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement",i.lang=t,document.body.append(i),e=i.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#Us.set(t,e),this.#Hs.set(e,{size:0,family:""})}return e}static#Ys(t,e,i){const n=this.#Hs.get(t);e===n.size&&i===n.family||(t.font=`${e}px ${i}`,n.size=e,n.family=i)}static#Vs(){if(null!==this.#Gs)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.#Gs=t.getBoundingClientRect().height,t.remove()}static#Xs(t,e,i){const n=this.#Ns.get(t);if(n)return n;const s=this.#js(i);s.canvas.width=s.canvas.height=30,this.#Ys(s,30,t);const a=s.measureText(""),r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;return r?l=r/(r+o):(util_FeatureTest.platform.isFirefox&&warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)),this.#Ns.set(t,l),l}}const RENDERING_CANCELLED_TIMEOUT=100;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new PDFDocumentLoadingTask,{docId:i}=e,n=t.url?getUrlProp(t.url):null,s=t.data?getDataProp(t.data):null,a=t.httpHeaders||null,r=!0===t.withCredentials,o=t.password??null,l=t.range instanceof PDFDataRangeTransport?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:65536;let d=t.worker instanceof PDFWorker?t.worker:null;const c=t.verbosity,u="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,p=getFactoryUrlProp(t.cMapUrl),g=!1!==t.cMapPacked,m=t.CMapReaderFactory||(isNodeJS?NodeCMapReaderFactory:DOMCMapReaderFactory),f=getFactoryUrlProp(t.iccUrl),b=getFactoryUrlProp(t.standardFontDataUrl),A=t.StandardFontDataFactory||(isNodeJS?NodeStandardFontDataFactory:DOMStandardFontDataFactory),y=getFactoryUrlProp(t.wasmUrl),w=t.WasmFactory||(isNodeJS?NodeWasmFactory:DOMWasmFactory),v=!0!==t.stopAtErrors,E=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,x=!1!==t.isEvalSupported,T="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!isNodeJS,S="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!isNodeJS&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,_="boolean"==typeof t.disableFontFace?t.disableFontFace:isNodeJS,P=!0===t.fontExtraProperties,D=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,I=!0===t.disableRange,k=!0===t.disableStream,F=!0===t.disableAutoFetch,R=!0===t.pdfBug,L=t.CanvasFactory||(isNodeJS?NodeCanvasFactory:DOMCanvasFactory),B=t.FilterFactory||(isNodeJS?NodeFilterFactory:DOMFilterFactory),O=!0===t.enableHWA,N=!1!==t.useWasm,U=l?l.length:t.length??NaN,H="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!isNodeJS&&!_,G="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:!!(m===DOMCMapReaderFactory&&A===DOMStandardFontDataFactory&&w===DOMWasmFactory&&p&&b&&y&&isValidFetchUrl(p,document.baseURI)&&isValidFetchUrl(b,document.baseURI)&&isValidFetchUrl(y,document.baseURI));setVerbosityLevel(c);const z={canvasFactory:new L({ownerDocument:M,enableHWA:O}),filterFactory:new B({docId:i,ownerDocument:M}),cMapReaderFactory:G?null:new m({baseUrl:p,isCompressed:g}),standardFontDataFactory:G?null:new A({baseUrl:b}),wasmFactory:G?null:new w({baseUrl:y})};d||(d=PDFWorker.create({verbosity:c,port:GlobalWorkerOptions.workerPort}),e._worker=d);const V={docId:i,apiVersion:"5.4.624",data:s,password:o,disableAutoFetch:F,rangeChunkSize:h,length:U,docBaseUrl:u,enableXfa:D,evaluatorOptions:{maxImageSize:E,disableFontFace:_,ignoreErrors:v,isEvalSupported:x,isOffscreenCanvasSupported:T,isImageDecoderSupported:S,canvasMaxAreaInBytes:C,fontExtraProperties:P,useSystemFonts:H,useWasm:N,useWorkerFetch:G,cMapUrl:p,iccUrl:f,standardFontDataUrl:b,wasmUrl:y}},W={ownerDocument:M,pdfBug:R,styleElement:null,enableHWA:O,loadingParams:{disableAutoFetch:F,enableXfa:D}};return 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",V,s?[s.buffer]:null);let o;if(l)o=new PDFDataTransportStream({pdfDataRangeTransport:l,disableRange:I,disableStream:k});else if(!s){if(!n)throw new Error("getDocument - no `url` parameter provided.");const t=isValidFetchUrl(n)?PDFFetchStream:isNodeJS?PDFNodeStream:PDFNetworkStream;o=new t({url:n,length:U,httpHeaders:a,withCredentials:r,rangeChunkSize:h,disableRange:I,disableStream:k})}return t.then(t=>{if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const n=new MessageHandler(i,t,d.port),s=new WorkerTransport(n,e,o,W,z);e._transport=s,n.send("Ready",null)})}).catch(e._capability.reject),e}class PDFDocumentLoadingTask{static#dn=0;_capability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#dn++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await(this._transport?.destroy())}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class PDFDataRangeTransport{#vs=Promise.withResolvers();#qs=[];#Js=[];#Qs=[];#Zs=[];constructor(t,e,i=!1,n=null){this.length=t,this.initialData=e,this.progressiveDone=i,this.contentDispositionFilename=n}addRangeListener(t){this.#Zs.push(t)}addProgressListener(t){this.#Qs.push(t)}addProgressiveReadListener(t){this.#Js.push(t)}addProgressiveDoneListener(t){this.#qs.push(t)}onDataRange(t,e){for(const i of this.#Zs)i(t,e)}onDataProgress(t,e){this.#vs.promise.then(()=>{for(const i of this.#Qs)i(t,e)})}onDataProgressiveRead(t){this.#vs.promise.then(()=>{for(const e of this.#Js)e(t)})}onDataProgressiveDone(){this.#vs.promise.then(()=>{for(const t of this.#qs)t()})}transportReady(){this.#vs.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#ta=!1;#ea=PagesMapper.instance;constructor(t,e,i,n=!1){this._pageIndex=t,this._pageInfo=e,this._transport=i,this._stats=n?new StatTimer:null,this._pdfBug=n,this.commonObjs=i.commonObjs,this.objs=new PDFObjects,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=AnnotationMode.ENABLE,transform:a=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:c=!1,recordOperations:u=!1,operationsFilter:p=null}){this._stats?.time("Overall");const g=this._transport.getRenderingIntent(n,s,d,c),{renderingIntent:m,cacheKey:f}=g;this.#ta=!1,o||=this._transport.getOptionalContentConfig(m);let b=this._intentStates.get(f);b||(b=Object.create(null),this._intentStates.set(f,b)),b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const A=!!(m&RenderingIntentFlag.PRINT);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(g));const y=Boolean(this._pdfBug&&globalThis.StepperManager?.enabled),w=!this.recordedBBoxes&&(u||y),v=t=>{if(b.renderTasks.delete(E),w){const t=E.gfx?.dependencyTracker.take();t&&(E.stepper&&E.stepper.setOperatorBBoxes(t,E.gfx.dependencyTracker.takeDebugMetadata()),u&&(this.recordedBBoxes=t))}A&&(this.#ta=!0),this.#ia(),t?(E.capability.reject(t),this._abortOperatorList({intentState:b,reason:t instanceof Error?t:new Error(t)})):E.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},E=new InternalRenderTask({callback:v,params:{canvas:e,canvasContext:t,dependencyTracker:w?new CanvasDependencyTracker(e,b.operatorList.length,y):null,viewport:i,transform:a,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!A,pdfBug:this._pdfBug,pageColors:h,enableHWA:this._transport.enableHWA,operationsFilter:p});(b.renderTasks||=new Set).add(E);const x=E.task;return Promise.all([b.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)v();else{if(this._stats?.time("Rendering"),!(e.renderingIntent&m))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");E.initializeGraphics({transparency:t,optionalContentConfig:e}),E.operatorListChanged()}}).catch(v),x}getOperatorList({intent:t="display",annotationMode:e=AnnotationMode.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0);let a,r=this._intentStates.get(s.cacheKey);return r||(r=Object.create(null),this._intentStates.set(s.cacheKey,r)),r.opListReadCapability||(a=Object.create(null),a.operatorListChanged=function(){r.operatorList.lastChunk&&(r.opListReadCapability.resolve(r.operatorList),r.renderTasks.delete(a))},r.opListReadCapability=Promise.withResolvers(),(r.renderTasks||=new Set).add(a),r.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(s)),r.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#ea.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>XfaText.textContent(t));const e=this.streamTextContent(t);return new Promise(function(t,i){const n=e.getReader(),s={items:[],styles:Object.create(null),lang:null};!function e(){n.read().then(function({value:i,done:n}){n?t(s):(s.lang??=i.lang,Object.assign(s.styles,i.styles),s.items.push(...i.items),e())},i)}()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const i of e.renderTasks)t.push(i.completed),i.cancel();return this.objs.clear(),this.#ta=!1,Promise.all(t)}cleanup(t=!1){this.#ta=!0;const e=this.#ia();return t&&e&&(this._stats&&=new StatTimer),e}#ia(){if(!this.#ta||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#ta=!1,!0}_startRenderPage(t,e){const i=this._intentStates.get(e);i&&(this._stats?.timeEnd("Page Request"),i.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++)e.operatorList.fnArray.push(t.fnArray[i]),e.operatorList.argsArray.push(t.argsArray[i]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#ia()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#ea.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const l=()=>{r.read().then(({value:t,done:e})=>{e?o.streamReader=null:this._transport.destroyed||(this._renderPageChunk(t,o),l())},t=>{if(o.streamReader=null,!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#ia()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};l()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;return e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),void(t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i))}}if(t.streamReader.cancel(new AbortException(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class PDFWorker{#vs=Promise.withResolvers();#na=null;#Jn=null;#sa=null;static#aa=0;static#ra=!1;static#oa=new WeakMap;static{isNodeJS&&(this.#ra=!0,GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin},this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))},this.fromPort=t=>{if(deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."),!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.create(t)}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=i,e){if(PDFWorker.#oa.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#oa.set(e,this),this.#la(e)}else this.#ha()}get promise(){return this.#vs.promise}#da(){this.#vs.resolve(),this.#na.send("configure",{verbosity:this.verbosity})}get port(){return this.#Jn}get messageHandler(){return this.#na}#la(t){this.#Jn=t,this.#na=new MessageHandler("main","worker",t),this.#na.on("ready",()=>{}),this.#da()}#ha(){if(PDFWorker.#ra||PDFWorker.#ca)return void this.#ua();let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),n=()=>{s.abort(),i.destroy(),e.terminate(),this.destroyed?this.#vs.reject(new Error("Worker was destroyed")):this.#ua()},s=new AbortController;e.addEventListener("error",()=>{this.#sa||n()},{signal:s.signal}),i.on("test",t=>{s.abort(),!this.destroyed&&t?(this.#na=i,this.#Jn=e,this.#sa=e,this.#da()):n()}),i.on("ready",t=>{if(s.abort(),this.destroyed)n();else try{a()}catch{this.#ua()}});const a=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};return void a()}catch{info("The worker has been disabled.")}this.#ua()}#ua(){PDFWorker.#ra||(warn("Setting up fake worker."),PDFWorker.#ra=!0),PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed)return void this.#vs.reject(new Error("Worker was destroyed"));const e=new LoopbackPort;this.#Jn=e;const i="fake"+PDFWorker.#aa++,n=new MessageHandler(i+"_worker",i,e);t.setup(n,e),this.#na=new MessageHandler(i,i+"_worker",e),this.#da()}).catch(t=>{this.#vs.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this.#sa?.terminate(),this.#sa=null,PDFWorker.#oa.delete(this.#Jn),this.#Jn=null,this.#na?.destroy(),this.#na=null}static create(t){const e=this.#oa.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error(\'No "GlobalWorkerOptions.workerSrc" specified.\')}static get#ca(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#ca)return this.#ca;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#pa=null;#ga=new Map;#ma=null;#fa=new Map;#ba=new Map;#Aa=new Map;#ya=null;#ea=PagesMapper.instance;constructor(t,e,i,n,s){this.messageHandler=t,this.loadingTask=e,this.#ma=i,this.commonObjs=new PDFObjects,this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement}),this.enableHWA=n.enableHWA,this.loadingParams=n.loadingParams,this._params=n,this.canvasFactory=s.canvasFactory,this.filterFactory=s.filterFactory,this.cMapReaderFactory=s.cMapReaderFactory,this.standardFontDataFactory=s.standardFontDataFactory,this.wasmFactory=s.wasmFactory,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler(),this.#ea.addListener(this.#wa.bind(this))}#wa(){const t=new Map,e=new Map;for(let i=0,n=this.#ea.pagesNumber;i<n;i++){const n=this.#ea.getPrevPageNumber(i+1)-1,s=this.#fa.get(n);s&&t.set(i,s);const a=this.#ba.get(n);a&&e.set(i,a)}this.#fa=t,this.#ba=e}#va(t,e=null){const i=this.#ga.get(t);if(i)return i;const n=this.messageHandler.sendWithPromise(t,e);return this.#ga.set(t,n),n}#ms({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:MathClamp(Math.round(t/e*100),0,100)})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=AnnotationMode.ENABLE,i=null,n=!1,s=!1){let a=RenderingIntentFlag.DISPLAY,r=SerializableEmpty;switch(t){case"any":a=RenderingIntentFlag.ANY;break;case"display":break;case"print":a=RenderingIntentFlag.PRINT;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const o=a&RenderingIntentFlag.PRINT&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case AnnotationMode.DISABLE:a+=RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case AnnotationMode.ENABLE:break;case AnnotationMode.ENABLE_FORMS:a+=RenderingIntentFlag.ANNOTATIONS_FORMS;break;case AnnotationMode.ENABLE_STORAGE:a+=RenderingIntentFlag.ANNOTATIONS_STORAGE,r=o.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(a+=RenderingIntentFlag.IS_EDITING),s&&(a+=RenderingIntentFlag.OPLIST);const{ids:l,hash:h}=o.modifiedIds;return{renderingIntent:a,cacheKey:[a,r.hash,h].join("_"),annotationStorageSerializable:r,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#ya?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#fa.values())t.push(e._destroy());this.#fa.clear(),this.#ba.clear(),this.#Aa.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#ga.clear(),this.filterFactory.destroy(),TextLayer.cleanup(),this.#ma?.cancelAllRequests(new AbortException("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this.#ma,"GetReader - no `BasePDFStream` instance available."),this.#pa=this.#ma.getFullReader(),this.#pa.onProgress=t=>this.#ms(t),e.onPull=()=>{this.#pa.read().then(function({value:t,done:i}){i?e.close():(assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{this.#pa.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}}),t.on("ReaderHeadersReady",async t=>{await this.#pa.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:n}=this.#pa;return e&&i&&(this.#pa.onProgress=null),{isStreamingSupported:e,isRangeSupported:i,contentLength:n}}),t.on("GetRangeReader",(t,e)=>{assert(this.#ma,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#ma.getRangeReader(t.begin,t.end);i?(e.onPull=()=>{i.read().then(function({value:t,done:i}){i?e.close():(assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),e.enqueue(new Uint8Array(t),1,[t]))}).catch(t=>{e.error(t)})},e.onCancel=t=>{i.cancel(t),e.ready.catch(t=>{if(!this.destroyed)throw t})}):e.close()}),t.on("GetDoc",({pdfInfo:t})=>{this.#ea.pagesNumber=t.numPages,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.#ya=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const i=t=>{t instanceof Error?this.#ya.reject(t):this.#ya.resolve({password:t})};e.onPassword(i,t.code)}catch(t){this.#ya.reject(t)}return this.#ya.promise}),t.on("DataLoaded",t=>{this.#ms({loaded:t.length,total:t.length}),this.downloadInfoCapability.resolve(t)}),t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#fa.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}),t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;warn(`Error during font loading: ${t}`),this.commonObjs.resolve(e,t);break}const s=new FontInfo(n),a=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,r=new FontFaceObject(s,a,n.extra,n.charProcOperatorList);this.fontLoader.bind(r).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{!r.fontExtraProperties&&r.data&&r.clearData(),this.commonObjs.resolve(e,r)});break;case"CopyLocalImage":const{imageRef:o}=n;assert(o,"The imageRef must be defined.");for(const t of this.#fa.values())for(const[,i]of t.objs)if(i?.ref===o)return i.dataLen?(this.commonObjs.resolve(e,structuredClone(i)),i.dataLen):null;break;case"FontPath":this.commonObjs.resolve(e,new FontPathInfo(n));break;case"Image":this.commonObjs.resolve(e,n);break;case"Pattern":const l=new PatternInfo(n);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#fa.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()}),t.on("DocProgress",t=>{this.destroyed||this.#ms(t)}),t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");const e=this[t.type];if(!e)throw new Error(`${t.type} not initialized, see the \\`useWorkerFetch\\` parameter.`);return e.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#pa?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){return this.messageHandler.sendWithPromise("ExtractPages",{pageInfos:t})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.#ea.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#ea.getPageId(t)-1,n=this.#ba.get(e);if(n)return n;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Aa.set(t.refStr,i);const n=new PDFPageProxy(e,t,this,this._params.pdfBug);return this.#fa.set(e,n),n});return this.#ba.set(e,s),s}async getPageIndex(t){if(!isRefProxy(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen});return this.#ea.getPageNumber(e+1)-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.#ea.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#va("GetFieldObjects")}hasJSActions(){return this.#va("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#va("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.#ea.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.#ea.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#va("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#ga.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this.#pa?.filename??null,contentLength:this.#pa?.contentLength??null,hasStructTree:t[2]}));return this.#ga.set(t,i),i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#fa.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear(),t||this.fontLoader.clear(),this.#ga.clear(),this.filterFactory.destroy(!0),TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#Aa.get(e);return i>=0?this.#ea.getPageNumber(i+1):null}}class RenderTask{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ea=null;static#xa=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:c=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t,this.params=e,this.objs=i,this.commonObjs=n,this.annotationCanvasMap=s,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=r,this.canvasFactory=o,this.filterFactory=l,this._pdfBug=d,this.pageColors=c,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new RenderTask(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvas,this._canvasContext=e.canvas?null:e.canvasContext,this._enableHWA=u,this._dependencyTracker=e.dependencyTracker,this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#xa.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.#xa.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:i,transform:n,background:s,dependencyTracker:a}=this.params,r=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,a),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#Ea&&(window.cancelAnimationFrame(this.#Ea),this.#Ea=null),InternalRenderTask.#xa.delete(this._canvas),t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e),this.callback(t),this.task.onError?.(t)}operatorListChanged(){this.graphicsReady?(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running||this._continue()):this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ea=window.requestAnimationFrame(()=>{this.#Ea=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),InternalRenderTask.#xa.delete(this._canvas),this.callback())))}}const version="5.4.624",build="384c6208b";class ColorPicker{#Ta=null;#Sa=null;#Ca;#_a=null;#Pa=!1;#Da=!1;#u=null;#Ma;#Ia=null;#T=null;static#ka=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}){t?(this.#Da=!1,this.#u=t):this.#Da=!0,this.#T=t?._uiManager||e,this.#Ma=this.#T._eventBus,this.#Ca=t?.color?.toUpperCase()||this.#T?.highlightColors.values().next().value||"#FFFF98",ColorPicker.#ka||=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.ariaHasPopup="true",this.#u&&(t.ariaControls=`${this.#u.id}_colorpicker_dropdown`);const e=this.#T._signal;t.addEventListener("click",this.#Fa.bind(this),{signal:e}),t.addEventListener("keydown",this.#Ra.bind(this),{signal:e});const i=this.#Sa=document.createElement("span");return i.className="swatch",i.ariaHidden="true",i.style.backgroundColor=this.#Ca,t.append(i),t}renderMainDropdown(){const t=this.#_a=this.#La();return t.ariaOrientation="horizontal",t.ariaLabelledBy="highlightColorPickerLabel",t}#La(){const t=document.createElement("div"),e=this.#T._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e}),t.className="dropdown",t.role="listbox",t.ariaMultiSelectable="false",t.ariaOrientation="vertical",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#u&&(t.id=`${this.#u.id}_colorpicker_dropdown`);for(const[i,n]of this.#T.highlightColors){const s=document.createElement("button");s.tabIndex="0",s.role="option",s.setAttribute("data-color",n),s.title=i,s.setAttribute("data-l10n-id",ColorPicker.#ka[i]);const a=document.createElement("span");s.append(a),a.className="swatch",a.style.backgroundColor=n,s.ariaSelected=n===this.#Ca,s.addEventListener("click",this.#Ba.bind(this,n),{signal:e}),t.append(s)}return t.addEventListener("keydown",this.#Ra.bind(this),{signal:e}),t}#Ba(t,e){e.stopPropagation(),this.#Ma.dispatch("switchannotationeditorparams",{source:this,type:AnnotationEditorParamsType.HIGHLIGHT_COLOR,value:t}),this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#Ta)return void this.#Fa(t);const e=t.target.getAttribute("data-color");e&&this.#Ba(e,t)}_moveToNext(t){this.#Oa?t.target!==this.#Ta?t.target.nextSibling?.focus():this.#_a.firstElementChild?.focus():this.#Fa(t)}_moveToPrevious(t){t.target!==this.#_a?.firstElementChild&&t.target!==this.#Ta?(this.#Oa||this.#Fa(t),t.target.previousSibling?.focus()):this.#Oa&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#Oa?this.#_a.firstElementChild?.focus():this.#Fa(t)}_moveToEnd(t){this.#Oa?this.#_a.lastElementChild?.focus():this.#Fa(t)}#Ra(t){ColorPicker._keyboardManager.exec(this,t)}#Fa(t){if(this.#Oa)return void this.hideDropdown();if(this.#Pa=0===t.detail,this.#Ia||(this.#Ia=new AbortController,window.addEventListener("pointerdown",this.#y.bind(this),{signal:this.#T.combinedSignal(this.#Ia)})),this.#Ta.ariaExpanded="true",this.#_a)return void this.#_a.classList.remove("hidden");const e=this.#_a=this.#La();this.#Ta.append(e)}#y(t){this.#_a?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#_a?.classList.add("hidden"),this.#Ta.ariaExpanded="false",this.#Ia?.abort(),this.#Ia=null}get#Oa(){return this.#_a&&!this.#_a.classList.contains("hidden")}_hideDropdownFromKeyboard(){this.#Da||(this.#Oa?(this.hideDropdown(),this.#Ta.focus({preventScroll:!0,focusVisible:this.#Pa})):this.#u?.unselect())}updateColor(t){if(this.#Sa&&(this.#Sa.style.backgroundColor=t),!this.#_a)return;const e=this.#T.highlightColors.values();for(const i of this.#_a.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#Ta?.remove(),this.#Ta=null,this.#Sa=null,this.#_a?.remove(),this.#_a=null}}class BasicColorPicker{#Na=null;#u=null;#T=null;static#ka=null;constructor(t){this.#u=t,this.#T=t._uiManager,BasicColorPicker.#ka||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#Na)return this.#Na;const{editorType:t,colorType:e,color:i}=this.#u,n=this.#Na=document.createElement("input");return n.type="color",n.value=i||"#000000",n.className="basicColorPicker",n.tabIndex=0,n.setAttribute("data-l10n-id",BasicColorPicker.#ka[t]),n.addEventListener("input",()=>{this.#T.updateParams(e,n.value)},{signal:this.#T._signal}),n}update(t){this.#Na&&(this.#Na.value=t)}destroy(){this.#Na?.remove(),this.#Na=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[scaleAndClamp(1-Math.min(1,t+n)),scaleAndClamp(1-Math.min(1,i+n)),scaleAndClamp(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,a=1-i;return["CMYK",n,s,a,Math.min(n,s,a)]}}const DateFormats=null,TimeFormats=null;class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");return n.setAttribute("version","1.1"),i||(n.setAttribute("width",`${t}px`),n.setAttribute("height",`${e}px`)),n.setAttribute("preserveAspectRatio","none"),n.setAttribute("viewBox",`0 0 ${t} ${e}`),n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(SVG_NS,t)}}const annotation_layer_DEFAULT_FONT_SIZE=9,GetElementsByNameSet=new WeakSet,TIMEZONE_OFFSET=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case AnnotationType.LINK:return new LinkAnnotationElement(t);case AnnotationType.TEXT:return new TextAnnotationElement(t);case AnnotationType.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case AnnotationType.POPUP:return new PopupAnnotationElement(t);case AnnotationType.FREETEXT:return new FreeTextAnnotationElement(t);case AnnotationType.LINE:return new LineAnnotationElement(t);case AnnotationType.SQUARE:return new SquareAnnotationElement(t);case AnnotationType.CIRCLE:return new CircleAnnotationElement(t);case AnnotationType.POLYLINE:return new PolylineAnnotationElement(t);case AnnotationType.CARET:return new CaretAnnotationElement(t);case AnnotationType.INK:return new InkAnnotationElement(t);case AnnotationType.POLYGON:return new PolygonAnnotationElement(t);case AnnotationType.HIGHLIGHT:return new HighlightAnnotationElement(t);case AnnotationType.UNDERLINE:return new UnderlineAnnotationElement(t);case AnnotationType.SQUIGGLY:return new SquigglyAnnotationElement(t);case AnnotationType.STRIKEOUT:return new StrikeOutAnnotationElement(t);case AnnotationType.STAMP:return new StampAnnotationElement(t);case AnnotationType.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Ua=null;#Ha=!1;#Ga=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableComment=t.enableComment,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,this.hasOwnCommentButton=!1,e&&(this.contentElement=this.container=this._createContainer(i)),n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,a=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)e[t+1]>a?(a=e[t+1],s=e[t+2]):e[t+1]===a&&(s=Math.max(s,e[t+2]));return[s,a]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)t[e+1]>a?(a=t[e+1],s=t[e]):t[e+1]===a&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,a]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:a}}}=this.parent;return t[1]=e[3]-t[1]+e[1],t[0]=100*(t[0]-s)/i,t[1]=100*(t[1]-a)/n,t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${AnnotationEditorPrefix}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date}),t||this.removePopup()}removePopup(){(this.#Ga?.popup||this.popup)?.remove(),this.#Ga=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#Ua||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#za(e);let n=this.#Ga?.popup||this.popup;!n&&i?.text&&(this._createPopup(i),n=this.#Ga.popup),n&&(n.updateEdited(t),i?.deleted&&(n.remove(),this.#Ga=null,this.popup=null))}resetEdited(){this.#Ua&&(this.#za(this.#Ua.rect),this.#Ga?.popup.resetEdited(),this.#Ua=null)}#za(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t),e.left=100*(t[0]-r)/s+"%",e.top=100*(a-t[3]+o)/a+"%",0===n?(e.width=100*(t[2]-t[0])/s+"%",e.height=100*(t[3]-t[1])/a+"%"):this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id),this instanceof WidgetAnnotationElement||this instanceof LinkAnnotationElement||(s.tabIndex=0);const{style:a}=s;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,e.alternativeText&&(s.title=e.alternativeText),e.noRotate&&s.classList.add("norotate"),!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;return e.hasOwnCanvas||0===t||this.setRotation(t,s),s}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;a.borderRadius=e}else if(this instanceof 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 AnnotationBorderStyleType.SOLID:a.borderStyle="solid";break;case AnnotationBorderStyleType.DASHED:a.borderStyle="dashed";break;case AnnotationBorderStyleType.BEVELED:warn("Unimplemented border style: beveled");break;case AnnotationBorderStyleType.INSET:warn("Unimplemented border style: inset");break;case AnnotationBorderStyleType.UNDERLINE:a.borderBottomStyle="solid"}const n=e.borderColor||null;n?(this.#Ha=!0,a.borderColor=Util.makeHexColor(0|n[0],0|n[1],0|n[2])):a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:d,pageX:c,pageY:u}=n.rawDims;a.left=100*(l[0]-c)/h+"%",a.top=100*(l[1]-u)/d+"%";const{rotation:p}=e;return e.hasOwnCanvas||0===p?(a.width=100*r/h+"%",a.height=100*o/d+"%"):this.setRotation(p,s),s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:a}=this;t%180!=0&&([s,a]=[a,s]),e.style.width=100*s/i+"%",e.style.height=100*a/n+"%",e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(t,e,i)=>{const n=i.detail[t],s=n[0],a=n.slice(1);i.target.style[e]=ColorConverters[`${s}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${s}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const a=i[n];if(a){a({detail:{[n]:s},target:t}),delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(n===a&&s===r&&e===o&&i===l)return}const{style:a}=this.container;let r;if(this.#Ha){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=n-e,l=s-i,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";const c=h.createElement("defs");d.append(c);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p),u.setAttribute("clipPathUnits","objectBoundingBox"),c.append(u);for(let i=2,n=t.length;i<n;i+=8){const n=t[i],a=t[i+1],d=t[i+2],c=t[i+3],p=h.createElement("rect"),g=(d-e)/o,m=(s-a)/l,f=(n-d)/o,b=(a-c)/l;p.setAttribute("x",g),p.setAttribute("y",m),p.setAttribute("width",f),p.setAttribute("height",b),u.append(p),r?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}this.#Ha&&(r.push("</g></svg>\')"),a.backgroundImage=r.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(t=null){const{data:e}=this;let i,n;t?(i={str:t.text},n=t.date):(i=e.contentsObj,n=e.modificationDate),this.#Ga=new PopupAnnotationElement({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#Ga||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#Ga}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:a}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${s}"]`);!r||GetElementsByNameSet.has(r)?i.push({id:s,exportValue:n,domElement:r}):warn(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(GetElementsByNameSet.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class EditorAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.editor=t.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t,t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;return t.url?(e.addLinkAttributes(i,t.url,t.newWindow),n=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),n=!0):t.attachment?(this.#Va(i,t.attachment,t.overlaidText,t.attachmentDest),n=!0):t.setOCGState?(this.#Wa(i,t.setOCGState,t.overlaidText),n=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),n=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),n=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(i,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&(this.contentElement=i,this.container.append(i)),this.container}#ja(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||""===e)&&this.#ja(),i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),i&&(t.title=i),this.#ja()}#Va(t,e,i="",n=null){t.href=this.linkService.getAnchorUrl(""),e.description?t.title=e.description:i&&(t.title=i),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,n),!1),this.#ja()}#Wa(t,e,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),i&&(t.title=i),this.#ja()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}}),!1))}e.overlaidText&&(t.title=e.overlaidText),t.onclick||(t.onclick=()=>!1),this.#ja()}_bindResetFormAction(t,e){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),this.#ja(),!this._fieldObjects)return warn(\'_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.\'),void(i||(t.onclick=()=>!1));t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,a=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;switch(o.push(e),t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(GetElementsByNameSet.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}}),!1}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(t),this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&("CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,a]of i)("Action"===a||this.data.actions?.[a])&&("Focus"!==a&&"Blur"!==a||(e||={focused:!1}),this._setEventListener(t,e,s,a,n),"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||9,s=t.style;let a;const r=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(1.35*n))||1);a=Math.min(n,r(e/1.35))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(n,r(t/1.35))}s.fontSize=`calc(${a}px * var(--total-scale-factor))`,s.color=Util.makeHexColor(i[0],i[1],i[2]),null!==this.data.textAlignment&&(s.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id))a.domElement&&(a.domElement[e]=i),s.setValue(a.id,{[n]:i})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&s.length>a&&(s=s.slice(0,a));let r=n.formattedValue||this.data.textContent?.join("\\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\\s+/g,""));const o={userValue:s,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(i=document.createElement("textarea"),i.textContent=r??s,this.data.doNotScroll&&(i.style.overflowY="hidden")):(i=document.createElement("input"),i.type=this.data.password?"password":"text",i.setAttribute("value",r??s),this.data.doNotScroll&&(i.style.overflowX="hidden")),this.data.hasOwnCanvas&&(i.hidden=!0),GetElementsByNameSet.add(i),this.contentElement=i,i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,i.name=this.data.fieldName,i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:d}=this.data,c=!!h&&this.enableScripting;l&&(i.title=l),this._setRequired(i,this.data.required),a&&(i.maxLength=a),i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value}),this.setPropertyOnSiblings(i,"value",n.target.value,"value"),o.formattedValue=null}),i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e,o.formattedValue=null});let u=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e),t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(c&&(e.type=h,d&&(e.step=d)),o.userValue){const t=o.userValue;if(c)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-TIMEZONE_OFFSET).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value,o.commitKey=1,this.data.actions?.Focus||(o.focused=!0)}),i.addEventListener("updatefromsandbox",i=>{this.showElementAndHideCanvas(i.target);const n={value(i){o.userValue=i.detail.value??"",c||t.setValue(e,{value:o.userValue.toString()}),i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n,null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};c&&(s.value=n),t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n)return void s.removeAttribute("maxLength");s.setAttribute("maxLength",n);let a=o.userValue;!a||a.length<=n||(a=a.slice(0,n),s.value=o.userValue=a,t.setValue(e,{value:a}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}}))}};this._dispatchEventFromSandbox(n,i)}),i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;if("Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2,-1===i)return;const{value:n}=t.target;o.lastCommittedValue!==n&&(o.lastCommittedValue=n,o.userValue=n,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}))});const n=u;u=null,i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(c){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf(),i.step=""}else s.includes("T")||(s=`${s}T00:00`),s=new Date(s).valueOf();i.type="text"}o.userValue=s,o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}}),n(t)}),this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:a,selectionEnd:r}=n;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,a).match(/\\w*[^\\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(a).match(/^[^\\w]*\\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}),this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}if(u&&i.addEventListener("blur",u),this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb"),i.style.letterSpacing=`calc(${t}px * var(--total-scale-factor) - 1ch)`}}else i=document.createElement("div"),i.textContent=this.data.fieldValue,i.style.verticalAlign="middle",i.style.display="table-cell",this.data.hasOwnCanvas&&(i.hidden=!0);return this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;"string"==typeof n&&(n="Off"!==n,t.setValue(i,{value:n})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");return GetElementsByNameSet.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="checkbox",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.setAttribute("exportValue",e.exportValue),s.tabIndex=0,s.addEventListener("change",n=>{const{name:s,checked:a}=n.target;for(const n of this._getElementsByName(s,i)){const i=a&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i),t.setValue(n.id,{value:i})}t.setValue(i,{value:a})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}),this.enableScripting&&this.hasJSActions&&(s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value,t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)}),this._setEventListeners(s,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(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n&&(n=n!==e.buttonValue,t.setValue(i,{value:n})),n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");if(GetElementsByNameSet.add(s),s.setAttribute("data-element-id",i),s.disabled=e.readOnly,this._setRequired(s,this.data.required),s.type="radio",s.name=e.fieldName,n&&s.setAttribute("checked",!0),s.tabIndex=0,s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})}),s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}),this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e),t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)}),this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}return this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),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;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})),t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");GetElementsByNameSet.add(n),n.setAttribute("data-element-id",e),n.disabled=this.data.readOnly,this._setRequired(n,this.data.required),n.name=this.data.fieldName,n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;this.data.combo||(n.size=this.data.options.length,this.data.multiSelect&&(n.multiple=!0)),n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.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,i.value.includes(t.exportValue)&&(e.setAttribute("selected",!0),s=!1),n.append(e)}let a=null;if(s){const t=document.createElement("option");t.value=" ",t.setAttribute("hidden",!0),t.setAttribute("selected",!0),n.prepend(t),a=()=>{t.remove(),n.removeEventListener("input",a),a=null},n.addEventListener("input",a)}const r=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let o=r(!1);const l=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.textContent,exportValue:t.value}))};return this.enableScripting&&this.hasJSActions?(n.addEventListener("updatefromsandbox",i=>{const s={value(i){a?.();const s=i.detail.value,l=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=l.has(t.value);t.setValue(e,{value:r(!0)}),o=r(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,a=i.detail.remove;if(s[a].selected=!1,n.remove(a),s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]}),o=r(!1)},insert(i){const{index:s,displayValue:a,exportValue:h}=i.detail.insert,d=n.children[s],c=document.createElement("option");c.textContent=a,c.value=h,d?d.before(c):n.append(c),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");s.textContent=e,s.value=i,n.append(s)}n.options.length>0&&(n.options[0].selected=!0),t.setValue(e,{value:r(!0),items:l(i)}),o=r(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:r(!0)}),o=r(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)}),n.addEventListener("input",i=>{const n=r(!0),s=r(!1);t.setValue(e,{value:n}),i.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:o,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(n,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)):n.addEventListener("input",function(i){t.setValue(e,{value:r(!0)})}),this.data.combo&&this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;if(super(t,{isRenderable:!s&&AnnotationElement._hasPopupData(e)}),this.elements=i,s&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#$a();for(const e of i)e.popup=t}else this.popup=null}#$a(){return new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const e=this.popup=this.#$a(),i=[];for(const t of this.elements)t.popup=e,t.container.ariaHasPopup="dialog",i.push(t.data.id),t.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(t=>`${AnnotationPrefix}${t}`).join(",")),this.container}}class PopupElement{#q=null;#Ka=this.#Ra.bind(this);#Xa=this.#Ya.bind(this);#qa=this.#Ja.bind(this);#Qa=this.#Za.bind(this);#tr=null;#kt=null;#er=null;#ir=null;#nr=null;#sr=null;#ar=null;#rr=!1;#or=null;#lr=null;#U=null;#hr=null;#dr=null;#Te=null;#cr=null;#we=null;#ur=null;#Ua=null;#pr=!1;#gr=null;#mr=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:d,commentManager:c=null}){this.#kt=t,this.#ur=n,this.#er=a,this.#we=r,this.#sr=o,this.#tr=e,this.#cr=l,this.#ar=h,this.#nr=i,this.#q=c,this.#gr=i[0],this.#ir=PDFDateString.toDateObject(s),this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup()),c||(this.#fr(),this.#kt.hidden=!0,d&&this.#Za())}#fr(){if(this.#lr)return;this.#lr=new AbortController;const{signal:t}=this.#lr;for(const e of this.trigger)e.addEventListener("click",this.#Qa,{signal:t}),e.addEventListener("pointerenter",this.#qa,{signal:t}),e.addEventListener("pointerleave",this.#Xa,{signal:t}),e.classList.add("popupTriggerArea");for(const e of this.#nr)e.container?.addEventListener("keydown",this.#Ka,{signal:t})}#br(){const t=this.#nr.find(t=>t.hasCommentButton);t&&(this.#dr=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#hr)return void(this.#hr.parentNode||this.#gr.container.after(this.#hr));if(this.#dr||this.#br(),!this.#dr)return;const{signal:t}=this.#lr=new AbortController,e=this.#gr.hasOwnCommentButton,i=()=>{this.#q.toggleCommentPopup(this,!0,void 0,!e)},n=()=>{this.#q.toggleCommentPopup(this,!1,!0,!e)},s=()=>{this.#q.toggleCommentPopup(this,!1,!1)};if(e){this.#hr=this.#gr.container;for(const e of this.trigger)e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.addEventListener("keydown",this.#Ka,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),e.classList.add("popupTriggerArea")}else{const e=this.#hr=document.createElement("button");e.className="annotationCommentButton";const a=this.#gr.container;e.style.zIndex=a.style.zIndex+1,e.tabIndex=0,e.ariaHasPopup="dialog",e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#Ar(),this.#yr(),e.addEventListener("keydown",this.#Ka,{signal:t}),e.addEventListener("click",i,{signal:t}),e.addEventListener("pointerenter",n,{signal:t}),e.addEventListener("pointerleave",s,{signal:t}),a.after(e)}}#yr(){if(this.#gr.extraPopupElement&&!this.#gr.editor)return;this.#hr||this.renderCommentButton();const[t,e]=this.#dr,{style:i}=this.#hr;i.left=`calc(${t}%)`,i.top=`calc(${e}% - var(--comment-button-dim))`}#Ar(){this.#gr.extraPopupElement||(this.#hr||this.renderCommentButton(),this.#hr.style.backgroundColor=this.commentButtonColor||"")}get commentButtonColor(){const{color:t,opacity:e}=this.#gr.commentData;return t?this.#sr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#hr?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#gr.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#hr}get comment(){return this.#mr||=this.#gr.commentText,this.#mr}set comment(t){t!==this.comment&&(this.#gr.commentText=this.#mr=t)}focus(){this.#gr.container?.focus()}get parentBoundingClientRect(){return this.#gr.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){this.#hr&&(this.#hr.classList.toggle("selected",t),this.#hr.ariaExpanded=e)}setSelectedCommentButton(t){this.#hr.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#Te)return this.#Te;const{x:t,y:e,height:i}=this.#hr.getBoundingClientRect(),{x:n,y:s,width:a,height:r}=this.#gr.layer.getBoundingClientRect();return[(t-n)/a,(e+i-s)/r]}set commentPopupPosition(t){this.#Te=t}hasDefaultPopupPosition(){return null===this.#Te}get commentButtonPosition(){return this.#dr}get commentButtonWidth(){return this.#hr.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#Te||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:a,width:r,height:o}=n;this.#q.showDialog(null,this,s+e*r,a+i*o,{...t,parentDimensions:n})}render(){if(this.#or)return;const t=this.#or=document.createElement("div");if(t.className="popup",this.#tr){const e=t.style.outlineColor=Util.makeHexColor(...this.#tr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");if(e.className="header",this.#ur?.str){const t=document.createElement("span");t.className="title",e.append(t),({dir:t.dir,str:t.textContent}=this.#ur)}if(t.append(e),this.#ir){const t=document.createElement("time");t.className="popupDate",t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#ir.valueOf()})),t.dateTime=this.#ir.toISOString(),e.append(t)}renderRichText({html:this.#wr||this.#er.str,dir:this.#er?.dir,className:"popupContent"},t),this.#kt.append(t)}get#wr(){const t=this.#we,e=this.#er;return!t?.str||e?.str&&e.str!==t.str?null:this.#we.html||null}get#vr(){return this.#wr?.attributes?.style?.fontSize||0}get#Er(){return this.#wr?.attributes?.style?.color||null}#xr(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#Er,fontSize:this.#vr?`calc(${this.#vr}px * var(--total-scale-factor))`:""}};for(const i of t.split("\\n"))e.push({name:"span",value:i,attributes:n});return i}#Ra(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#rr)&&this.#Za()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#q)return i?(this.remove(),this.#mr=null):e&&(e.deleted?this.remove():(this.#Ar(),this.#mr=e.text)),void(t&&(this.#dr=null,this.#br(),this.#yr()));i||e?.deleted?this.remove():(this.#fr(),this.#Ua||={contentsObj:this.#er,richText:this.#we},t&&(this.#U=null),e&&e.text&&(this.#we=this.#xr(e.text),this.#ir=PDFDateString.toDateObject(e.date),this.#er=null),this.#or?.remove(),this.#or=null)}resetEdited(){this.#Ua&&(({contentsObj:this.#er,richText:this.#we}=this.#Ua),this.#Ua=null,this.#or?.remove(),this.#or=null,this.#U=null)}remove(){if(this.#lr?.abort(),this.#lr=null,this.#or?.remove(),this.#or=null,this.#pr=!1,this.#rr=!1,this.#hr?.remove(),this.#hr=null,this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#Tr(){if(null!==this.#U)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#sr;let a=!!this.#ar,r=a?this.#ar:this.#cr;for(const t of this.#nr)if(!r||null!==Util.intersect(t.data.rect,r)){r=t.data.rect,a=!0;break}const o=Util.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),l=a?r[2]-r[0]+5:0,h=o[0]+l,d=o[1];this.#U=[100*(h-n)/e,100*(d-s)/i];const{style:c}=this.#kt;c.left=`${this.#U[0]}%`,c.top=`${this.#U[1]}%`}#Za(){this.#q?this.#q.toggleCommentPopup(this,!1):(this.#rr=!this.#rr,this.#rr?(this.#Ja(),this.#kt.addEventListener("click",this.#Qa),this.#kt.addEventListener("keydown",this.#Ka)):(this.#Ya(),this.#kt.removeEventListener("click",this.#Qa),this.#kt.removeEventListener("keydown",this.#Ka)))}#Ja(){this.#or||this.render(),this.isVisible?this.#rr&&this.#kt.classList.add("focused"):(this.#Tr(),this.#kt.hidden=!1,this.#kt.style.zIndex=parseInt(this.#kt.style.zIndex)+1e3)}#Ya(){this.#kt.classList.remove("focused"),!this.#rr&&this.isVisible&&(this.#kt.hidden=!0,this.#kt.style.zIndex=parseInt(this.#kt.style.zIndex)-1e3)}forceHide(){this.#pr=this.isVisible,this.#pr&&(this.#kt.hidden=!0)}maybeShow(){this.#q||(this.#fr(),this.#pr&&(this.#or||this.#Ja(),this.#pr=!1,this.#kt.hidden=!1))}get isVisible(){return!this.#q&&!1===this.#kt.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=AnnotationEditorType.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e,t.append(i)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class LineAnnotationElement extends AnnotationElement{#Sr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Sr=this.svgFactory.createElement("svg:line");return s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),s.setAttribute("stroke-width",t.borderStyle.width||1),s.setAttribute("stroke","transparent"),s.setAttribute("fill","transparent"),n.append(s),this.container.append(n),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#Sr}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Cr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#Cr=this.svgFactory.createElement("svg:rect");return a.setAttribute("x",s/2),a.setAttribute("y",s/2),a.setAttribute("width",e-s),a.setAttribute("height",i-s),a.setAttribute("stroke-width",s||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),n.append(a),this.container.append(n),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#Cr}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#_r=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#_r=this.svgFactory.createElement("svg:ellipse");return a.setAttribute("cx",e/2),a.setAttribute("cy",i/2),a.setAttribute("rx",e/2-s/2),a.setAttribute("ry",i/2-s/2),a.setAttribute("stroke-width",s||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),n.append(a),this.container.append(n),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#_r}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#Pr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(s,a,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#Pr=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",o),l.setAttribute("stroke-width",i.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),r.append(l),this.container.append(r),!n&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return this.#Pr}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}class InkAnnotationElement extends AnnotationElement{#Dr=null;#Mr=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType="InkHighlight"===this.data.it?AnnotationEditorType.HIGHLIGHT:AnnotationEditorType.INK}#Ir(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:a,width:r,height:o}=this.#Ir(e,t),l=this.svgFactory.create(r,o,!0),h=this.#Dr=this.svgFactory.createElement("svg:g");l.append(h),h.setAttribute("stroke-width",n.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Mr.push(e),e.setAttribute("points",i[t].join(",")),h.append(e)}return!s&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#Dr;if(e>=0&&s.setAttribute("stroke-width",e||1),i)for(let t=0,e=this.#Mr.length;t<e;t++)this.#Mr[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#Ir(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`),s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Mr}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=AnnotationEditorType.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),t){const e=document.createElement("mark");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),t){const e=document.createElement("u");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),t){const e=document.createElement("s");e.classList.add("overlaidText"),e.textContent=t,this.container.append(e)}return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=AnnotationEditorType.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#kr=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let i;e.hasAppearance||0===e.fillAlpha?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)),i.addEventListener("dblclick",this.#Fr.bind(this)),this.#kr=i;const{isMac:n}=util_FeatureTest.platform;return t.addEventListener("keydown",t=>{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#Fr()}),!e.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return this.#kr}addHighlightArea(){this.container.classList.add("highlightArea")}#Fr(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Rr=null;#Lr=null;#K=null;#Br=new Map;#Or=null;#Nr=null;#nr=[];#Ur=!1;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:a,structTreeLayer:r,commentManager:o,linkService:l,annotationStorage:h}){this.div=t,this.#Rr=e,this.#Lr=i,this.#Or=r||null,this.#Nr=l||null,this.#K=h||new AnnotationStorage,this.page=s,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=n,this._commentManager=o||null}hasEditableAnnotations(){return this.#Br.size>0}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const n=new Map,s=[],a={data:null,layer:i,linkService:this.#Nr,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#K,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===AnnotationType.POPUP;if(e){const e=n.get(t.id);if(!e)continue;if(!this._commentManager){s.push(t);continue}a.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;a.data=t;const i=AnnotationElementFactory.create(a);if(!i.isRenderable)continue;if(!e&&(this.#nr.push(i),t.popupRef)){const e=n.get(t.popupRef);e?e.push(i):n.set(t.popupRef,[i])}const r=i.render();t.hidden&&(r.style.visibility="hidden"),i._isEditable&&(this.#Br.set(i.data.id,i),this._annotationEditorUIManager?.renderAnnotationElement(i))}await this.#Hr();for(const t of s){const e=a.elements=n.get(t.id);a.data=t;const i=AnnotationElementFactory.create(a);if(!i.isRenderable)continue;const s=i.render();i.contentElement.id=`${AnnotationPrefix}${t.id}`,t.hidden&&(s.style.visibility="hidden"),e.at(-1).container.after(s)}this.#Gr()}async#Hr(){if(0===this.#nr.length)return;this.div.replaceChildren();const t=[];if(!this.#Ur){this.#Ur=!0;for(const{contentElement:e,data:{id:i}}of this.#nr){const n=e.id=`${AnnotationPrefix}${i}`;t.push(this.#Or?.getAriaAttributes(n).then(t=>{if(t)for(const[i,n]of t)e.setAttribute(i,n)}))}}this.#nr.sort(({data:{rect:[t,e,i,n]}},{data:{rect:[s,a,r,o]}})=>{if(t===i&&e===n)return 1;if(s===r&&a===o)return-1;const l=(e+n)/2,h=(a+o)/2;if(l>=o&&h<=e)return-1;if(h>=n&&l<=a)return 1;return(t+i)/2-(s+r)/2});const e=document.createDocumentFragment();for(const t of this.#nr)e.append(t.container),this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render());if(this.div.append(e),await Promise.all(t),this.#Rr)for(const t of this.#nr)this.#Rr.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#Nr,svgFactory:new DOMSVGFactory,parent:this};for(const i of t){i.borderStyle||=AnnotationLayer._defaultBorderStyle,e.data=i;const t=AnnotationElementFactory.create(e);t.isRenderable&&(t.render(),t.contentElement.id=`${AnnotationPrefix}${i.id}`,this.#nr.push(t))}await this.#Hr()}update({viewport:t}){const e=this.div;this.viewport=t,setLayerDimensions(e,{rotation:t.rotation}),this.#Gr(),e.hidden=!1}#Gr(){if(!this.#Lr)return;const t=this.div;for(const[e,i]of this.#Lr){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;i.className="annotationContent";const{firstChild:s}=n;s?"CANVAS"===s.nodeName?s.replaceWith(i):s.classList.contains("annotationContent")?s.after(i):s.before(i):n.append(i);const a=this.#Br.get(e);a&&(a._hasNoCanvas?(this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i),a._hasNoCanvas=!1):a.canvas=i)}this.#Lr.clear()}getEditableAnnotations(){return Array.from(this.#Br.values())}getEditableAnnotation(t){return this.#Br.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#Nr,annotationStorage:this.#K});return s.render(),s.contentElement.id=`${AnnotationPrefix}${i}`,s.createOrUpdatePopup(),this.#nr.push(s),s}removeAnnotation(t){const e=this.#nr.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#nr.splice(e,1);this.#Rr?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#Hr()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:AnnotationBorderStyleType.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const EOL_PATTERN=/\\r\\n?|\\n/g;class FreeTextEditor extends AnnotationEditor{#zr="";#Vr=`${this.id}-editor`;#Wr=null;#vr;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,e=t=>t.isEmpty(),i=AnnotationEditorUIManager.TRANSLATE_SMALL,n=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,n],checker:e}]]))}static _type="freetext";static _editorType=AnnotationEditorType.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor,this.#vr=t.fontSize||FreeTextEditor._defaultFontSize,this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"),this.canAddComment=!1}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case AnnotationEditorParamsType.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case AnnotationEditorParamsType.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case AnnotationEditorParamsType.FREETEXT_SIZE:this.#jr(e);break;case AnnotationEditorParamsType.FREETEXT_COLOR:this.#Ar(e)}}static get defaultPropertiesToUpdate(){return[[AnnotationEditorParamsType.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[AnnotationEditorParamsType.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[AnnotationEditorParamsType.FREETEXT_SIZE,this.#vr],[AnnotationEditorParamsType.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new BasicColorPicker(this),[["colorPicker",this._colorPicker]]}get colorType(){return AnnotationEditorParamsType.FREETEXT_COLOR}#jr(t){const e=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`,this.translate(0,-(t-this.#vr)*this.parentScale),this.#vr=t,this.#$r()},i=this.#vr;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#Ar(t){const e=t=>{this.color=t,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#vr)*t]}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#Wr=new AbortController;const t=this._uiManager.combinedSignal(this.#Wr);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){return!!super.disableEditMode()&&(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#Vr),this._isDraggable=!0,this.#Wr?.abort(),this.#Wr=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0)}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#Kr(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&"BR"===i.nodeName||(t.push(FreeTextEditor.#Xr(i)),e=i);return t.join("\\n")}#$r(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden"),e.style.display="hidden",t.div.append(this.div),i=e.getBoundingClientRect(),e.remove(),e.style.display=n,e.classList.toggle("hidden",s)}this.rotation%180==this.parentRotation%180?(this.width=i.width/t,this.height=i.height/e):(this.width=i.height/t,this.height=i.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#zr,e=this.#zr=this.#Kr().trimEnd();if(t===e)return;const i=t=>{this.#zr=t,t?(this.#Yr(),this._uiManager.rebuild(this),this.#$r()):this.remove()};this.addCommands({cmd:()=>{i(e)},undo:()=>{i(t)},mustExec:!1}),this.#$r()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&"Enter"===t.key&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;(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.#Vr),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${this.#vr}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,d]=this.pageTranslation;let c,u;switch(this.rotation){case 0:c=t+(s[0]-h)/o,u=e+this.height-(s[1]-d)/l;break;case 90:c=t+(s[0]-h)/o,u=e-(s[1]-d)/l,[a,r]=[r,-a];break;case 180:c=t-this.width+(s[0]-h)/o,u=e-(s[1]-d)/l,[a,r]=[-a,-r];break;case 270:c=t+(s[0]-h-this.height*l)/o,u=e+(s[1]-d-this.width*o)/l,[a,r]=[-r,a]}this.setAt(c*i,u*n,a,r)}else this._moveAfterPaste(t,e);this.#Yr(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#Xr(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(EOL_PATTERN,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=FreeTextEditor.#qr(e.getData("text")||"").replaceAll(EOL_PATTERN,"\\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize(),s.deleteFromDocument();const a=s.getRangeAt(0);if(!n.includes("\\n"))return a.insertNode(document.createTextNode(n)),this.editorDiv.normalize(),void s.collapseToStart();const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;if(h.push(r.nodeValue.slice(o).replaceAll(EOL_PATTERN,"")),t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Xr(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(EOL_PATTERN,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes)e++===o&&(t=h),t.push(FreeTextEditor.#Xr(i))}this.#zr=`${l.join("\\n")}${n}${h.join("\\n")}`,this.#Yr();const d=new Range;let c=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(c<=e){d.setStart(t,c),d.setEnd(t,c);break}c-=e}s.removeAllRanges(),s.addRange(d)}#Yr(){if(this.editorDiv.replaceChildren(),this.#zr)for(const t of this.#zr.split("\\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#Jr(){return this.#zr.replaceAll(" "," ")}static#qr(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=FreeTextEditor._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:a,id:r,popupRef:o,richText:l,contentsObj:h,creationDate:d,modificationDate:c},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u||0===u.length)return null;n=t={annotationType:AnnotationEditorType.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\\n"),position:p,pageIndex:g-1,rect:s.slice(0),rotation:a,annotationElementId:r,id:r,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:d,modificationDate:c}}const s=await super.deserialize(t,e,i);return s.#vr=t.fontSize,s.color=Util.makeHexColor(...t.color),s.#zr=FreeTextEditor.#qr(t.value),s._initialData=n,t.comment&&s.setCommentData(t),s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#vr,value:this.#Jr()});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!this.#Qr(i)?null:(i.id=this.annotationElementId,i)}#Qr(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#vr}px * var(--total-scale-factor))`,i.color=this.color,e.replaceChildren();for(const t of this.#zr.split("\\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br")),e.append(i)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#zr}}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r]*n,a[r+1]=i+t[r+1]*s;return a}static _rescaleAndSwap(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2)a[r]=e+t[r+1]*n,a[r+1]=i+t[r]*s;return a}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s+=2)n[s]=e+t[s],n[s+1]=i+t[s+1];return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static _normalizePagePoint(t,e,i){switch(i){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,i,n,s,a){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+a)/6,(i+s)/2,(n+a)/2]}}class FreeDrawOutliner{#Zr;#to=[];#eo;#io;#no=[];#so=new Float32Array(18);#ao;#ro;#oo;#lo;#ho;#do;#co=[];static#uo=8;static#po=2;static#go=FreeDrawOutliner.#uo+FreeDrawOutliner.#po;constructor({x:t,y:e},i,n,s,a,r=0){this.#Zr=i,this.#do=s*n,this.#io=a,this.#so.set([NaN,NaN,NaN,NaN,t,e],6),this.#eo=r,this.#lo=FreeDrawOutliner.#uo*n,this.#oo=FreeDrawOutliner.#go*n,this.#ho=n,this.#co.push(t,e)}isEmpty(){return isNaN(this.#so[8])}#mo(){const t=this.#so.subarray(4,6),e=this.#so.subarray(16,18),[i,n,s,a]=this.#Zr;return[(this.#ao+(t[0]-e[0])/2-i)/s,(this.#ro+(t[1]-e[1])/2-n)/a,(this.#ao+(e[0]-t[0])/2-i)/s,(this.#ro+(e[1]-t[1])/2-n)/a]}add({x:t,y:e}){this.#ao=t,this.#ro=e;const[i,n,s,a]=this.#Zr;let[r,o,l,h]=this.#so.subarray(8,12);const d=t-l,c=e-h,u=Math.hypot(d,c);if(u<this.#oo)return!1;const p=u-this.#lo,g=p/u,m=g*d,f=g*c;let b=r,A=o;r=l,o=h,l+=m,h+=f,this.#co?.push(t,e);const y=m/p,w=-f/p*this.#do,v=y*this.#do;if(this.#so.set(this.#so.subarray(2,8),0),this.#so.set([l+w,h+v],4),this.#so.set(this.#so.subarray(14,18),12),this.#so.set([l-w,h-v],16),isNaN(this.#so[6]))return 0===this.#no.length&&(this.#so.set([r+w,o+v],2),this.#no.push(NaN,NaN,NaN,NaN,(r+w-i)/s,(o+v-n)/a),this.#so.set([r-w,o-v],14),this.#to.push(NaN,NaN,NaN,NaN,(r-w-i)/s,(o-v-n)/a)),this.#so.set([b,A,r,o,l,h],6),!this.isEmpty();this.#so.set([b,A,r,o,l,h],6);return Math.abs(Math.atan2(A-o,b-r)-Math.atan2(f,m))<Math.PI/2?([r,o,l,h]=this.#so.subarray(2,6),this.#no.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/s,((o+h)/2-n)/a),[r,o,b,A]=this.#so.subarray(14,18),this.#to.push(NaN,NaN,NaN,NaN,((b+r)/2-i)/s,((A+o)/2-n)/a),!0):([b,A,r,o,l,h]=this.#so.subarray(0,6),this.#no.push(((b+5*r)/6-i)/s,((A+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a),[l,h,r,o,b,A]=this.#so.subarray(12,18),this.#to.push(((b+5*r)/6-i)/s,((A+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a),!0)}toSVGPath(){if(this.isEmpty())return"";const t=this.#no,e=this.#to;if(isNaN(this.#so[6])&&!this.isEmpty())return this.#fo();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#bo(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);return this.#Ao(i),i.join(" ")}#fo(){const[t,e,i,n]=this.#Zr,[s,a,r,o]=this.#mo();return`M${(this.#so[2]-t)/i} ${(this.#so[3]-e)/n} L${(this.#so[4]-t)/i} ${(this.#so[5]-e)/n} L${s} ${a} L${r} ${o} L${(this.#so[16]-t)/i} ${(this.#so[17]-e)/n} L${(this.#so[14]-t)/i} ${(this.#so[15]-e)/n} Z`}#Ao(t){const e=this.#to;t.push(`L${e[4]} ${e[5]} Z`)}#bo(t){const[e,i,n,s]=this.#Zr,a=this.#so.subarray(4,6),r=this.#so.subarray(16,18),[o,l,h,d]=this.#mo();t.push(`L${(a[0]-e)/n} ${(a[1]-i)/s} L${o} ${l} L${h} ${d} L${(r[0]-e)/n} ${(r[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,a){return new FreeDrawOutline(t,e,i,n,s,a)}getOutlines(){const t=this.#no,e=this.#to,i=this.#so,[n,s,a,r]=this.#Zr,o=new Float32Array((this.#co?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2)o[t]=(this.#co[t]-n)/a,o[t+1]=(this.#co[t+1]-s)/r;if(o[o.length-2]=(this.#ao-n)/a,o[o.length-1]=(this.#ro-s)/r,isNaN(i[6])&&!this.isEmpty())return this.#yo(o);const l=new Float32Array(this.#no.length+24+this.#to.length);let h=t.length;for(let e=0;e<h;e+=2)isNaN(t[e])?l[e]=l[e+1]=NaN:(l[e]=t[e],l[e+1]=t[e+1]);h=this.#wo(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)isNaN(e[t+i])?(l[h]=l[h+1]=NaN,h+=2):(l[h]=e[t+i],l[h+1]=e[t+i+1],h+=2);return this.#vo(l,h),this.newFreeDrawOutline(l,o,this.#Zr,this.#ho,this.#eo,this.#io)}#yo(t){const e=this.#so,[i,n,s,a]=this.#Zr,[r,o,l,h]=this.#mo(),d=new Float32Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/a,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/a,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/a],0),this.newFreeDrawOutline(d,t,this.#Zr,this.#ho,this.#eo,this.#io)}#vo(t,e){const i=this.#to;return t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e),e+6}#wo(t,e){const i=this.#so.subarray(4,6),n=this.#so.subarray(16,18),[s,a,r,o]=this.#Zr,[l,h,d,c]=this.#mo();return t.set([NaN,NaN,NaN,NaN,(i[0]-s)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,d,c,NaN,NaN,NaN,NaN,(n[0]-s)/r,(n[1]-a)/o],e),e+24}}class FreeDrawOutline extends Outline{#Zr;#Eo=new Float32Array(4);#eo;#io;#co;#ho;#xo;constructor(t,e,i,n,s,a){super(),this.#xo=t,this.#co=e,this.#Zr=i,this.#ho=n,this.#eo=s,this.#io=a,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#To(a);const[r,o,l,h]=this.#Eo;for(let e=0,i=t.length;e<i;e+=2)t[e]=(t[e]-r)/l,t[e+1]=(t[e+1]-o)/h;for(let t=0,i=e.length;t<i;t+=2)e[t]=(e[t]-r)/l,e[t+1]=(e[t+1]-o)/h}toSVGPath(){const t=[`M${this.#xo[4]} ${this.#xo[5]}`];for(let e=6,i=this.#xo.length;e<i;e+=6)isNaN(this.#xo[e])?t.push(`L${this.#xo[e+4]} ${this.#xo[e+5]}`):t.push(`C${this.#xo[e]} ${this.#xo[e+1]} ${this.#xo[e+2]} ${this.#xo[e+3]} ${this.#xo[e+4]} ${this.#xo[e+5]}`);return t.push("Z"),t.join(" ")}serialize([t,e,i,n],s){const a=i-t,r=n-e;let o,l;switch(s){case 0:o=Outline._rescale(this.#xo,t,n,a,-r),l=Outline._rescale(this.#co,t,n,a,-r);break;case 90:o=Outline._rescaleAndSwap(this.#xo,t,e,a,r),l=Outline._rescaleAndSwap(this.#co,t,e,a,r);break;case 180:o=Outline._rescale(this.#xo,i,e,-a,r),l=Outline._rescale(this.#co,i,e,-a,r);break;case 270:o=Outline._rescaleAndSwap(this.#xo,i,n,-a,-r),l=Outline._rescaleAndSwap(this.#co,i,n,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#To(t){const e=this.#xo;let i=e[4],n=e[5];const s=[i,n,i,n];let a=i,r=n,o=i,l=n;const h=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,c=e.length;t<c;t+=6){const c=e[t+4],u=e[t+5];isNaN(e[t])?(Util.pointBoundingBox(c,u,s),r>u?(a=c,r=u):r===u&&(a=h(a,c)),l<u?(o=c,l=u):l===u&&(o=h(o,c))):(d[0]=d[1]=1/0,d[2]=d[3]=-1/0,Util.bezierBoundingBox(i,n,...e.slice(t,t+6),d),Util.rectBoundingBox(d[0],d[1],d[2],d[3],s),r>d[1]?(a=d[0],r=d[1]):r===d[1]&&(a=h(a,d[0])),l<d[3]?(o=d[2],l=d[3]):l===d[3]&&(o=h(o,d[2]))),i=c,n=u}const c=this.#Eo;c[0]=s[0]-this.#eo,c[1]=s[1]-this.#eo,c[2]=s[2]-s[0]+2*this.#eo,c[3]=s[3]-s[1]+2*this.#eo,this.firstPoint=[a,r],this.lastPoint=[o,l]}get box(){return this.#Eo}newOutliner(t,e,i,n,s,a=0){return new FreeDrawOutliner(t,e,i,n,s,a)}getNewOutline(t,e){const[i,n,s,a]=this.#Eo,[r,o,l,h]=this.#Zr,d=s*l,c=a*h,u=i*l+r,p=n*h+o,g=this.newOutliner({x:this.#co[0]*d+u,y:this.#co[1]*c+p},this.#Zr,this.#ho,t,this.#io,e??this.#eo);for(let t=2;t<this.#co.length;t+=2)g.add({x:this.#co[t]*d+u,y:this.#co[t+1]*c+p});return g.getOutlines()}}class HighlightOutliner{#Zr;#So;#Co;#_o=[];#Po=[];constructor(t,e=0,i=0,n=!0){const s=[1/0,1/0,-1/0,-1/0],a=1e-4;for(const{x:i,y:n,width:r,height:o}of t){const t=Math.floor((i-e)/a)*a,l=Math.ceil((i+r+e)/a)*a,h=Math.floor((n-e)/a)*a,d=Math.ceil((n+o+e)/a)*a,c=[t,h,d,!0],u=[l,h,d,!1];this.#_o.push(c,u),Util.rectBoundingBox(t,h,l,d,s)}const r=s[2]-s[0]+2*i,o=s[3]-s[1]+2*i,l=s[0]-i,h=s[1]-i;let d=n?-1/0:1/0,c=1/0;const u=this.#_o.at(n?-1:-2),p=[u[0],u[2]];for(const t of this.#_o){const[e,i,s,a]=t;!a&&n?i<c?(c=i,d=e):i===c&&(d=Math.max(d,e)):a&&!n&&(i<c?(c=i,d=e):i===c&&(d=Math.min(d,e))),t[0]=(e-l)/r,t[1]=(i-h)/o,t[2]=(s-h)/o}this.#Zr=new Float32Array([l,h,r,o]),this.#So=[d,c],this.#Co=p}getOutlines(){this.#_o.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#_o)e[3]?(t.push(...this.#Do(e)),this.#Mo(e)):(this.#Io(e),t.push(...this.#Do(e)));return this.#ko(t)}#ko(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s),s.push(n),i.add(n),i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,d=a;for(s=[e,r],n.push(s);;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t),[e,a,r,o,l]=t,h!==e&&(s.push(h,d,e,d===a?a:r),h=e),d=d===a?r:a}s.push(h,d)}return new HighlightOutline(n,this.#Zr,this.#So,this.#Co)}#Fo(t){const e=this.#Po;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,a=e[s][0];if(a===t)return s;a<t?i=s+1:n=s-1}return n+1}#Mo([,t,e]){const i=this.#Fo(t);this.#Po.splice(i,0,[t,e])}#Io([,t,e]){const i=this.#Fo(t);for(let n=i;n<this.#Po.length;n++){const[i,s]=this.#Po[n];if(i!==t)break;if(i===t&&s===e)return void this.#Po.splice(n,1)}for(let n=i-1;n>=0;n--){const[i,s]=this.#Po[n];if(i!==t)break;if(i===t&&s===e)return void this.#Po.splice(n,1)}}#Do(t){const[e,i,n]=t,s=[[e,i,n]],a=this.#Fo(n);for(let t=0;t<a;t++){const[i,n]=this.#Po[t];for(let t=0,a=s.length;t<a;t++){const[,r,o]=s[t];if(!(n<=r||o<=i))if(r>=i)if(o>n)s[t][1]=n;else{if(1===a)return[];s.splice(t,1),t--,a--}else s[t][2]=i,o>n&&s.push([e,n,o])}}return s}}class HighlightOutline extends Outline{#Zr;#Ro;constructor(t,e,i,n){super(),this.#Ro=t,this.#Zr=e,this.firstPoint=i,this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#Ro){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const a=e[s],r=e[s+1];a===i?(t.push(`V${r}`),n=r):r===n&&(t.push(`H${a}`),i=a)}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const a=[],r=i-t,o=n-e;for(const e of this.#Ro){const i=new Array(e.length);for(let s=0;s<e.length;s+=2)i[s]=t+e[s]*r,i[s+1]=n-e[s+1]*o;a.push(i)}return a}get box(){return this.#Zr}get classNamesForOutlining(){return["highlightOutline"]}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,i,n,s,a){return new FreeHighlightOutline(t,e,i,n,s,a)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,i,n,s,a=0){return new FreeHighlightOutliner(t,e,i,n,s,a)}}class HighlightEditor extends AnnotationEditor{#Lo=null;#Bo=0;#Oo;#No=null;#c=null;#Uo=null;#Ho=null;#Go=0;#zo=null;#Vo=null;#k=null;#Wo=!1;#So=null;#Co=null;#jo=null;#ve="";#do;#$o="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=AnnotationEditorType.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.#do=t.thickness||HighlightEditor._defaultThickness,this.opacity=t.opacity||HighlightEditor._defaultOpacity,this.#Oo=t.boxes||null,this.#$o=t.methodOfCreation||"",this.#ve=t.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(this.#Wo=!0,this.#Ko(t),this.#Xo()):this.#Oo&&(this.#Lo=t.anchorNode,this.#Bo=t.anchorOffset,this.#Ho=t.focusNode,this.#Go=t.focusOffset,this.#Yo(),this.#Xo(),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}get telemetryInitialData(){return{action:"added",type:this.#Wo?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#do,methodOfCreation:this.#$o}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#Yo(){const t=new HighlightOutliner(this.#Oo,.001);this.#Vo=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#Vo.box;const e=new HighlightOutliner(this.#Oo,.0025,.001,"ltr"===this._uiManager.direction);this.#Uo=e.getOutlines();const{firstPoint:i}=this.#Vo;this.#So=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#Uo;this.#Co=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#Ko({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#Vo=t;if(this.#Uo=t.getNewOutline(this.#do/2+1.5,.0025),e>=0)this.#k=e,this.#No=i,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#jo=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#Uo.box,path:{d:this.#Uo.toSVGPath()}},!0);else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#k,{bbox:HighlightEditor.#qo(this.#Vo.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#jo,{bbox:HighlightEditor.#qo(this.#Uo.box,e),path:{d:this.#Uo.toSVGPath()}})}const[n,s,a,r]=t.box;switch(this.rotation){case 0:this.x=n,this.y=s,this.width=a,this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=s,this.y=1-n,this.width=a*e/t,this.height=r*t/e;break}case 180:this.x=1-n,this.y=1-s,this.width=a,this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s,this.y=n,this.width=a*e/t,this.height=r*t/e;break}}const{firstPoint:o}=t;this.#So=[(o[0]-n)/a,(o[1]-s)/r];const{lastPoint:l}=this.#Uo;this.#Co=[(l[0]-n)/a,(l[1]-s)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e),HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case AnnotationEditorParamsType.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Co}get commentButtonPosition(){return this.#So}updateParams(t,e){switch(t){case AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#Ar(e);break;case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#Jo(e)}}static get defaultPropertiesToUpdate(){return[[AnnotationEditorParamsType.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#do||HighlightEditor._defaultThickness],[AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#Wo]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#k,{root:{fill:this.color,"fill-opacity":this.opacity}}),this.#c?.updateColor(this.color),super.onUpdatedColor()}#Ar(t){const e=(t,e)=>{this.color=t,this.opacity=e,this.onUpdatedColor()},i=this.color,n=this.opacity;this.addCommands({cmd:e.bind(this,t,HighlightEditor._defaultOpacity),undo:e.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Jo(t){const e=this.#do,i=t=>{this.#do=t,this.#Qo(t)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#c=new ColorPicker({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Zo())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Zo())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#tl(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Xo(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#tl():t&&(this.#Xo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#Qo(t){this.#Wo&&(this.#Ko({highlightOutlines:this.#Vo.getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())}#tl(){null!==this.#k&&this.parent&&(this.parent.drawLayer.remove(this.#k),this.#k=null,this.parent.drawLayer.remove(this.#jo),this.#jo=null)}#Xo(t=this.parent){null===this.#k&&(({id:this.#k,clipPathId:this.#No}=t.drawLayer.draw({bbox:this.#Vo.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#Wo},path:{d:this.#Vo.toSVGPath()}},!1,!0)),this.#jo=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Wo},bbox:this.#Uo.box,path:{d:this.#Uo.toSVGPath()}},this.#Wo),this.#zo&&(this.#zo.style.clipPath=this.#No))}static#qo([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;this.#Wo?(t=(t-this.rotation+360)%360,i=HighlightEditor.#qo(this.#Vo.box,t)):i=HighlightEditor.#qo([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#k,{bbox:i,root:{"data-main-rotation":t}}),e.updateProperties(this.#jo,{bbox:HighlightEditor.#qo(this.#Uo.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#ve&&(t.setAttribute("aria-label",this.#ve),t.setAttribute("role","mark")),this.#Wo?t.classList.add("free"):this.div.addEventListener("keydown",this.#el.bind(this),{signal:this._uiManager._signal});const e=this.#zo=document.createElement("div");return t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#No,this.setDims(),bindEvents(this,this.#zo,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!1}})}#el(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#il(!0);break;case 1:case 3:this.#il(!1)}}#il(t){if(!this.#Lo)return;const e=window.getSelection();t?e.setPosition(this.#Lo,this.#Bo):e.setPosition(this.#Ho,this.#Go)}select(){super.select(),this.#jo&&this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#jo&&(this.parent?.drawLayer.updateProperties(this.#jo,{rootClass:{selected:!1}}),this.#Wo||this.#il(!1))}get _mustFixPosition(){return!this.#Wo}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#k,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#jo,{rootClass:{hidden:!t}}))}#Zo(){return this.#Wo?this.rotation:0}#nl(){if(this.#Wo)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#Oo,a=new Float32Array(8*s.length);let r=0;for(const{x:o,y:l,width:h,height:d}of s){const s=o*t+i,c=(1-l)*e+n;a[r]=a[r+4]=s,a[r+1]=a[r+3]=c,a[r+2]=a[r+6]=s+h*t,a[r+5]=a[r+7]=c-d*e,r+=8}return a}#sl(t){return this.#Vo.serialize(t,this.#Zo())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,d=t.combinedSignal(h),c=e=>{h.abort(),this.#al(t,e)};window.addEventListener("blur",c,{signal:d}),window.addEventListener("pointerup",c,{signal:d}),window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:d}),window.addEventListener("contextmenu",noContextMenu,{signal:d}),i.addEventListener("pointermove",this.#rl.bind(this,t),{signal:d}),this._freeHighlight=new FreeHighlightOutliner({x:n,y:s},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001),({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#rl(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#al(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:s,id:a,color:r,opacity:o,popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:AnnotationEditorType.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:d,creationDate:c,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:AnnotationEditorType.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:d?.str||null,creationDate:c,modificationDate:u}}const{color:s,quadPoints:a,inkLists:r,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...s),l.opacity=o||1,r&&(l.#do=t.thickness),l._initialData=n,t.comment&&l.setCommentData(t);const[h,d]=l.pageDimensions,[c,u]=l.pageTranslation;if(a){const t=l.#Oo=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-c)/h,y:1-(a[e+1]-u)/d,width:(a[e+2]-a[e])/h,height:(a[e+1]-a[e+5])/d});l.#Yo(),l.#Xo(),l.rotate(l.rotation)}else if(r){l.#Wo=!0;const t=r[0],i={x:t[0]-c,y:d-(t[1]-u)},n=new FreeHighlightOutliner(i,[0,0,h,d],1,l.#do/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2)i.x=t[e]-c,i.y=d-(t[e+1]-u),n.add(i);const{id:s,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:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);l.#Ko({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:a}),l.#Xo(),l.rotate(l.parentRotation)}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#do,quadPoints:this.#nl(),outlines:this.#sl(i.rect)}),this.addComment(i),this.annotationElementId&&!this.#Qr(i)?null:(i.id=this.annotationElementId,i)}#Qr(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#ol=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#ol[t]=e}toSVGProperties(){const t=this.#ol;return this.#ol=Object.create(null),{root:t}}reset(){this.#ol=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#ll=null;#hl;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#dl=null;static#cl=null;static#ul=null;static _INNER_MARGIN=3;constructor(t){super(t),this.#hl=t.mustBeCommitted||!1,this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}_addOutlines(t){t.drawOutlines&&(this.#pl(t),this.#Xo())}#pl({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ll=t,this._drawingOptions||=i,this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#gl(t,this.parent),this.#ml(t.box)}#gl(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e),this._currentParent&&(DrawingEditor.#dl.updateProperty(i,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],a=i=>{n.updateProperty(e,i);const s=this.#ll.updateProperty(e,i);s&&this.#ml(s),this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties()),t===this.colorType&&this.onUpdatedColor()};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathResizingSVGProperties(this.#fl()),{bbox:this.#bl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathResizedSVGProperties(this.#fl()),{bbox:this.#bl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#bl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ll.getPathTranslatedSVGProperties(this.#fl(),this.parentDimensions),{bbox:this.#bl()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#hl&&(this.#hl=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#tl(),super.remove()}rebuild(){this.parent&&(super.rebuild(),null!==this.div&&(this.#Xo(),this.#ml(this.#ll.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#tl()):t&&(this._uiManager.addShouldRescale(this),this.#Xo(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#tl(){null!==this._drawId&&this.parent&&(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#Xo(t=this.parent){null!==this._drawId&&this.parent===t||(null===this._drawId?(this._drawingOptions.updateAll(),this._drawId=this.#gl(this.#ll,t)):this.parent.drawLayer.updateParent(this._drawId,t.drawLayer))}#Al([t,e,i,n]){const{parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/s),n*(s/a)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(a/s),n*(s/a)];default:return[t,e,i,n]}}#fl(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(s/a),n*(a/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/a),n*(a/s)];default:return[t,e,i,n]}}#ml(t){[this.x,this.y,this.width,this.height]=this.#Al(t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()}#bl(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*s+a)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(r/o),n*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),n*(o/r)];case 6:return[1-t-n*(o/r),1-e,n*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-n*(o/r),i*(r/o),n*(o/r)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/r),e,n*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-n*(o/r),i*(r/o),n*(o/r)];case 14:return[1-t,1-e-i*(r/o),n*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),n*(o/r)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#bl()},this.#ll.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#ml(this.#ll.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;this._isCopy&&(t=this.x,e=this.y);const i=super.render();i.classList.add("draw");const n=document.createElement("div");return i.append(n),n.setAttribute("aria-hidden","true"),n.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,e),i}static createDrawerInstance(t,e,i,n,s){unreachable("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=n;if(CurrentPointers.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:d,height:c}=s.getBoundingClientRect(),u=DrawingEditor.#cl=new AbortController,p=t.combinedSignal(u);CurrentPointers.setPointer(l,o),window.addEventListener("pointerup",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p}),window.addEventListener("pointercancel",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p}),window.addEventListener("pointerdown",t=>{CurrentPointers.isSamePointerType(t.pointerType)&&(CurrentPointers.initializeAndAddPointerId(t.pointerId),DrawingEditor.#dl.isCancellable()&&(DrawingEditor.#dl.removeLastElement(),DrawingEditor.#dl.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",noContextMenu,{signal:p}),s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p}),s.addEventListener("touchmove",t=>{CurrentPointers.isSameTimeStamp(t.timeStamp)&&stopEvent(t)},{signal:p}),t.toggleDrawing(),e._editorUndoBar?.hide(),DrawingEditor.#dl?t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.startNew(a,r,d,c,h)):(e.updateUIForDefaultProperties(this),DrawingEditor.#dl=this.createDrawerInstance(a,r,d,c,h),DrawingEditor.#ul=this.getDefaultDrawingOptions(),this._currentParent=t,({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#ul.toSVGProperties(),DrawingEditor.#dl.defaultSVGProperties),!0,!1)))}static _drawMove(t){if(CurrentPointers.isSameTimeStamp(t.timeStamp),!DrawingEditor.#dl)return;const{offsetX:e,offsetY:i,pointerId:n}=t;CurrentPointers.isSamePointerId(n)&&(CurrentPointers.isUsingMultiplePointers()?this._endDraw(t):(this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.add(e,i)),CurrentPointers.setTimeStamp(t.timeStamp),stopEvent(t)))}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,DrawingEditor.#dl=null,DrawingEditor.#ul=null,CurrentPointers.clearTimeStamp()),DrawingEditor.#cl&&(DrawingEditor.#cl.abort(),DrawingEditor.#cl=null,CurrentPointers.clearPointerIds())}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#dl.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const t=DrawingEditor.#dl,i=this._currentDrawId,n=t.getLastElement();return void e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:AnnotationEditorParamsType.DRAW_STEP})}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP),!DrawingEditor.#dl.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#dl.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:DrawingEditor.#ul,mustBeCommitted:!t});return this._cleanup(!0),a}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);return l.createDrawingOptions(t),l.#pl({drawOutlines:o}),l.#Xo(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#ll.serialize([e,i,n,s],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#so=new Float64Array(6);#Sr;#yl;#Ms;#do;#co;#wl="";#vl=0;#Ro=new InkDrawOutline;#El;#xl;constructor(t,e,i,n,s,a){this.#El=i,this.#xl=n,this.#Ms=s,this.#do=a,[t,e]=this.#Tl(t,e);const r=this.#Sr=[NaN,NaN,NaN,NaN,t,e];this.#co=[t,e],this.#yl=[{line:r,points:this.#co}],this.#so.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#do=e)}#Tl(t,e){return Outline._normalizePoint(t,e,this.#El,this.#xl,this.#Ms)}isEmpty(){return!this.#yl||0===this.#yl.length}isCancellable(){return this.#co.length<=10}add(t,e){[t,e]=this.#Tl(t,e);const[i,n,s,a]=this.#so.subarray(2,6),r=t-s,o=e-a;return Math.hypot(this.#El*r,this.#xl*o)<=2?null:(this.#co.push(t,e),isNaN(i)?(this.#so.set([s,a,t,e],2),this.#Sr.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#so[0])&&this.#Sr.splice(6,6),this.#so.set([i,n,s,a,t,e],0),this.#Sr.push(...Outline.createBezierPoints(i,n,s,a,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const i=this.add(t,e);return i||(2===this.#co.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#El=i,this.#xl=n,this.#Ms=s,[t,e]=this.#Tl(t,e);const a=this.#Sr=[NaN,NaN,NaN,NaN,t,e];this.#co=[t,e];const r=this.#yl.at(-1);return r&&(r.line=new Float32Array(r.line),r.points=new Float32Array(r.points)),this.#yl.push({line:a,points:this.#co}),this.#so.set(a,0),this.#vl=0,this.toSVGPath(),null}getLastElement(){return this.#yl.at(-1)}setLastElement(t){return this.#yl?(this.#yl.push(t),this.#Sr=t.line,this.#co=t.points,this.#vl=0,{path:{d:this.toSVGPath()}}):this.#Ro.setLastElement(t)}removeLastElement(){if(!this.#yl)return this.#Ro.removeLastElement();this.#yl.pop(),this.#wl="";for(let t=0,e=this.#yl.length;t<e;t++){const{line:e,points:i}=this.#yl[t];this.#Sr=e,this.#co=i,this.#vl=0,this.toSVGPath()}return{path:{d:this.#wl}}}toSVGPath(){const t=Outline.svgRound(this.#Sr[4]),e=Outline.svgRound(this.#Sr[5]);if(2===this.#co.length)return this.#wl=`${this.#wl} M ${t} ${e} Z`,this.#wl;if(this.#co.length<=6){const i=this.#wl.lastIndexOf("M");this.#wl=`${this.#wl.slice(0,i)} M ${t} ${e}`,this.#vl=6}if(4===this.#co.length){const t=Outline.svgRound(this.#Sr[10]),e=Outline.svgRound(this.#Sr[11]);return this.#wl=`${this.#wl} L ${t} ${e}`,this.#vl=12,this.#wl}const i=[];0===this.#vl&&(i.push(`M ${t} ${e}`),this.#vl=6);for(let t=this.#vl,e=this.#Sr.length;t<e;t+=6){const[e,n,s,a,r,o]=this.#Sr.slice(t,t+6).map(Outline.svgRound);i.push(`C${e} ${n} ${s} ${a} ${r} ${o}`)}return this.#wl+=i.join(" "),this.#vl=this.#Sr.length,this.#wl}getOutlines(t,e,i,n){const s=this.#yl.at(-1);return s.line=new Float32Array(s.line),s.points=new Float32Array(s.points),this.#Ro.build(this.#yl,t,e,i,this.#Ms,this.#do,n),this.#so=null,this.#Sr=null,this.#yl=null,this.#wl=null,this.#Ro}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#Eo;#Sl=0;#eo;#yl;#El;#xl;#Cl;#Ms;#do;build(t,e,i,n,s,a,r){this.#El=e,this.#xl=i,this.#Cl=n,this.#Ms=s,this.#do=a,this.#eo=r??0,this.#yl=t,this.#_l()}get thickness(){return this.#do}setLastElement(t){return this.#yl.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#yl.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#yl)if(t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`),6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else for(let i=6,n=e.length;i<n;i+=6){const[n,s,a,r,o,l]=e.subarray(i,i+6).map(Outline.svgRound);t.push(`C${n} ${s} ${a} ${r} ${o} ${l}`)}else t.push("Z");return t.join("")}serialize([t,e,i,n],s){const a=[],r=[],[o,l,h,d]=this.#Pl();let c,u,p,g,m,f,b,A,y;switch(this.#Ms){case 0:y=Outline._rescale,c=t,u=e+n,p=i,g=-n,m=t+o*i,f=e+(1-l-d)*n,b=t+(o+h)*i,A=e+(1-l)*n;break;case 90:y=Outline._rescaleAndSwap,c=t,u=e,p=i,g=n,m=t+l*i,f=e+o*n,b=t+(l+d)*i,A=e+(o+h)*n;break;case 180:y=Outline._rescale,c=t+i,u=e,p=-i,g=n,m=t+(1-o-h)*i,f=e+l*n,b=t+(1-o)*i,A=e+(l+d)*n;break;case 270:y=Outline._rescaleAndSwap,c=t+i,u=e+n,p=-i,g=-n,m=t+(1-l-d)*i,f=e+(1-o-h)*n,b=t+(1-l)*i,A=e+(1-o)*n}for(const{line:t,points:e}of this.#yl)a.push(y(t,c,u,p,g,s?new Array(t.length):null)),r.push(y(e,c,u,p,g,s?new Array(e.length):null));return{lines:a,points:r,rect:[m,f,b,A]}}static deserialize(t,e,i,n,s,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let d,c,u,p,g;switch(o){case 0:g=Outline._rescale,d=-t/i,c=e/n+1,u=1/i,p=-1/n;break;case 90:g=Outline._rescaleAndSwap,d=-e/n,c=-t/i,u=1/n,p=1/i;break;case 180:g=Outline._rescale,d=t/i+1,c=-e/n,u=-1/i,p=1/n;break;case 270:g=Outline._rescaleAndSwap,d=e/n+1,c=t/i+1,u=-1/n,p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[n,s,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(Outline.createBezierPoints(n,s,r,o,e,l),3*(a-2)),[n,s,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),d,c,u,p),points:g(r[t].map(t=>t??NaN),d,c,u,p)});const m=new this.prototype.constructor;return m.build(h,i,n,1,o,l,s),m}#Dl(t=this.#do){const e=this.#eo+t/2*this.#Cl;return this.#Ms%180==0?[e/this.#El,e/this.#xl]:[e/this.#xl,e/this.#El]}#Pl(){const[t,e,i,n]=this.#Eo,[s,a]=this.#Dl(0);return[t+s,e+a,i-2*s,n-2*a]}#_l(){const t=this.#Eo=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#yl){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6)Util.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],n=e[5];for(let s=6,a=e.length;s<a;s+=6){const[a,r,o,l,h,d]=e.subarray(s,s+6);Util.bezierBoundingBox(i,n,a,r,o,l,h,d,t),i=h,n=d}}const[e,i]=this.#Dl();t[0]=MathClamp(t[0]-e,0,1),t[1]=MathClamp(t[1]-i,0,1),t[2]=MathClamp(t[2]+e,0,1),t[3]=MathClamp(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#Eo}updateProperty(t,e){return"stroke-width"===t?this.#Jo(e):null}#Jo(t){const[e,i]=this.#Dl();this.#do=t;const[n,s]=this.#Dl(),[a,r]=[n-e,s-i],o=this.#Eo;return o[0]-=a,o[1]-=r,o[2]+=2*a,o[3]+=2*r,o}updateParentDimensions([t,e],i){const[n,s]=this.#Dl();this.#El=t,this.#xl=e,this.#Cl=i;const[a,r]=this.#Dl(),o=a-n,l=r-s,h=this.#Eo;return h[0]-=o,h[1]-=l,h[2]+=2*o,h[3]+=2*l,h}updateRotation(t){return this.#Sl=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Eo.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#Eo;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#Eo;let i=0,n=0,s=0,a=0,r=0,o=0;switch(this.#Sl){case 90:n=e/t,s=-t/e,r=t;break;case 180:i=-1,a=-1,r=t,o=e;break;case 270:n=-e/t,s=t/e,o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${a} ${Outline.svgRound(r)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,a]=this.#Dl(),[r,o,l,h]=this.#Eo;if(Math.abs(l-s)<=Outline.PRECISION||Math.abs(h-a)<=Outline.PRECISION){const s=t+i/2-(r+l/2),a=e+n/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${a})`}}}const d=(i-2*s)/(l-2*s),c=(n-2*a)/(h-2*a),u=l/i,p=h/n;return{path:{"transform-origin":`${Outline.svgRound(r)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(s)} ${Outline.svgRound(a)}) scale(${d} ${c}) translate(${Outline.svgRound(-s)} ${Outline.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,a]=this.#Dl(),r=this.#Eo,[o,l,h,d]=r;if(r[0]=t,r[1]=e,r[2]=i,r[3]=n,Math.abs(h-s)<=Outline.PRECISION||Math.abs(d-a)<=Outline.PRECISION){const s=t+i/2-(o+h/2),a=e+n/2-(l+d/2);for(const{line:t,points:e}of this.#yl)Outline._translate(t,s,a,t),Outline._translate(e,s,a,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const c=(i-2*s)/(h-2*s),u=(n-2*a)/(d-2*a),p=-c*(o+s)+t+s,g=-u*(l+a)+e+a;if(1!==c||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#yl)Outline._rescale(t,p,g,c,u,t),Outline._rescale(e,p,g,c,u,e);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,a=this.#Eo,r=t-a[0],o=e-a[1];if(this.#El===n&&this.#xl===s)for(const{line:t,points:e}of this.#yl)Outline._translate(t,r,o,t),Outline._translate(e,r,o,e);else{const t=this.#El/n,e=this.#xl/s;this.#El=n,this.#xl=s;for(const{line:i,points:n}of this.#yl)Outline._rescale(i,r,o,t,e,i),Outline._rescale(n,r,o,t,e,n);a[2]*=t,a[3]*=e}return a[0]=t,a[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#Eo;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{constructor(t){super(),this._viewParameters=t,super.updateProperties({fill:"none",stroke:AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){"stroke-width"===t&&(e??=this["stroke-width"],e*=this._viewParameters.realScale),super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this._viewParameters);return t.updateAll(this),t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=AnnotationEditorType.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e),this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return shadow(this,"typesMap",new Map([[AnnotationEditorParamsType.INK_THICKNESS,"stroke-width"],[AnnotationEditorParamsType.INK_COLOR,"stroke"],[AnnotationEditorParamsType.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new InkDrawOutliner(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,a){return InkDrawOutline.deserialize(t,e,i,n,s,a)}static async deserialize(t,e,i){let n=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:AnnotationEditorType.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:p}}const s=await super.deserialize(t,e,i);return s._initialData=n,t.comment&&s.setCommentData(t),s}get toolbarButtons(){return this._colorPicker||=new BasicColorPicker(this),[["colorPicker",this._colorPicker]]}get colorType(){return AnnotationEditorParamsType.INK_COLOR}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=InkEditor.getDefaultDrawingOptions({stroke:Util.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":s,"stroke-width":a}}=this,r=Object.assign(super.serialize(t),{color:AnnotationEditor._colorManager.convert(n),opacity:s,thickness:a,paths:{lines:e,points:i}});return this.addComment(r),t?(r.isCopy=!0,r):this.annotationElementId&&!this.#Qr(r)?null:(r.id=this.annotationElementId,r)}#Qr(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:e,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment}),null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();return t.endsWith("Z")||(t+="Z"),t}}const BASE_HEADER_LENGTH=8,POINTS_PROPERTIES_NUMBER=3;class SignatureExtractor{static#Ml={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#Il(t,e,i,n){return n-=e,0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#kl=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#Fl(t,e,i,n,s,a,r){const o=this.#Il(i,n,s,a);for(let s=0;s<8;s++){const a=(-s+o-r+16)%8;if(0!==t[(i+this.#kl[2*a])*e+(n+this.#kl[2*a+1])])return a}return-1}static#Rl(t,e,i,n,s,a,r){const o=this.#Il(i,n,s,a);for(let s=0;s<8;s++){const a=(s+o+r+16)%8;if(0!==t[(i+this.#kl[2*a])*e+(n+this.#kl[2*a+1])])return a}return-1}static#Ll(t,e,i,n){const s=t.length,a=new Int32Array(s);for(let e=0;e<s;e++)a[e]=t[e]<=n?1:0;for(let t=1;t<i-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*i-1-t]=0;let r,o=1;const l=[];for(let t=1;t<i-1;t++){r=1;for(let i=1;i<e-1;i++){const n=t*e+i,s=a[n];if(0===s)continue;let h=t,d=i;if(1===s&&0===a[n-1])o+=1,d-=1;else{if(!(s>=1&&0===a[n+1])){1!==s&&(r=Math.abs(s));continue}o+=1,d+=1,s>1&&(r=s)}const c=[i,t],u=d===i+1,p={isHole:u,points:c,id:o,parent:0};let g;l.push(p);for(const t of l)if(t.id===r){g=t;break}g?g.isHole?p.parent=u?g.parent:r:p.parent=u?r:g.parent:p.parent=u?r:0;const m=this.#Fl(a,e,t,i,h,d,0);if(-1===m){a[n]=-o,1!==a[n]&&(r=Math.abs(a[n]));continue}let f=this.#kl[2*m],b=this.#kl[2*m+1];const A=t+f,y=i+b;h=A,d=y;let w=t,v=i;for(;;){const s=this.#Rl(a,e,w,v,h,d,1);f=this.#kl[2*s],b=this.#kl[2*s+1];const l=w+f,u=v+b;c.push(u,l);const p=w*e+v;if(0===a[p+1]?a[p]=-o:1===a[p]&&(a[p]=o),l===t&&u===i&&w===A&&v===y){1!==a[n]&&(r=Math.abs(a[n]));break}h=w,d=v,w=l,v=u}}}return l}static#Bl(t,e,i,n){if(i-e<=4){for(let s=e;s<i-2;s+=2)n.push(t[s],t[s+1]);return}const s=t[e],a=t[e+1],r=t[i-4]-s,o=t[i-3]-a,l=Math.hypot(r,o),h=r/l,d=o/l,c=h*a-d*s,u=o/r,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),A=p*(1-b+b**2),y=Math.max(Math.atan(Math.abs(f+m)*A),Math.atan(Math.abs(f-m)*A));let w=0,v=e;for(let n=e+2;n<i-2;n+=2){const e=Math.abs(c-h*t[n+1]+d*t[n]);e>w&&(v=n,w=e)}w>(l*y)**2?(this.#Bl(t,e,v+2,n),this.#Bl(t,v,i,n)):n.push(s,a)}static#Ol(t){const e=[],i=t.length;return this.#Bl(t,0,i,e),e.push(t[i-2],t[i-1]),e.length<=4?null:e}static#Nl(t,e,i,n,s,a){const r=new Float32Array(a**2),o=-2*n**2,l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let i=0;i<a;i++)r[t*a+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),d=-2*s**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/d);const c=t.length,u=new Uint8Array(c),p=new Uint32Array(256);for(let n=0;n<i;n++)for(let s=0;s<e;s++){const o=n*e+s,d=t[o];let c=0,g=0;for(let o=0;o<a;o++){const u=n+o-l;if(!(u<0||u>=i))for(let i=0;i<a;i++){const n=s+i-l;if(n<0||n>=e)continue;const p=t[u*e+n],m=r[o*a+i]*h[Math.abs(p-d)];c+=p*m,g+=m}}p[u[o]=Math.round(c/g)]++}return[u,p]}static#Ul(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#Hl(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,a=i.length;e<a;e++){const a=i[e]=t[e<<2];n=Math.max(n,a),s=Math.min(s,a)}const a=255/(n-s);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-s)*a;return i}static#Gl(t){let e,i=-1/0,n=-1/0;const s=t.findIndex(t=>0!==t);let a=s,r=s;for(e=s;e<256;e++){const s=t[e];s>i&&(e-a>n&&(n=e-a,r=e-1),i=s,a=e)}for(e=r-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#zl(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#Ml;let a=i,r=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const d=Math.floor(h);h=h===d?d-1:d;for(let i=0;i<h;i++){a=Math.ceil(o/2),r=Math.ceil(l/2);const i=new OffscreenCanvas(a,r);i.getContext("2d").drawImage(t,0,0,o,l,0,0,a,r),o=a,l=r,t!==e&&t.close(),t=i.transferToImageBitmap()}const c=Math.min(s/a,s/r);a=Math.round(a*c),r=Math.round(r*c)}const o=new OffscreenCanvas(a,r).getContext("2d",{willReadFrequently:!0});o.fillStyle="white",o.fillRect(0,0,a,r),o.filter="grayscale(1)",o.drawImage(t,0,0,t.width,t.height,0,0,a,r);const l=o.getImageData(0,0,a,r).data;return[this.#Hl(l),a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:n},s,a,r,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const d=h.font=`${i} ${n} 200px ${e}`,{actualBoundingBoxLeft:c,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),A=1.5,y=Math.ceil(Math.max(Math.abs(c)+Math.abs(u)||0,b)*A),w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*A);l=new OffscreenCanvas(y,w),h=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=d,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,y,w),h.fillStyle="black",h.fillText(t,.5*y/2,1.5*w/2);const v=this.#Hl(h.getImageData(0,0,y,w).data),E=this.#Ul(v),x=this.#Gl(E),T=this.#Ll(v,y,w,x);return this.processDrawnLines({lines:{curves:T,width:y,height:w},pageWidth:s,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,n,s){const[a,r,o]=this.#zl(t),[l,h]=this.#Nl(a,r,o,Math.hypot(r,o)*this.#Ml.sigmaSFactor,this.#Ml.sigmaR,this.#Ml.kernelSize),d=this.#Gl(h),c=this.#Ll(l,r,o,d);return this.processDrawnLines({lines:{curves:c,width:r,height:o},pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:a,areContours:r}){n%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,d=t.thickness??0,c=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=a?this.#Ol(t):t;if(!e)continue;m.push(e);const i=e.length,n=new Float32Array(i),s=new Float32Array(3*(2===i?2:i-2));if(c.push({line:s,points:n}),2===i){n[0]=e[0]*p,n[1]=e[1]*g,s.set([NaN,NaN,NaN,NaN,n[0],n[1]],0);continue}let[r,o,l,h]=e;r*=p,o*=g,l*=p,h*=g,n.set([r,o,l,h],0),s.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<i;t+=2){const i=n[t]=e[t]*p,a=n[t+1]=e[t+1]*g;s.set(Outline.createBezierPoints(r,o,l,h,i,a),3*(t-2)),[r,o,l,h]=[l,h,i,a]}}if(0===c.length)return null;const f=r?new ContourDrawOutline:new InkDrawOutline;return f.build(c,e,i,1,n,r?0:d,s),{outline:f,newCurves:m,areContours:r,thickness:d,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:n,height:s}){let a,r=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];r=Math.min(r,i),o=Math.max(o,i)}}a=r>=-128&&o<=127?Int8Array:r>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,d=8+3*h,c=new Uint32Array(d);let u=0;c[u++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*a.BYTES_PER_ELEMENT,c[u++]=0,c[u++]=n,c[u++]=s,c[u++]=e?0:1,c[u++]=Math.max(0,Math.floor(i??0)),c[u++]=h,c[u++]=a.BYTES_PER_ELEMENT;for(const e of t)c[u++]=e.length-2,c[u++]=e[0],c[u++]=e[1];const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready,g.write(c);const m=a.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i<n;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();const f=await new Response(p.readable).arrayBuffer();return new Uint8Array(f).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:i,writable:n}=new DecompressionStream("deflate-raw"),s=n.getWriter();await s.ready,s.write(e).then(async()=>{await s.ready,await s.close()}).catch(()=>{});let a=null,r=0;for await(const t of i)a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]),a.set(t,r),r+=t.length;const o=new Uint32Array(a.buffer,0,a.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],d=o[3],c=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(a.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(a.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(a.buffer,f)}r=0;for(let t=0;t<p;t++){const e=o[3*t+8],i=new Float32Array(e+2);m.push(i);for(let e=0;e<2;e++)i[e]=o[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+b[r++]}return{areContours:c,thickness:u,outlines:m,width:h,height:d}}catch(t){return warn(`decompressSignature: ${t}`),null}}}class SignatureOptions extends DrawingOptions{constructor(){super(),super.updateProperties({fill:AnnotationEditor._defaultLineColor,"stroke-width":0})}clone(){const t=new SignatureOptions;return t.updateAll(this),t}}class DrawnSignatureOptions extends InkDrawingOptions{constructor(t){super(t),super.updateProperties({stroke:AnnotationEditor._defaultLineColor,"stroke-width":1})}clone(){const t=new DrawnSignatureOptions(this._viewParameters);return t.updateAll(this),t}}class SignatureEditor extends DrawingEditor{#Vl=!1;#Wl=null;#jl=null;#$l=null;static _type="signature";static _editorType=AnnotationEditorType.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"}),this._willKeepAspectRatio=!0,this.#jl=t.signatureData||null,this.#Wl=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){AnnotationEditor.initialize(t,e),this._defaultDrawingOptions=new SignatureOptions,this._defaultDrawnSignatureOptions=new DrawnSignatureOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!1}static get typesMap(){return shadow(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#Wl}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,e=this.y),super.render(),null===this._drawId)if(this.#jl){const{lines:t,mustSmooth:e,areContours:i,description:n,uuid:s,heightInPage:a}=this.#jl,{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport,h=SignatureExtractor.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,a,n,s)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#Wl||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,e)),this.div}setUuid(t){this.#$l=t,this.addEditToolbar()}getUuid(){return this.#$l}get description(){return this.#Wl}set description(t){this.#Wl=t,this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#jl,a=Math.max(n,s);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:a}=this,{outline:r}=this.#jl=t;let o;this.#Vl=r instanceof ContourDrawOutline,this.description=i,this.#Vl?o=SignatureEditor.getDefaultDrawingOptions():(o=SignatureEditor._defaultDrawnSignatureOptions.clone(),o.updateProperties({"stroke-width":r.thickness})),this._addOutlines({drawOutlines:r,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h,this.width*=h/this.height,this.width>=1&&(h*=.9/this.width,this.width=.9),this.height=h,this.setDims(),this.x=s,this.y=a,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(n),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.process(t,e,i,n,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,n,s,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){t?this._drawingOptions=SignatureEditor.getDefaultDrawingOptions():(this._drawingOptions=SignatureEditor._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":e}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#Vl,color:[0,0,0],thickness:this.#Vl?0:n});return this.addComment(s),t?(s.paths={lines:e,points:i},s.uuid=this.#$l,s.isCopy=!0):s.lines=e,this.#Wl&&(s.accessibilityData={type:"Figure",alt:this.#Wl}),s}static deserializeDraw(t,e,i,n,s,a){return a.areContours?ContourDrawOutline.deserialize(t,e,i,n,s,a):InkDrawOutline.deserialize(t,e,i,n,s,a)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);return n.#Vl=t.areContours,n.description=t.accessibilityData?.alt||"",n.#$l=t.uuid,n}}class StampEditor extends AnnotationEditor{#Kl=null;#Xl=null;#Yl=null;#ql=null;#Jl=null;#Ql="";#Zl=null;#th=!1;#eh=null;#ih=!1;#nh=!1;static _type="stamp";static _editorType=AnnotationEditorType.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#ql=t.bitmapUrl,this.#Jl=t.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return SupportedImageMimeTypes.includes(t)}static paste(t,e){e.pasteEditor({mode:AnnotationEditorType.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#sh(t,e=!1){t?(this.#Kl=t.bitmap,e||(this.#Xl=t.id,this.#ih=t.isSvg),t.file&&(this.#Ql=t.file.name),this.#ah()):this.remove()}#rh(){if(this.#Yl=null,this._uiManager.enableWaiting(!1),this.#Zl)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kl)this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#Kl){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn\'t enabled for alt text.");const{data:n,width:s,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:n,width:s,height:a,channels:n.length/(s*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;return await this.setGuessedAltText(o),e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1}),o}#oh(){if(this.#Xl)return this._uiManager.enableWaiting(!0),void this._uiManager.imageManager.getFromId(this.#Xl).then(t=>this.#sh(t,!0)).finally(()=>this.#rh());if(this.#ql){const t=this.#ql;return this.#ql=null,this._uiManager.enableWaiting(!0),void(this.#Yl=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#sh(t)).finally(()=>this.#rh()))}if(this.#Jl){const t=this.#Jl;return this.#Jl=null,this._uiManager.enableWaiting(!0),void(this.#Yl=this._uiManager.imageManager.getFromFile(t).then(t=>this.#sh(t)).finally(()=>this.#rh()))}const t=document.createElement("input");t.type="file",t.accept=SupportedImageMimeTypes.join(",");const e=this._uiManager._signal;this.#Yl=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#sh(e)}else this.remove();i()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:e})}).finally(()=>this.#rh()),t.click()}remove(){this.#Xl&&(this.#Kl=null,this._uiManager.imageManager.deleteId(this.#Xl),this.#Zl?.remove(),this.#Zl=null,this.#eh&&(clearTimeout(this.#eh),this.#eh=null)),super.remove()}rebuild(){this.parent?(super.rebuild(),null!==this.div&&(this.#Xl&&null===this.#Zl&&this.#oh(),this.isAttachedToDOM||this.parent.add(this))):this.#Xl&&this.#oh()}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#Yl||this.#Kl||this.#ql||this.#Jl||this.#Xl||this.#th)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;return this._isCopy&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.createAltText(),this.#th||(this.#Kl?this.#ah():this.#oh()),this._isCopy&&this._moveAfterPaste(t,e),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(this.#Xl=i,n&&(this.#Kl=n),this.#th=!1,this.#ah())}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#eh&&clearTimeout(this.#eh);this.#eh=setTimeout(()=>{this.#eh=null,this.#lh()},200)}#ah(){const{div:t}=this;let{width:e,height:i}=this.#Kl;const[n,s]=this.pageDimensions,a=.75;if(this.width)e=this.width*n,i=this.height*s;else if(e>a*n||i>a*s){const t=Math.min(a*n/e,a*s/i);e*=t,i*=t}this._uiManager.enableWaiting(!1);const r=this.#Zl=document.createElement("canvas");r.setAttribute("role","img"),this.addContainer(r),this.width=e/n,this.height=i/s,this.setDims(),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1),this.#lh(),this.#nh||(this.parent.addUndoableEditor(this),this.#nh=!0),this._reportTelemetry({action:"inserted_image"}),this.#Ql&&this.div.setAttribute("aria-description",this.#Ql),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#Kl,a=new OutputScale;let r=this.#Kl,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t),l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#ih||(r=this.#hh(t,i));const d=h.getContext("2d");d.filter=this._uiManager.hcmFilter;let c="white",u="#cfcfd8";"none"!==this._uiManager.hcmFilter?u="black":ColorScheme.isDarkMode&&(c="#8f8f9d",u="#42414d");const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=c,b.fillRect(0,0,2*g,2*m),b.fillStyle=u,b.fillRect(0,0,g,m),b.fillRect(g,m,g,m),d.fillStyle=d.createPattern(f,"repeat"),d.fillRect(0,0,t,i),d.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let d=null;if(i){let e,i;if(a.symmetric&&r.width<t&&r.height<t)e=r.width,i=r.height;else if(r=this.#Kl,n>t||s>t){const a=Math.min(t/n,t/s);e=Math.floor(n*a),i=Math.floor(s*a),this.#ih||(r=this.#hh(e,i))}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i),d={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:d}}#hh(t,e){const{width:i,height:n}=this.#Kl;let s=i,a=n,r=this.#Kl;for(;s>2*t||a>2*e;){const i=s,n=a;s>2*t&&(s=s>=16384?Math.floor(s/2)-1:Math.ceil(s/2)),a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(s,a);o.getContext("2d").drawImage(r,0,0,i,n,0,0,s,a),r=o.transferToImageBitmap()}return r}#lh(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new OutputScale,a=Math.ceil(i*t*s.sx),r=Math.ceil(n*e*s.sy),o=this.#Zl;if(!o||o.width===a&&o.height===r)return;o.width=a,o.height=r;const l=this.#ih?this.#Kl:this.#hh(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#dh(t){if(t){if(this.#ih){const t=this._uiManager.imageManager.getSvgUrl(this.#Xl);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#Kl);return t.getContext("2d").drawImage(this.#Kl,0,0),t.toDataURL()}if(this.#ih){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);return s.getContext("2d").drawImage(this.#Kl,0,0,this.#Kl.width,this.#Kl.height,0,0,i,n),s.transferToImageBitmap()}return structuredClone(this.#Kl)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof StampAnnotationElement){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h,richText:d,contentsObj:c,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:m}},canvas:f}=t;let b,A;f?(delete t.canvas,({id:b,bitmap:A}=i.imageManager.getFromCanvas(g.id,f)),f.remove()):(s=!0,t._hasNoCanvas=!0);const y=(await e._structTree.getAriaAttributes(`${AnnotationPrefix}${o}`))?.get("aria-label")||"";n=t={annotationType:AnnotationEditorType.STAMP,bitmapId:b,bitmap:A,pageIndex:m-1,rect:a.slice(0),rotation:r,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:y},isSvg:!1,structParent:l,popupRef:h,richText:d,comment:c?.str||null,creationDate:u,modificationDate:p}}const a=await super.deserialize(t,e,i),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:d,accessibilityData:c}=t;s?(i.addMissingCanvas(t.id,a),a.#th=!0):h&&i.imageManager.isValidId(h)?(a.#Xl=h,o&&(a.#Kl=o)):a.#ql=l,a.#ih=d;const[u,p]=a.pageDimensions;return a.width=(r[2]-r[0])/u,a.height=(r[3]-r[1])/p,c&&(a.altTextData=c),a._initialData=n,t.comment&&a.setCommentData(t),a.#nh=!!n,a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#Xl,isSvg:this.#ih});if(this.addComment(i),t)return i.bitmapUrl=this.#dh(!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:n,altText:s}=this.serializeAltText(!1);if(!n&&s&&(i.accessibilityData={type:"Figure",alt:s}),this.annotationElementId){const t=this.#Qr(i);return t.isSame?null:(t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(null===e)return i;e.stamps||=new Map;const a=this.#ih?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Xl)){if(this.#ih){const t=e.stamps.get(this.#Xl);a>t.area&&(t.area=a,t.serialized.bitmap.close(),t.serialized.bitmap=this.#dh(!1))}}else e.stamps.set(this.#Xl,{area:a,serialized:i}),i.bitmap=this.#dh(!1);return i}#Qr(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}class AnnotationEditorLayer{#Rr;#ch=!1;#uh=null;#ph=null;#gh=null;#mh=new Map;#fh=!1;#bh=!1;#Ah=!1;#yh=null;#wh=null;#vh=null;#Eh=null;#xh=null;#Th=-1;#T;static _initialized=!1;static#it=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const d=[...AnnotationEditorLayer.#it.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of d)e.initialize(h,t)}t.registerEditorTypes(d),this.#T=t,this.pageIndex=e,this.div=i,this.#Rr=s,this.#uh=a,this.viewport=l,this.#vh=o,this.drawLayer=r,this._structTree=n,this.#T.addLayer(this)}updatePageIndex(t){this.pageIndex=t}get isEmpty(){return 0===this.#mh.size}get isInvisible(){return this.isEmpty&&this.#T.getMode()===AnnotationEditorType.NONE}updateToolbar(t){this.#T.updateToolbar(t)}updateMode(t=this.#T.getMode()){switch(this.#Sh(),t){case AnnotationEditorType.NONE:return this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),void this.disableClick();case AnnotationEditorType.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;if(e.toggle("nonEditing",!1),t===AnnotationEditorType.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#it.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#vh?.div}setEditingState(t){this.#T.setEditingState(t)}addCommands(t){this.#T.addCommands(t)}cleanUndoStack(t){this.#T.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#uh?.togglePointerEvents(t)}get#Ch(){return 0!==this.#mh.size?this.#mh.values():this.#T.getEditors(this.pageIndex)}async enable(){this.#Ah=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#xh?.abort(),this.#xh=null;const t=new Set;for(const e of this.#Ch)e.enableEditing(),e.show(!0),e.annotationElementId&&(this.#T.removeChangedExistingAnnotation(e),t.add(e.annotationElementId));const e=this.#uh;if(e)for(const i of e.getEditableAnnotations()){if(i.hide(),this.#T.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);e&&(this.addOrRebuild(e),e.enableEditing())}this.#Ah=!1,this.#T._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#bh=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#vh&&!this.#xh){this.#xh=new AbortController;const t=this.#T.combinedSignal(this.#xh);this.#vh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#Th>500)return void(this.#Th=n);this.#Th=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const a=document.elementsFromPoint(e,i);if(s.toggle("getElements",!1),!this.div.contains(a[0]))return;let r;const o=new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`);for(const t of a)if(o.test(t.id)){r=t.id;break}if(!r)return;const l=this.#mh.get(r);null===l?.annotationElementId&&(t.stopPropagation(),t.preventDefault(),l.dblclick(t))},{signal:t,capture:!0})}const t=this.#uh,e=[];if(t){const i=new Map,n=new Map;for(const t of this.#Ch)t.disableEditing(),t.annotationElementId?null===t.serialize()?(n.set(t.annotationElementId,t),this.getEditableAnnotation(t.annotationElementId)?.show(),t.remove()):i.set(t.annotationElementId,t):e.push(t);const s=t.getEditableAnnotations();for(const t of s){const{id:e}=t.data;if(this.#T.isDeletedAnnotationElement(e)){t.updateEdited({deleted:!0});continue}let s=n.get(e);s?(s.resetAnnotationElement(t),s.show(!1),t.show()):(s=i.get(e),s&&(this.#T.addChangedExistingAnnotation(s),s.renderAnnotationElement(t)&&s.show(!1)),t.show())}}this.#Sh(),this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#it.values())i.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),t?.updateFakeAnnotations(e),this.#bh=!1}getEditableAnnotation(t){return this.#uh?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#T.getActive()!==t&&this.#T.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#vh?.div&&!this.#Eh){this.#Eh=new AbortController;const t=this.#T.combinedSignal(this.#Eh);this.#vh.div.addEventListener("pointerdown",this.#_h.bind(this),{signal:t}),this.#vh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#vh?.div&&this.#Eh&&(this.#Eh.abort(),this.#Eh=null,this.#vh.div.classList.remove("highlighting"))}#_h(t){this.#T.unselectAll();const{target:e}=t;if(e===this.#vh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#vh.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#T.showAllEditors("highlight",!0,!0),this.#vh.div.classList.add("free"),this.toggleDrawing(),HighlightEditor.startHighlighting(this,"ltr"===this.#T.direction,{target:this.#vh.div,x:t.x,y:t.y}),this.#vh.div.addEventListener("pointerup",()=>{this.#vh.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#T._signal}),t.preventDefault()}}enableClick(){if(this.#ph)return;this.#ph=new AbortController;const t=this.#T.combinedSignal(this.#ph);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.#ph?.abort(),this.#ph=null}attach(t){this.#mh.set(t.id,t);const{annotationElementId:e}=t;e&&this.#T.isDeletedAnnotationElement(e)&&this.#T.removeDeletedAnnotationElement(t)}detach(t){this.#mh.delete(t.id),this.#Rr?.removePointerInTextLayer(t.contentDiv),!this.#bh&&t.annotationElementId&&this.#T.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#T.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#T.addDeletedAnnotationElement(t),AnnotationEditor.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(t.parent!==this||!t.isAttachedToDOM){if(this.changeParent(t),this.#T.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#Ah),this.#T.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#gh&&(t._focusEventsAllowed=!1,this.#gh=setTimeout(()=>{this.#gh=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#T._signal}),e.focus())},0)),t._structTreeParentId=this.#Rr?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#mh.values())if(e.uid===t)return e;return null}getNextId(){return this.#T.getId()}get#Ph(){return AnnotationEditorLayer.#it.get(this.#T.getMode())}combinedSignal(t){return this.#T.combinedSignal(t)}#Dh(t){const e=this.#Ph;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#Ph?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t),await this.#T.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#Mh(),s=this.getNextId(),a=this.#Dh({parent:this,id:s,x:i,y:n,uiManager:this.#T,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#it.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#T))||null}createAndAddNewEditor(t,e,i={}){const n=this.getNextId(),s=this.#Dh({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#T,isCentered:e,...i});return s&&this.add(s),s}get boundingClientRect(){return this.div.getBoundingClientRect()}#Mh(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),a=Math.max(0,e),r=(s+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#Mh(),!0,t)}setSelected(t){this.#T.setSelected(t)}toggleSelected(t){this.#T.toggleSelected(t)}unselect(t){this.#T.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#fh)return;if(this.#fh=!1,this.#Ph?.isDrawer&&this.#Ph.supportMultipleDrawings)return;if(!this.#ch)return void(this.#ch=!0);const i=this.#T.getMode();i!==AnnotationEditorType.STAMP&&i!==AnnotationEditorType.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#T.unselectAll()}pointerdown(t){if(this.#T.getMode()===AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#fh)return void(this.#fh=!1);const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(this.#fh=!0,this.#Ph?.isDrawer)return void this.startDrawingSession(t);const i=this.#T.getActive();this.#ch=!i||i.isEmpty()}startDrawingSession(t){if(this.div.focus({preventScroll:!0}),this.#yh)return void this.#Ph.startDrawing(this,this.#T,!1,t);this.#T.setCurrentDrawingSession(this),this.#yh=new AbortController;const e=this.#T.combinedSignal(this.#yh);this.div.addEventListener("blur",({relatedTarget:t})=>{t&&!this.div.contains(t)&&(this.#wh=null,this.commitOrRemove())},{signal:e}),this.#Ph.startDrawing(this,this.#T,!1,t)}pause(t){if(t){const{activeElement:t}=document;return void(this.div.contains(t)&&(this.#wh=t))}this.#wh&&setTimeout(()=>{this.#wh?.focus(),this.#wh=null},0)}endDrawingSession(t=!1){return this.#yh?(this.#T.setCurrentDrawingSession(null),this.#yh.abort(),this.#yh=null,this.#wh=null,this.#Ph.endDrawing(t)):null}findNewParent(t,e,i){const n=this.#T.findParent(e,i);return null!==n&&n!==this&&(n.changeParent(t),!0)}commitOrRemove(){return!!this.#yh&&(this.endDrawingSession(),!0)}onScaleChanging(){this.#yh&&this.#Ph.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#T.getActive()?.parent===this&&(this.#T.commitOrRemove(),this.#T.setActiveEditor(null)),this.#gh&&(clearTimeout(this.#gh),this.#gh=null);for(const t of this.#mh.values())this.#Rr?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#mh.clear(),this.#T.removeLayer(this)}#Sh(){for(const t of this.#mh.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,setLayerDimensions(this.div,t);for(const t of this.#T.getEditors(this.pageIndex))this.add(t),t.rebuild();this.updateMode()}update({viewport:t}){this.#T.commitOrRemove(),this.#Sh();const e=this.viewport.rotation,i=t.rotation;if(this.viewport=t,setLayerDimensions(this.div,{rotation:i}),e!==i)for(const t of this.#mh.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#T.viewParameters.realScale}}class DrawLayer{#sr=null;#Ih=new Map;#kh=new Map;static#k=0;setParent(t){if(this.#sr){if(this.#sr!==t){if(this.#Ih.size>0)for(const e of this.#Ih.values())e.remove(),t.append(e);this.#sr=t}}else this.#sr=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#Fh(t,[e,i,n,s]){const{style:a}=t;a.top=100*i+"%",a.left=100*e+"%",a.width=100*n+"%",a.height=100*s+"%"}#Rh(){const t=DrawLayer._svgFactory.create(1,1,!0);return this.#sr.append(t),t.setAttribute("aria-hidden",!0),t}#Lh(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n),i.setAttribute("clipPathUnits","objectBoundingBox");const s=DrawLayer._svgFactory.createElement("use");return i.append(s),s.setAttribute("href",`#${e}`),s.classList.add("clip"),n}#Bh(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=DrawLayer.#k++,s=this.#Rh(),a=DrawLayer._svgFactory.createElement("defs");s.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_${n}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#kh.set(n,r);const l=i?this.#Lh(a,o):null,h=DrawLayer._svgFactory.createElement("use");return s.append(h),h.setAttribute("href",`#${o}`),this.updateProperties(s,t),this.#Ih.set(n,s),{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#k++,n=this.#Rh(),s=DrawLayer._svgFactory.createElement("defs");n.append(s);const a=DrawLayer._svgFactory.createElement("path");s.append(a);const r=`path_${i}`;let o;if(a.setAttribute("id",r),a.setAttribute("vector-effect","non-scaling-stroke"),e){const t=DrawLayer._svgFactory.createElement("mask");s.append(t),o=`mask_${i}`,t.setAttribute("id",o),t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e),e.setAttribute("width","1"),e.setAttribute("height","1"),e.setAttribute("fill","white");const n=DrawLayer._svgFactory.createElement("use");t.append(n),n.setAttribute("href",`#${r}`),n.setAttribute("stroke","none"),n.setAttribute("fill","black"),n.setAttribute("fill-rule","nonzero"),n.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");n.append(l),l.setAttribute("href",`#${r}`),o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();return n.append(h),l.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(n,t),this.#Ih.set(i,n),i}finalizeDraw(t,e){this.#kh.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:a}=e,r="number"==typeof t?this.#Ih.get(t):t;if(r){if(i&&this.#Bh(r,i),n&&DrawLayer.#Fh(r,n),s){const{classList:t}=r;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(a){const t=r.firstElementChild.firstElementChild;this.#Bh(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#Ih.get(t);i&&(e.#sr.append(i),this.#Ih.delete(t),e.#Ih.set(t,i))}remove(t){this.#kh.delete(t),null!==this.#sr&&(this.#Ih.get(t).remove(),this.#Ih.delete(t))}destroy(){this.#sr=null;for(const t of this.#Ih.values())t.remove();this.#Ih.clear(),this.#kh.clear()}}globalThis._pdfjsTestingUtils={HighlightOutliner:HighlightOutliner},globalThis.pdfjsLib={AbortException:AbortException,AnnotationEditorLayer:AnnotationEditorLayer,AnnotationEditorParamsType:AnnotationEditorParamsType,AnnotationEditorType:AnnotationEditorType,AnnotationEditorUIManager:AnnotationEditorUIManager,AnnotationLayer:AnnotationLayer,AnnotationMode:AnnotationMode,AnnotationType:AnnotationType,applyOpacity:applyOpacity,build:build,ColorPicker:ColorPicker,createValidAbsoluteUrl:createValidAbsoluteUrl,CSSConstants:CSSConstants,DOMSVGFactory:DOMSVGFactory,DrawLayer:DrawLayer,FeatureTest:util_FeatureTest,fetchData:fetchData,findContrastColor:findContrastColor,getDocument:getDocument,getFilenameFromUrl:getFilenameFromUrl,getPdfFilenameFromUrl:getPdfFilenameFromUrl,getRGB:getRGB,getUuid:getUuid,getXfaPageViewport:getXfaPageViewport,GlobalWorkerOptions:GlobalWorkerOptions,ImageKind:util_ImageKind,InvalidPDFException:InvalidPDFException,isDataScheme:isDataScheme,isPdfFile:isPdfFile,isValidExplicitDest:isValidExplicitDest,MathClamp:MathClamp,noContextMenu:noContextMenu,normalizeUnicode:normalizeUnicode,OPS:OPS,OutputScale:OutputScale,PagesMapper:PagesMapper,PasswordResponses:PasswordResponses,PDFDataRangeTransport:PDFDataRangeTransport,PDFDateString:PDFDateString,PDFWorker:PDFWorker,PermissionFlag:PermissionFlag,PixelsPerInch:PixelsPerInch,RenderingCancelledException:RenderingCancelledException,renderRichText:renderRichText,ResponseException:ResponseException,setLayerDimensions:setLayerDimensions,shadow:shadow,SignatureExtractor:SignatureExtractor,stopEvent:stopEvent,SupportedImageMimeTypes:SupportedImageMimeTypes,TextLayer:TextLayer,TouchManager:TouchManager,updateUrlHash:updateUrlHash,Util:Util,VerbosityLevel:VerbosityLevel,version:version,XfaLayer:XfaLayer};export{AbortException,AnnotationEditorLayer,AnnotationEditorParamsType,AnnotationEditorType,AnnotationEditorUIManager,AnnotationLayer,AnnotationMode,AnnotationType,CSSConstants,ColorPicker,DOMSVGFactory,DrawLayer,util_FeatureTest as FeatureTest,GlobalWorkerOptions,util_ImageKind as ImageKind,InvalidPDFException,MathClamp,OPS,OutputScale,PDFDataRangeTransport,PDFDateString,PDFWorker,PagesMapper,PasswordResponses,PermissionFlag,PixelsPerInch,RenderingCancelledException,ResponseException,SignatureExtractor,SupportedImageMimeTypes,TextLayer,TouchManager,Util,VerbosityLevel,XfaLayer,applyOpacity,build,createValidAbsoluteUrl,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getUuid,getXfaPageViewport,isDataScheme,isPdfFile,isValidExplicitDest,noContextMenu,normalizeUnicode,renderRichText,setLayerDimensions,shadow,stopEvent,updateUrlHash,version};';export{t as default};