@component-hook/pdf-canvas 1.3.0-alpha.4 → 1.3.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.
@@ -1,11 +1,11 @@
1
- (function(st,J){typeof exports=="object"&&typeof module<"u"?J(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],J):(st=typeof globalThis<"u"?globalThis:st||self,J(st["pdf-canvas"]={},st.React))})(this,(function(st,J){"use strict";var Jl=st=>{throw TypeError(st)};var Mo=(st,J,mt)=>J.has(st)||Jl("Cannot "+mt);var ye=(st,J,mt)=>(Mo(st,J,"read from private field"),mt?mt.call(st):J.get(st)),Xs=(st,J,mt)=>J.has(st)?Jl("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(st):J.set(st,mt),Ai=(st,J,mt,Oe)=>(Mo(st,J,"write to private field"),Oe?Oe.call(st,mt):J.set(st,mt),mt),Un=(st,J,mt)=>(Mo(st,J,"access private method"),mt);var Zl=(st,J,mt,Oe)=>({set _(ts){Ai(st,J,ts,mt)},get _(){return ye(st,J,Oe)}});var Xn,_s,ws,Vs,$n,Ws,qn;var mt=typeof document<"u"?document.currentScript:null,Oe={exports:{}},ts={};var Po;function Ql(){if(Po)return ts;Po=1;var a=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,i,n){var r=null;if(n!==void 0&&(r=""+n),i.key!==void 0&&(r=""+i.key),"key"in i){n={};for(var o in i)o!=="key"&&(n[o]=i[o])}else n=i;return i=n.ref,{$$typeof:a,type:s,key:r,ref:i!==void 0?i:null,props:n}}return ts.Fragment=t,ts.jsx=e,ts.jsxs=e,ts}var Us={};var Oo;function tc(){return Oo||(Oo=1,process.env.NODE_ENV!=="production"&&(function(){function a(E){if(E==null)return null;if(typeof E=="function")return E.$$typeof===F?null:E.displayName||E.name||null;if(typeof E=="string")return E;switch(E){case b:return"Fragment";case v:return"Profiler";case m:return"StrictMode";case A:return"Suspense";case T:return"SuspenseList";case B:return"Activity"}if(typeof E=="object")switch(typeof E.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),E.$$typeof){case p:return"Portal";case _:return E.displayName||"Context";case y:return(E._context.displayName||"Context")+".Consumer";case S:var H=E.render;return E=E.displayName,E||(E=H.displayName||H.name||"",E=E!==""?"ForwardRef("+E+")":"ForwardRef"),E;case k:return H=E.displayName||null,H!==null?H:a(E.type)||"Memo";case P:H=E._payload,E=E._init;try{return a(E(H))}catch{}}return null}function t(E){return""+E}function e(E){try{t(E);var H=!1}catch{H=!0}if(H){H=console;var V=H.error,Q=typeof Symbol=="function"&&Symbol.toStringTag&&E[Symbol.toStringTag]||E.constructor.name||"Object";return V.call(H,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",Q),t(E)}}function s(E){if(E===b)return"<>";if(typeof E=="object"&&E!==null&&E.$$typeof===P)return"<...>";try{var H=a(E);return H?"<"+H+">":"<...>"}catch{return"<...>"}}function i(){var E=I.A;return E===null?null:E.getOwner()}function n(){return Error("react-stack-top-frame")}function r(E){if(O.call(E,"key")){var H=Object.getOwnPropertyDescriptor(E,"key").get;if(H&&H.isReactWarning)return!1}return E.key!==void 0}function o(E,H){function V(){M||(M=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",H))}V.isReactWarning=!0,Object.defineProperty(E,"key",{get:V,configurable:!0})}function h(){var E=a(this.type);return R[E]||(R[E]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),E=this.props.ref,E!==void 0?E:null}function l(E,H,V,Q,kt,rt){var N=V.ref;return E={$$typeof:g,type:E,key:H,props:V,_owner:Q},(N!==void 0?N:null)!==null?Object.defineProperty(E,"ref",{enumerable:!1,get:h}):Object.defineProperty(E,"ref",{enumerable:!1,value:null}),E._store={},Object.defineProperty(E._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(E,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(E,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:kt}),Object.defineProperty(E,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:rt}),Object.freeze&&(Object.freeze(E.props),Object.freeze(E)),E}function c(E,H,V,Q,kt,rt){var N=H.children;if(N!==void 0)if(Q)if(D(N)){for(Q=0;Q<N.length;Q++)u(N[Q]);Object.freeze&&Object.freeze(N)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else u(N);if(O.call(H,"key")){N=a(E);var ft=Object.keys(H).filter(function(Zt){return Zt!=="key"});Q=0<ft.length?"{key: someKey, "+ft.join(": ..., ")+": ...}":"{key: someKey}",dt[N+Q]||(ft=0<ft.length?"{"+ft.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
1
+ (function(st,J){typeof exports=="object"&&typeof module<"u"?J(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],J):(st=typeof globalThis<"u"?globalThis:st||self,J(st["pdf-canvas"]={},st.React))})(this,(function(st,J){"use strict";var Jl=st=>{throw TypeError(st)};var Mo=(st,J,mt)=>J.has(st)||Jl("Cannot "+mt);var ye=(st,J,mt)=>(Mo(st,J,"read from private field"),mt?mt.call(st):J.get(st)),Xs=(st,J,mt)=>J.has(st)?Jl("Cannot add the same private member more than once"):J instanceof WeakSet?J.add(st):J.set(st,mt),Ai=(st,J,mt,Oe)=>(Mo(st,J,"write to private field"),Oe?Oe.call(st,mt):J.set(st,mt),mt),Un=(st,J,mt)=>(Mo(st,J,"access private method"),mt);var Zl=(st,J,mt,Oe)=>({set _(ts){Ai(st,J,ts,mt)},get _(){return ye(st,J,Oe)}});var Xn,_s,ws,Vs,$n,Ws,qn;var mt=typeof document<"u"?document.currentScript:null,Oe={exports:{}},ts={};var Po;function Ql(){if(Po)return ts;Po=1;var a=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function e(s,i,n){var r=null;if(n!==void 0&&(r=""+n),i.key!==void 0&&(r=""+i.key),"key"in i){n={};for(var o in i)o!=="key"&&(n[o]=i[o])}else n=i;return i=n.ref,{$$typeof:a,type:s,key:r,ref:i!==void 0?i:null,props:n}}return ts.Fragment=t,ts.jsx=e,ts.jsxs=e,ts}var Us={};var Oo;function tc(){return Oo||(Oo=1,process.env.NODE_ENV!=="production"&&(function(){function a(E){if(E==null)return null;if(typeof E=="function")return E.$$typeof===F?null:E.displayName||E.name||null;if(typeof E=="string")return E;switch(E){case b:return"Fragment";case v:return"Profiler";case m:return"StrictMode";case A:return"Suspense";case T:return"SuspenseList";case B:return"Activity"}if(typeof E=="object")switch(typeof E.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),E.$$typeof){case p:return"Portal";case _:return E.displayName||"Context";case y:return(E._context.displayName||"Context")+".Consumer";case S:var H=E.render;return E=E.displayName,E||(E=H.displayName||H.name||"",E=E!==""?"ForwardRef("+E+")":"ForwardRef"),E;case k:return H=E.displayName||null,H!==null?H:a(E.type)||"Memo";case P:H=E._payload,E=E._init;try{return a(E(H))}catch{}}return null}function t(E){return""+E}function e(E){try{t(E);var H=!1}catch{H=!0}if(H){H=console;var V=H.error,Q=typeof Symbol=="function"&&Symbol.toStringTag&&E[Symbol.toStringTag]||E.constructor.name||"Object";return V.call(H,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",Q),t(E)}}function s(E){if(E===b)return"<>";if(typeof E=="object"&&E!==null&&E.$$typeof===P)return"<...>";try{var H=a(E);return H?"<"+H+">":"<...>"}catch{return"<...>"}}function i(){var E=I.A;return E===null?null:E.getOwner()}function n(){return Error("react-stack-top-frame")}function r(E){if(O.call(E,"key")){var H=Object.getOwnPropertyDescriptor(E,"key").get;if(H&&H.isReactWarning)return!1}return E.key!==void 0}function o(E,H){function V(){M||(M=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",H))}V.isReactWarning=!0,Object.defineProperty(E,"key",{get:V,configurable:!0})}function h(){var E=a(this.type);return R[E]||(R[E]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),E=this.props.ref,E!==void 0?E:null}function l(E,H,V,Q,kt,rt){var N=V.ref;return E={$$typeof:g,type:E,key:H,props:V,_owner:Q},(N!==void 0?N:null)!==null?Object.defineProperty(E,"ref",{enumerable:!1,get:h}):Object.defineProperty(E,"ref",{enumerable:!1,value:null}),E._store={},Object.defineProperty(E._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(E,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(E,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:kt}),Object.defineProperty(E,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:rt}),Object.freeze&&(Object.freeze(E.props),Object.freeze(E)),E}function c(E,H,V,Q,kt,rt){var N=H.children;if(N!==void 0)if(Q)if(D(N)){for(Q=0;Q<N.length;Q++)u(N[Q]);Object.freeze&&Object.freeze(N)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else u(N);if(O.call(H,"key")){N=a(E);var ht=Object.keys(H).filter(function(Pt){return Pt!=="key"});Q=0<ht.length?"{key: someKey, "+ht.join(": ..., ")+": ...}":"{key: someKey}",ft[N+Q]||(ht=0<ht.length?"{"+ht.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
2
  let props = %s;
3
3
  <%s {...props} />
4
4
  React keys must be passed directly to JSX without using spread:
5
5
  let props = %s;
6
- <%s key={someKey} {...props} />`,Q,N,ft,N),dt[N+Q]=!0)}if(N=null,V!==void 0&&(e(V),N=""+V),r(H)&&(e(H.key),N=""+H.key),"key"in H){V={};for(var It in H)It!=="key"&&(V[It]=H[It])}else V=H;return N&&o(V,typeof E=="function"?E.displayName||E.name||"Unknown":E),l(E,N,V,i(),kt,rt)}function u(E){d(E)?E._store&&(E._store.validated=1):typeof E=="object"&&E!==null&&E.$$typeof===P&&(E._payload.status==="fulfilled"?d(E._payload.value)&&E._payload.value._store&&(E._payload.value._store.validated=1):E._store&&(E._store.validated=1))}function d(E){return typeof E=="object"&&E!==null&&E.$$typeof===g}var f=J,g=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),b=Symbol.for("react.fragment"),m=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),y=Symbol.for("react.consumer"),_=Symbol.for("react.context"),S=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),B=Symbol.for("react.activity"),F=Symbol.for("react.client.reference"),I=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=Object.prototype.hasOwnProperty,D=Array.isArray,z=console.createTask?console.createTask:function(){return null};f={react_stack_bottom_frame:function(E){return E()}};var M,R={},U=f.react_stack_bottom_frame.bind(f,n)(),ht=z(s(n)),dt={};Us.Fragment=b,Us.jsx=function(E,H,V){var Q=1e4>I.recentlyCreatedOwnerStacks++;return c(E,H,V,!1,Q?Error("react-stack-top-frame"):U,Q?z(s(E)):ht)},Us.jsxs=function(E,H,V){var Q=1e4>I.recentlyCreatedOwnerStacks++;return c(E,H,V,!0,Q?Error("react-stack-top-frame"):U,Q?z(s(E)):ht)}})()),Us}var Do;function ec(){return Do||(Do=1,process.env.NODE_ENV==="production"?Oe.exports=Ql():Oe.exports=tc()),Oe.exports}var Ro=ec();const sc="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e",ic={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},nc={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},rc={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},oc={stroke:"#000",hoverStroke:"#B7EC5D",src:sc},ac=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function x(a,t,e){return(t=(function(s){var i=(function(n,r){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,r);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)})(s,"string");return typeof i=="symbol"?i:i+""})(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Lo(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter((function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable}))),e.push.apply(e,s)}return e}function w(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Lo(Object(e),!0).forEach((function(s){x(a,s,e[s])})):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Lo(Object(e)).forEach((function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))}))}return a}function lt(a,t){if(a==null)return{};var e,s,i=(function(r,o){if(r==null)return{};var h={};for(var l in r)if({}.hasOwnProperty.call(r,l)){if(o.indexOf(l)>=0)continue;h[l]=r[l]}return h})(a,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(a);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(a,e)&&(i[e]=a[e])}return i}function _e(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class Fo{constructor(){x(this,"browserShadowBlurConstant",1),x(this,"DPI",96),x(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),x(this,"perfLimitSizeTotal",2097152),x(this,"maxCacheSideLimit",4096),x(this,"minCacheSideLimit",256),x(this,"disableStyleCopyPaste",!1),x(this,"enableGLFiltering",!0),x(this,"textureSize",4096),x(this,"forceGLPutImageData",!1),x(this,"cachesBoundsOfCurve",!1),x(this,"fontPaths",{}),x(this,"NUM_FRACTION_DIGITS",4)}}const et=new class extends Fo{constructor(a){super(),this.configure(a)}configure(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,a)}addFonts(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=w(w({},this.fontPaths),a)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach((a=>{delete this.fontPaths[a]}))}clearFonts(){this.fontPaths={}}restoreDefaults(a){const t=new Fo,e=a?.reduce(((s,i)=>(s[i]=t[i],s)),{})||t;this.configure(e)}},De=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[a]("fabric",...e)};class we extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class Kn extends we{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class hc{}class lc extends hc{testPrecision(t,e){const s="precision ".concat(e,` float;
7
- void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find((s=>this.testPrecision(e,s))),e.getExtension("WEBGL_lose_context").loseContext(),De("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const cc={};let Io;const xe=()=>Io||(Io={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new lc,dispose(){},copyPasteData:cc}),xs=()=>xe().document,Ys=()=>xe().window,No=()=>{var a;return Math.max((a=et.devicePixelRatio)!==null&&a!==void 0?a:Ys().devicePixelRatio,1)},$s=new class{constructor(){x(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase();const i=this.charWidthsCache;i.has(t)||i.set(t,new Map);const n=i.get(t),r="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return n.has(r)||n.set(r,new Map),n.get(r)}clearFontCache(a){a?this.charWidthsCache.delete((a||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(a){const{perfLimitSizeTotal:t}=et,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},Jn="6.9.0";function es(){}const We=Math.PI/2,Re=2*Math.PI,Zn=Math.PI/180,Nt=Object.freeze([1,0,0,1,0,0]),Qn=16,Xe=.4477152502,$="center",it="left",Yt="top",tr="bottom",bt="right",jt="none",er=/\r?\n/,jo="moving",Ti="scaling",Bo="rotating",sr="rotate",Ho="skewing",qs="resizing",uc="modifyPoly",dc="modifyPath",Ei="changed",ki="scale",Bt="scaleX",Qt="scaleY",Ss="skewX",Cs="skewY",wt="fill",Ht="stroke",Mi="modified",As="json",ir="svg",L=new class{constructor(){this[As]=new Map,this[ir]=new Map}has(a){return this[As].has(a)}getClass(a){const t=this[As].get(a);if(!t)throw new we("No class registered for ".concat(a));return t}setClass(a,t){t?this[As].set(t,a):(this[As].set(a.type,a),this[As].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[ir].get(a)}setSVGClass(a,t){this[ir].set(t??a.type.toLowerCase(),a)}},Pi=new class extends Array{remove(a){const t=this.indexOf(a);t>-1&&this.splice(t,1)}cancelAll(){const a=this.splice(0);return a.forEach((t=>t.abort())),a}cancelByCanvas(a){if(!a)return[];const t=this.filter((e=>{var s;return e.target===a||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===a}));return t.forEach((e=>e.abort())),t}cancelByTarget(a){if(!a)return[];const t=this.filter((e=>e.target===a));return t.forEach((e=>e.abort())),t}};class fc{constructor(){x(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach((s=>{let[i,n]=s;this.on(i,n)})),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach((i=>{let[n,r]=i;s.push(this.once(n,r))})),()=>s.forEach((i=>i()))}if(e){const s=this.on(t,(function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()}));return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach((s=>{let[i,n]=s;this._removeEventListener(i,n)})):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const ss=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},le=a=>{if(a===0)return 1;switch(Math.abs(a)/We){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ce=a=>{if(a===0)return 0;const t=a/We,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class C{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new C(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new C(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new C(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new C(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new C(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new C(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new C(this.x/t.x,this.y/t.y)}scalarDivide(t){return new C(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new C(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new C(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new C(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new C(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nr;const s=ce(t),i=le(t),n=this.subtract(e);return new C(n.x*i-n.y*s,n.x*s+n.y*i).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new C(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const nr=new C(0,0),Oi=a=>!!a&&Array.isArray(a._objects);function zo(a){class t extends a{constructor(){super(...arguments),x(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach((o=>this._onObjectAdded(o))),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach((o=>this._onObjectAdded(o))),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach((h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))})),i}forEachObject(s){this.getObjects().forEach(((i,n,r)=>s(i,n,r)))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter((r=>r.isType(...i)))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some((n=>n instanceof t&&n.contains(s,!0)))}complexity(){return this._objects.reduce(((s,i)=>s+=i.complexity?i.complexity():0),0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(ss(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(ss(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==0){const r=this.findNewLowerIndex(s,n,i);return ss(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==this._objects.length-1){const r=this.findNewUpperIndex(s,n,i);return ss(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(ss(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let o=i-1;o>=0;--o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let o=i+1;o<this._objects.length;++o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:o}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],c=new C(i,n),u=c.add(new C(r,o));for(let d=this._objects.length-1;d>=0;d--){const f=this._objects[d];f.selectable&&f.visible&&(h&&f.intersectsWithRect(c,u)||f.isContainedWithinRect(c,u)||h&&f.containsPoint(c)||h&&f.containsPoint(u))&&l.push(f)}return l}}return t}class Go extends fc{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function Ks(a){return Ys().requestAnimationFrame(a)}function Vo(a){return Ys().cancelAnimationFrame(a)}let gc=0;const Ue=()=>gc++,Se=()=>{const a=xs().createElement("canvas");if(!a||a.getContext===void 0)throw new we("Failed to create `canvas` element");return a},Wo=()=>xs().createElement("img"),te=a=>{const t=Se();return t.width=a.width,t.height=a.height,t},rr=(a,t,e)=>a.toDataURL("image/".concat(t),e),or=(a,t,e)=>new Promise(((s,i)=>{a.toBlob(s,"image/".concat(t),e)})),pt=a=>a*Zn,Ce=a=>a/Zn,Xo=a=>a.every(((t,e)=>t===Nt[e])),Mt=(a,t,e)=>new C(a).transform(t,e),$t=a=>{const t=1/(a[0]*a[3]-a[1]*a[2]),e=[t*a[3],-t*a[1],-t*a[2],t*a[0],0,0],{x:s,y:i}=new C(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},vt=(a,t,e)=>[a[0]*t[0]+a[2]*t[1],a[1]*t[0]+a[3]*t[1],a[0]*t[2]+a[2]*t[3],a[1]*t[2]+a[3]*t[3],e?0:a[0]*t[4]+a[2]*t[5]+a[4],e?0:a[1]*t[4]+a[3]*t[5]+a[5]],Di=(a,t)=>a.reduceRight(((e,s)=>s&&e?vt(s,e,t):s||e),void 0)||Nt.concat(),Uo=a=>{let[t,e]=a;return Math.atan2(e,t)},is=a=>{const t=Uo(a),e=Math.pow(a[0],2)+Math.pow(a[1],2),s=Math.sqrt(e),i=(a[0]*a[3]-a[2]*a[1])/s,n=Math.atan2(a[0]*a[2]+a[1]*a[3],e);return{angle:Ce(t),scaleX:s,scaleY:i,skewX:Ce(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},Ts=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function ns(){let{angle:a=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=pt(a),i=le(s),n=ce(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Ri=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},Yo=a=>Math.tan(pt(a)),ar=a=>[1,0,Yo(a),1,0,0],hr=a=>[1,Yo(a),0,1,0,0],Js=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=Ri(s?-t:t,i?-e:e);return n&&(o=vt(o,ar(n),!0)),r&&(o=vt(o,hr(r),!0)),o},$o=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=Ts(t,e);s&&(i=vt(i,ns({angle:s})));const n=Js(a);return Xo(n)||(i=vt(i,n)),i},Zs=function(a){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((function(s,i){if(t&&t.aborted)return i(new Kn("loadImage"));const n=Wo();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};a?(n.onload=o,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new we("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()}))},Es=function(a){let{signal:t,reviver:e=es}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(((s,i)=>{const n=[];t&&t.addEventListener("abort",i,{once:!0}),Promise.all(a.map((r=>L.getClass(r.type).fromObject(r,{signal:t}).then((o=>(e(r,o),n.push(o),o)))))).then(s).catch((r=>{n.forEach((o=>{o.dispose&&o.dispose()})),i(r)})).finally((()=>{t&&t.removeEventListener("abort",i)}))}))},Qs=function(a){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(((e,s)=>{const i=[];t&&t.addEventListener("abort",s,{once:!0});const n=Object.values(a).map((o=>o&&o.type&&L.has(o.type)?Es([o],{signal:t}).then((h=>{let[l]=h;return i.push(l),l})):o)),r=Object.keys(a);Promise.all(n).then((o=>o.reduce(((h,l,c)=>(h[r[c]]=l,h)),{}))).then(e).catch((o=>{i.forEach((h=>{h.dispose&&h.dispose()})),s(o)})).finally((()=>{t&&t.removeEventListener("abort",s)}))}))},rs=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce(((t,e)=>(e in a&&(t[e]=a[e]),t)),{})},lr=(a,t)=>Object.keys(a).reduce(((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e)),{}),ot=(a,t)=>parseFloat(Number(a).toFixed(t)),ks=a=>"matrix("+a.map((t=>ot(t,et.NUM_FRACTION_DIGITS))).join(" ")+")",re=a=>!!a&&a.toLive!==void 0,qo=a=>!!a&&typeof a.toObject=="function",Ko=a=>!!a&&a.offsetX!==void 0&&"source"in a,os=a=>!!a&&"multiSelectionStacking"in a;function Jo(a){const t=a&&ue(a);let e=0,s=0;if(!a||!t)return{left:e,top:s};let i=a;const n=t.documentElement,r=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(e=r.scrollLeft||n.scrollLeft||0,s=r.scrollTop||n.scrollTop||0):(e+=i.scrollLeft||0,s+=i.scrollTop||0),i.nodeType!==1||i.style.position!=="fixed"););return{left:e,top:s}}const ue=a=>a.ownerDocument||null,Zo=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Qo=function(a,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;a.width=s,a.height=i,n>1&&(a.setAttribute("width",(s*n).toString()),a.setAttribute("height",(i*n).toString()),t.scale(n,n))},cr=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(a.style.height=typeof s=="number"?"".concat(s,"px"):s)};function ta(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=jt,a}class ea{constructor(t){x(this,"_originalCanvasStyle",void 0),x(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&xs().getElementById(t)||Se();var s;if(e.hasAttribute("data-fabric"))throw new we("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;Qo(s,i,t,e)}setCSSDimensions(t){cr(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&ue(t),i={left:0,top:0};if(!s)return i;const n=((e=Zo(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=Jo(t);return{left:r.left+h.left-(o.clientLeft||0)+i.left,top:r.top+h.top-(o.clientTop||0)+i.top}})(this.lower.el)}dispose(){xe().dispose(this.lower.el),delete this.lower}}const pc={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Nt]},mc=["objects"];class ti extends zo(Go){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return ti.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new ea(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(De("warn",`Canvas is trying to add an object that belongs to a different canvas.
8
- Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?No():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i=w({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=Mt(t,$t(i));i[0]=e,i[3]=e;const r=Mt(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new C(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new C(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(t){t.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor="",this.overlayColor="",this.clearContext(this.getContext()),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=Ks((()=>this.renderAndReset())))}calcViewportBoundaries(){const t=this.width,e=this.height,s=$t(this.viewportTransform),i=Mt({x:0,y:0},s),n=Mt({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new C(o.x,r.y),bl:new C(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(Vo(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,i=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),i&&(i._set("canvas",this),i.shouldCache(),i._transformDone=!0,i.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,i)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,i=e.length;s<i;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],i=this["".concat(e,"Image")],n=this.viewportTransform,r=this["".concat(e,"Vpt")];if(!s&&!i)return;const o=re(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=o?s.toLive(t):s,r&&t.transform(...n),o){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new C(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new C(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new C(t.getCenterPoint().x,this.getCenterPoint().y))}centerObject(t){return this._centerObject(t,this.getCenterPoint())}viewportCenterObject(t){return this._centerObject(t,this.getVpCenter())}viewportCenterObjectH(t){return this._centerObject(t,new C(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new C(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Mt(this.getCenterPoint(),$t(this.viewportTransform))}_centerObject(t,e){t.setXY(e,$,$),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,i=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return w(w(w({version:Jn},rs(this,e)),{},{objects:this._objects.filter((n=>!n.excludeFromExport)).map((n=>this._toObject(n,t,e)))},this.__serializeBgOverlay(t,e)),i?{clipPath:i}:null)}_toObject(t,e,s){let i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!i),n}__serializeBgOverlay(t,e){const s={},i=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,o=this.overlayColor;return re(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),re(o)?o.excludeFromExport||(s.overlay=o.toObject(e)):o&&(s.overlay=o),i&&!i.excludeFromExport&&(s.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(s.overlayImage=this._toObject(n,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
6
+ <%s key={someKey} {...props} />`,Q,N,ht,N),ft[N+Q]=!0)}if(N=null,V!==void 0&&(e(V),N=""+V),r(H)&&(e(H.key),N=""+H.key),"key"in H){V={};for(var Mt in H)Mt!=="key"&&(V[Mt]=H[Mt])}else V=H;return N&&o(V,typeof E=="function"?E.displayName||E.name||"Unknown":E),l(E,N,V,i(),kt,rt)}function u(E){d(E)?E._store&&(E._store.validated=1):typeof E=="object"&&E!==null&&E.$$typeof===P&&(E._payload.status==="fulfilled"?d(E._payload.value)&&E._payload.value._store&&(E._payload.value._store.validated=1):E._store&&(E._store.validated=1))}function d(E){return typeof E=="object"&&E!==null&&E.$$typeof===g}var f=J,g=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),b=Symbol.for("react.fragment"),m=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),y=Symbol.for("react.consumer"),_=Symbol.for("react.context"),S=Symbol.for("react.forward_ref"),A=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),B=Symbol.for("react.activity"),F=Symbol.for("react.client.reference"),I=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O=Object.prototype.hasOwnProperty,D=Array.isArray,z=console.createTask?console.createTask:function(){return null};f={react_stack_bottom_frame:function(E){return E()}};var M,R={},U=f.react_stack_bottom_frame.bind(f,n)(),lt=z(s(n)),ft={};Us.Fragment=b,Us.jsx=function(E,H,V){var Q=1e4>I.recentlyCreatedOwnerStacks++;return c(E,H,V,!1,Q?Error("react-stack-top-frame"):U,Q?z(s(E)):lt)},Us.jsxs=function(E,H,V){var Q=1e4>I.recentlyCreatedOwnerStacks++;return c(E,H,V,!0,Q?Error("react-stack-top-frame"):U,Q?z(s(E)):lt)}})()),Us}var Do;function ec(){return Do||(Do=1,process.env.NODE_ENV==="production"?Oe.exports=Ql():Oe.exports=tc()),Oe.exports}var Ro=ec();const sc="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e",ic={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},nc={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},rc={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},oc={stroke:"#000",hoverStroke:"#B7EC5D",src:sc},ac=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function x(a,t,e){return(t=(function(s){var i=(function(n,r){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,r);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)})(s,"string");return typeof i=="symbol"?i:i+""})(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function Lo(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);t&&(s=s.filter((function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable}))),e.push.apply(e,s)}return e}function w(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Lo(Object(e),!0).forEach((function(s){x(a,s,e[s])})):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):Lo(Object(e)).forEach((function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(e,s))}))}return a}function ct(a,t){if(a==null)return{};var e,s,i=(function(r,o){if(r==null)return{};var h={};for(var l in r)if({}.hasOwnProperty.call(r,l)){if(o.indexOf(l)>=0)continue;h[l]=r[l]}return h})(a,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(a);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(a,e)&&(i[e]=a[e])}return i}function _e(a,t){return t||(t=a.slice(0)),Object.freeze(Object.defineProperties(a,{raw:{value:Object.freeze(t)}}))}class Fo{constructor(){x(this,"browserShadowBlurConstant",1),x(this,"DPI",96),x(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),x(this,"perfLimitSizeTotal",2097152),x(this,"maxCacheSideLimit",4096),x(this,"minCacheSideLimit",256),x(this,"disableStyleCopyPaste",!1),x(this,"enableGLFiltering",!0),x(this,"textureSize",4096),x(this,"forceGLPutImageData",!1),x(this,"cachesBoundsOfCurve",!1),x(this,"fontPaths",{}),x(this,"NUM_FRACTION_DIGITS",4)}}const et=new class extends Fo{constructor(a){super(),this.configure(a)}configure(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,a)}addFonts(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=w(w({},this.fontPaths),a)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach((a=>{delete this.fontPaths[a]}))}clearFonts(){this.fontPaths={}}restoreDefaults(a){const t=new Fo,e=a?.reduce(((s,i)=>(s[i]=t[i],s)),{})||t;this.configure(e)}},De=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[a]("fabric",...e)};class we extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class Kn extends we{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class hc{}class lc extends hc{testPrecision(t,e){const s="precision ".concat(e,` float;
7
+ void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find((s=>this.testPrecision(e,s))),e.getExtension("WEBGL_lose_context").loseContext(),De("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const cc={};let Io;const xe=()=>Io||(Io={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new lc,dispose(){},copyPasteData:cc}),xs=()=>xe().document,Ys=()=>xe().window,No=()=>{var a;return Math.max((a=et.devicePixelRatio)!==null&&a!==void 0?a:Ys().devicePixelRatio,1)},$s=new class{constructor(){x(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(a){let{fontFamily:t,fontStyle:e,fontWeight:s}=a;t=t.toLowerCase();const i=this.charWidthsCache;i.has(t)||i.set(t,new Map);const n=i.get(t),r="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return n.has(r)||n.set(r,new Map),n.get(r)}clearFontCache(a){a?this.charWidthsCache.delete((a||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(a){const{perfLimitSizeTotal:t}=et,e=Math.sqrt(t*a);return[Math.floor(e),Math.floor(t/e)]}},Jn="6.9.0";function es(){}const We=Math.PI/2,Re=2*Math.PI,Zn=Math.PI/180,jt=Object.freeze([1,0,0,1,0,0]),Qn=16,Xe=.4477152502,$="center",it="left",$t="top",tr="bottom",bt="right",Bt="none",er=/\r?\n/,jo="moving",Ti="scaling",Bo="rotating",sr="rotate",Ho="skewing",qs="resizing",uc="modifyPoly",dc="modifyPath",Ei="changed",ki="scale",Ht="scaleX",Qt="scaleY",Ss="skewX",Cs="skewY",wt="fill",zt="stroke",Mi="modified",As="json",ir="svg",L=new class{constructor(){this[As]=new Map,this[ir]=new Map}has(a){return this[As].has(a)}getClass(a){const t=this[As].get(a);if(!t)throw new we("No class registered for ".concat(a));return t}setClass(a,t){t?this[As].set(t,a):(this[As].set(a.type,a),this[As].set(a.type.toLowerCase(),a))}getSVGClass(a){return this[ir].get(a)}setSVGClass(a,t){this[ir].set(t??a.type.toLowerCase(),a)}},Pi=new class extends Array{remove(a){const t=this.indexOf(a);t>-1&&this.splice(t,1)}cancelAll(){const a=this.splice(0);return a.forEach((t=>t.abort())),a}cancelByCanvas(a){if(!a)return[];const t=this.filter((e=>{var s;return e.target===a||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===a}));return t.forEach((e=>e.abort())),t}cancelByTarget(a){if(!a)return[];const t=this.filter((e=>e.target===a));return t.forEach((e=>e.abort())),t}};class fc{constructor(){x(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach((s=>{let[i,n]=s;this.on(i,n)})),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach((i=>{let[n,r]=i;s.push(this.once(n,r))})),()=>s.forEach((i=>i()))}if(e){const s=this.on(t,(function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()}));return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach((s=>{let[i,n]=s;this._removeEventListener(i,n)})):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const ss=(a,t)=>{const e=a.indexOf(t);return e!==-1&&a.splice(e,1),a},le=a=>{if(a===0)return 1;switch(Math.abs(a)/We){case 1:case 3:return 0;case 2:return-1}return Math.cos(a)},ce=a=>{if(a===0)return 0;const t=a/We,e=Math.sign(a);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(a)};class C{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new C(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new C(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new C(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new C(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new C(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new C(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new C(this.x/t.x,this.y/t.y)}scalarDivide(t){return new C(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new C(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new C(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new C(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new C(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nr;const s=ce(t),i=le(t),n=this.subtract(e);return new C(n.x*i-n.y*s,n.x*s+n.y*i).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new C(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const nr=new C(0,0),Oi=a=>!!a&&Array.isArray(a._objects);function zo(a){class t extends a{constructor(){super(...arguments),x(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach((o=>this._onObjectAdded(o))),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach((o=>this._onObjectAdded(o))),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return r.forEach((h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),i.push(h),this._onObjectRemoved(h))})),i}forEachObject(s){this.getObjects().forEach(((i,n,r)=>s(i,n,r)))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter((r=>r.isType(...i)))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some((n=>n instanceof t&&n.contains(s,!0)))}complexity(){return this._objects.reduce(((s,i)=>s+=i.complexity?i.complexity():0),0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(ss(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(ss(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==0){const r=this.findNewLowerIndex(s,n,i);return ss(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==this._objects.length-1){const r=this.findNewUpperIndex(s,n,i);return ss(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(ss(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let o=i-1;o>=0;--o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let o=i+1;o<this._objects.length;++o)if(s.isOverlapping(this._objects[o])){r=o;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:o}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],c=new C(i,n),u=c.add(new C(r,o));for(let d=this._objects.length-1;d>=0;d--){const f=this._objects[d];f.selectable&&f.visible&&(h&&f.intersectsWithRect(c,u)||f.isContainedWithinRect(c,u)||h&&f.containsPoint(c)||h&&f.containsPoint(u))&&l.push(f)}return l}}return t}class Go extends fc{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function Ks(a){return Ys().requestAnimationFrame(a)}function Vo(a){return Ys().cancelAnimationFrame(a)}let gc=0;const Ue=()=>gc++,Se=()=>{const a=xs().createElement("canvas");if(!a||a.getContext===void 0)throw new we("Failed to create `canvas` element");return a},Wo=()=>xs().createElement("img"),te=a=>{const t=Se();return t.width=a.width,t.height=a.height,t},rr=(a,t,e)=>a.toDataURL("image/".concat(t),e),or=(a,t,e)=>new Promise(((s,i)=>{a.toBlob(s,"image/".concat(t),e)})),pt=a=>a*Zn,Ce=a=>a/Zn,Xo=a=>a.every(((t,e)=>t===jt[e])),Ot=(a,t,e)=>new C(a).transform(t,e),qt=a=>{const t=1/(a[0]*a[3]-a[1]*a[2]),e=[t*a[3],-t*a[1],-t*a[2],t*a[0],0,0],{x:s,y:i}=new C(a[4],a[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},vt=(a,t,e)=>[a[0]*t[0]+a[2]*t[1],a[1]*t[0]+a[3]*t[1],a[0]*t[2]+a[2]*t[3],a[1]*t[2]+a[3]*t[3],e?0:a[0]*t[4]+a[2]*t[5]+a[4],e?0:a[1]*t[4]+a[3]*t[5]+a[5]],Di=(a,t)=>a.reduceRight(((e,s)=>s&&e?vt(s,e,t):s||e),void 0)||jt.concat(),Uo=a=>{let[t,e]=a;return Math.atan2(e,t)},is=a=>{const t=Uo(a),e=Math.pow(a[0],2)+Math.pow(a[1],2),s=Math.sqrt(e),i=(a[0]*a[3]-a[2]*a[1])/s,n=Math.atan2(a[0]*a[2]+a[1]*a[3],e);return{angle:Ce(t),scaleX:s,scaleY:i,skewX:Ce(n),skewY:0,translateX:a[4]||0,translateY:a[5]||0}},Ts=function(a){return[1,0,0,1,a,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function ns(){let{angle:a=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=pt(a),i=le(s),n=ce(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Ri=function(a){return[a,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:a,0,0]},Yo=a=>Math.tan(pt(a)),ar=a=>[1,0,Yo(a),1,0,0],hr=a=>[1,Yo(a),0,1,0,0],Js=a=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=a,o=Ri(s?-t:t,i?-e:e);return n&&(o=vt(o,ar(n),!0)),r&&(o=vt(o,hr(r),!0)),o},$o=a=>{const{translateX:t=0,translateY:e=0,angle:s=0}=a;let i=Ts(t,e);s&&(i=vt(i,ns({angle:s})));const n=Js(a);return Xo(n)||(i=vt(i,n)),i},Zs=function(a){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((function(s,i){if(t&&t.aborted)return i(new Kn("loadImage"));const n=Wo();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const o=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};a?(n.onload=o,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new we("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=a):o()}))},Es=function(a){let{signal:t,reviver:e=es}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(((s,i)=>{const n=[];t&&t.addEventListener("abort",i,{once:!0}),Promise.all(a.map((r=>L.getClass(r.type).fromObject(r,{signal:t}).then((o=>(e(r,o),n.push(o),o)))))).then(s).catch((r=>{n.forEach((o=>{o.dispose&&o.dispose()})),i(r)})).finally((()=>{t&&t.removeEventListener("abort",i)}))}))},Qs=function(a){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(((e,s)=>{const i=[];t&&t.addEventListener("abort",s,{once:!0});const n=Object.values(a).map((o=>o&&o.type&&L.has(o.type)?Es([o],{signal:t}).then((h=>{let[l]=h;return i.push(l),l})):o)),r=Object.keys(a);Promise.all(n).then((o=>o.reduce(((h,l,c)=>(h[r[c]]=l,h)),{}))).then(e).catch((o=>{i.forEach((h=>{h.dispose&&h.dispose()})),s(o)})).finally((()=>{t&&t.removeEventListener("abort",s)}))}))},rs=function(a){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce(((t,e)=>(e in a&&(t[e]=a[e]),t)),{})},lr=(a,t)=>Object.keys(a).reduce(((e,s)=>(t(a[s],s,a)&&(e[s]=a[s]),e)),{}),ot=(a,t)=>parseFloat(Number(a).toFixed(t)),ks=a=>"matrix("+a.map((t=>ot(t,et.NUM_FRACTION_DIGITS))).join(" ")+")",re=a=>!!a&&a.toLive!==void 0,qo=a=>!!a&&typeof a.toObject=="function",Ko=a=>!!a&&a.offsetX!==void 0&&"source"in a,os=a=>!!a&&"multiSelectionStacking"in a;function Jo(a){const t=a&&ue(a);let e=0,s=0;if(!a||!t)return{left:e,top:s};let i=a;const n=t.documentElement,r=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(e=r.scrollLeft||n.scrollLeft||0,s=r.scrollTop||n.scrollTop||0):(e+=i.scrollLeft||0,s+=i.scrollTop||0),i.nodeType!==1||i.style.position!=="fixed"););return{left:e,top:s}}const ue=a=>a.ownerDocument||null,Zo=a=>{var t;return((t=a.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Qo=function(a,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;a.width=s,a.height=i,n>1&&(a.setAttribute("width",(s*n).toString()),a.setAttribute("height",(i*n).toString()),t.scale(n,n))},cr=(a,t)=>{let{width:e,height:s}=t;e&&(a.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(a.style.height=typeof s=="number"?"".concat(s,"px"):s)};function ta(a){return a.onselectstart!==void 0&&(a.onselectstart=()=>!1),a.style.userSelect=Bt,a}class ea{constructor(t){x(this,"_originalCanvasStyle",void 0),x(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&xs().getElementById(t)||Se();var s;if(e.hasAttribute("data-fabric"))throw new we("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;Qo(s,i,t,e)}setCSSDimensions(t){cr(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&ue(t),i={left:0,top:0};if(!s)return i;const n=((e=Zo(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=Jo(t);return{left:r.left+h.left-(o.clientLeft||0)+i.left,top:r.top+h.top-(o.clientTop||0)+i.top}})(this.lower.el)}dispose(){xe().dispose(this.lower.el),delete this.lower}}const pc={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...jt]},mc=["objects"];class ti extends zo(Go){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return ti.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new ea(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(De("warn",`Canvas is trying to add an object that belongs to a different canvas.
8
+ Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?No():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i=w({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=Ot(t,qt(i));i[0]=e,i[3]=e;const r=Ot(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new C(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new C(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(t){t.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor="",this.overlayColor="",this.clearContext(this.getContext()),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=Ks((()=>this.renderAndReset())))}calcViewportBoundaries(){const t=this.width,e=this.height,s=qt(this.viewportTransform),i=Ot({x:0,y:0},s),n=Ot({x:t,y:e},s),r=i.min(n),o=i.max(n);return this.vptCoords={tl:r,tr:new C(o.x,r.y),bl:new C(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(Vo(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,i=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),i&&(i._set("canvas",this),i.shouldCache(),i._transformDone=!0,i.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,i)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,i=e.length;s<i;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],i=this["".concat(e,"Image")],n=this.viewportTransform,r=this["".concat(e,"Vpt")];if(!s&&!i)return;const o=re(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=o?s.toLive(t):s,r&&t.transform(...n),o){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new C(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new C(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new C(t.getCenterPoint().x,this.getCenterPoint().y))}centerObject(t){return this._centerObject(t,this.getCenterPoint())}viewportCenterObject(t){return this._centerObject(t,this.getVpCenter())}viewportCenterObjectH(t){return this._centerObject(t,new C(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new C(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Ot(this.getCenterPoint(),qt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,$,$),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,i=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return w(w(w({version:Jn},rs(this,e)),{},{objects:this._objects.filter((n=>!n.excludeFromExport)).map((n=>this._toObject(n,t,e)))},this.__serializeBgOverlay(t,e)),i?{clipPath:i}:null)}_toObject(t,e,s){let i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!i),n}__serializeBgOverlay(t,e){const s={},i=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,o=this.overlayColor;return re(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),re(o)?o.excludeFromExport||(s.overlay=o.toObject(e)):o&&(s.overlay=o),i&&!i.excludeFromExport&&(s.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(s.overlayImage=this._toObject(n,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
9
9
  `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
10
10
  `),this._setSVGBgOverlayColor(s,"overlay"),this._setSVGBgOverlayImage(s,"overlayImage",e),s.push("</svg>"),s.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",`" standalone="no" ?>
11
11
  `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
@@ -21,15 +21,15 @@ Resulting to default behavior: removing object from previous canvas and adding t
21
21
  }
22
22
  `))).join("");return i?` <style type="text/css"><![CDATA[
23
23
  `.concat(i,`]]></style>
24
- `):""}_setSVGObjects(t,e){this.forEachObject((s=>{s.excludeFromExport||this._setSVGObject(t,s,e)}))}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(re(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?ks($t(this.viewportTransform)):"";t.push('<rect transform="'.concat(o," translate(").concat(n/2,",").concat(r/2,')" x="').concat(s.offsetX-n/2,'" y="').concat(s.offsetY-r/2,'" width="').concat(i!=="repeat-y"&&i!=="no-repeat"||!Ko(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!Ko(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
24
+ `):""}_setSVGObjects(t,e){this.forEachObject((s=>{s.excludeFromExport||this._setSVGObject(t,s,e)}))}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(re(s)){const i=s.repeat||"",n=this.width,r=this.height,o=this["".concat(e,"Vpt")]?ks(qt(this.viewportTransform)):"";t.push('<rect transform="'.concat(o," translate(").concat(n/2,",").concat(r/2,')" x="').concat(s.offsetX-n/2,'" y="').concat(s.offsetY-r/2,'" width="').concat(i!=="repeat-y"&&i!=="no-repeat"||!Ko(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!Ko(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
25
25
  `))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
26
- `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new we("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[]}=i,r=lt(i,mc),{backgroundImage:o,background:h,overlayImage:l,overlay:c,clipPath:u}=r,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Es(n,{reviver:e,signal:s}),Qs({backgroundImage:o,backgroundColor:h,overlayImage:l,overlayColor:c,clipPath:u},{signal:s})]).then((f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(r),this.set(p),this.renderOnAddRemove=d,this}))}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=te(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return rr(this.toCanvasElement(r,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return or(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const o=(e||this.width)*t,h=(s||this.height)*t,l=this.getZoom(),c=this.width,u=this.height,d=this.skipControlsDrawing,f=l*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],b=this.enableRetinaScaling,m=te({width:o,height:h}),v=r?this._objects.filter((y=>r(y))):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),v),this.viewportTransform=g,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=b,this.skipControlsDrawing=d,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Pi.cancelByCanvas(this),this.disposed=!0,new Promise(((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()}))}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject((t=>t.dispose())),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}x(ti,"ownDefaults",pc);const bc=["touchstart","touchmove","touchend"],sa=a=>{const t=Jo(a.target),e=(function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s})(a);return new C(e.clientX+t.left,e.clientY+t.top)},Li=a=>bc.includes(a.type)||a.pointerType==="touch",ia=a=>{a.preventDefault(),a.stopPropagation()},Ae=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},vc=["translateX","translateY","scaleX","scaleY"],na=(a,t)=>Ms(a,vt(t,a.calcOwnMatrix())),Ms=(a,t)=>{const e=is(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=lt(e,vc),h=new C(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,$,$)},ra=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},ur=a=>({scaleX:a.scaleX,scaleY:a.scaleY,skewX:a.skewX,skewY:a.skewY,angle:a.angle,left:a.left,flipX:a.flipX,flipY:a.flipY,top:a.top}),Fi=(a,t,e)=>{const s=a/2,i=t/2,n=[new C(-s,-i),new C(s,-i),new C(-s,i),new C(s,i)].map((o=>o.transform(e))),r=Ae(n);return new C(r.width,r.height)},ei=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Nt;return vt($t(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Nt),a)},as=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Nt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Nt;return a.transform(ei(t,e))},oa=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Nt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Nt;return a.transform(ei(t,e),!0)},dr=(a,t,e)=>{const s=ei(t,e);return Ms(a,vt(s,a.calcOwnMatrix())),s},aa=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),w(w({},t),{},{target:s})),s.fire(a,t)},yc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},xt=a=>typeof a=="string"?yc[a]:a-.5,Ii="not-allowed";function ha(a){return xt(a.originX)===xt($)&&xt(a.originY)===xt($)}function la(a){return .5-xt(a)}const de=(a,t)=>a[t],ca=(a,t,e,s)=>({e:a,transform:t,pointer:new C(e,s)});function ua(a,t){const e=a.getTotalAngle()+Ce(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function fr(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],l=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/l,u=(function(d,f,g,p){const b=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(b,$,$,g,p):new C(d.left,d.top);return(d.angle?f.rotate(-pt(d.angle),b):f).subtract(m)})(r,new C(s,i),t,e);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=h.offsetX,u.y-=h.offsetY,u}const _c=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!de(i,"lockMovementX")&&i.left!==o,c=!de(i,"lockMovementY")&&i.top!==h;return l&&i.set(it,o),c&&i.set(Yt,h),(l||c)&&aa(jo,ca(a,t,e,s)),l||c},Ni=a=>a.replace(/\s+/g," "),da={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#F0F",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#639",red:"#F00",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},gr=(a,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?a+6*(t-a)*e:e<.5?t:e<2/3?a+(t-a)*(2/3-e)*6:a),fa=(a,t,e,s)=>{a/=255,t/=255,e/=255;const i=Math.max(a,t,e),n=Math.min(a,t,e);let r,o;const h=(i+n)/2;if(i===n)r=o=0;else{const l=i-n;switch(o=h>.5?l/(2-i-n):l/(i+n),i){case a:r=(t-e)/l+(t<e?6:0);break;case t:r=(e-a)/l+2;break;case e:r=(a-t)/l+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},ga=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},ji=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),pa=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class nt{constructor(t){if(x(this,"isUnrecognised",!1),t)if(t instanceof nt)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,i,n=1]=t;this.setSource([e,s,i,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in da&&(t=da[t]),t==="transparent"?[255,255,255,0]:nt.sourceFromHex(t)||nt.sourceFromRgb(t)||nt.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=fa(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=fa(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(ji(t)).concat(ji(e)).concat(ji(s)).concat(ji(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(pa(this.getSource())),this}toBlackWhite(t){const[e,,,s]=pa(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof nt||(t=new nt(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map(((o,h)=>Math.round(.5*o+.5*s[h])));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return nt.fromRgba(t)}static fromRgba(t){return new nt(nt.sourceFromRgb(t))}static sourceFromRgb(t){const e=Ni(t).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(e){const[s,i,n]=e.slice(1,4).map((r=>{const o=parseFloat(r);return r.endsWith("%")?Math.round(2.55*o):o}));return[s,i,n,ga(e[4])]}}static fromHsl(t){return nt.fromHsla(t)}static fromHsla(t){return new nt(nt.sourceFromHsl(t))}static sourceFromHsl(t){const e=Ni(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!e)return;const s=(nt.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,h;if(i===0)r=o=h=n;else{const l=n<=.5?n*(i+1):n+i-n*i,c=2*n-l;r=gr(c,l,s+1/3),o=gr(c,l,s),h=gr(c,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),ga(e[4])]}static fromHex(t){return new nt(nt.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map((h=>h+h)):e.match(/.{2}/g);const[i,n,r,o=255]=s.map((h=>parseInt(h,16)));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?Ce(s):e.includes("turn")?360*s:s}}const zt=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qn;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=et.DPI;switch(e?.[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},pr=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==jt?[n.slice(1,4),n.slice(5,8)]:n===jt?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},si=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new nt(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(a,": ").concat(e,"; ").concat(s?"".concat(a,"-opacity: ").concat(s,"; "):""):"".concat(a,'="').concat(e,'" ').concat(s?"".concat(a,'-opacity="').concat(s,'" '):"")};class ma{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):jt,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=si(wt,this.fill);return[si(Ht,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",e,"; ","opacity: ",l,";",u,c].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(ks(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),o=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let b;h&&(h.clipPathId="CLIPPATH_".concat(Ue()),b='<clipPath id="'.concat(h.clipPathId,`" >
26
+ `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new we("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[]}=i,r=ct(i,mc),{backgroundImage:o,background:h,overlayImage:l,overlay:c,clipPath:u}=r,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Es(n,{reviver:e,signal:s}),Qs({backgroundImage:o,backgroundColor:h,overlayImage:l,overlayColor:c,clipPath:u},{signal:s})]).then((f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(r),this.set(p),this.renderOnAddRemove=d,this}))}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=te(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return rr(this.toCanvasElement(r,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return or(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const o=(e||this.width)*t,h=(s||this.height)*t,l=this.getZoom(),c=this.width,u=this.height,d=this.skipControlsDrawing,f=l*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],b=this.enableRetinaScaling,m=te({width:o,height:h}),v=r?this._objects.filter((y=>r(y))):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=o,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),v),this.viewportTransform=g,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=b,this.skipControlsDrawing=d,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Pi.cancelByCanvas(this),this.disposed=!0,new Promise(((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()}))}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject((t=>t.dispose())),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}x(ti,"ownDefaults",pc);const bc=["touchstart","touchmove","touchend"],sa=a=>{const t=Jo(a.target),e=(function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s})(a);return new C(e.clientX+t.left,e.clientY+t.top)},Li=a=>bc.includes(a.type)||a.pointerType==="touch",ia=a=>{a.preventDefault(),a.stopPropagation()},Ae=a=>{let t=0,e=0,s=0,i=0;for(let n=0,r=a.length;n<r;n++){const{x:o,y:h}=a[n];(o>s||!n)&&(s=o),(o<t||!n)&&(t=o),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},vc=["translateX","translateY","scaleX","scaleY"],na=(a,t)=>Ms(a,vt(t,a.calcOwnMatrix())),Ms=(a,t)=>{const e=is(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,o=ct(e,vc),h=new C(s,i);a.flipX=!1,a.flipY=!1,Object.assign(a,o),a.set({scaleX:n,scaleY:r}),a.setPositionByOrigin(h,$,$)},ra=a=>{a.scaleX=1,a.scaleY=1,a.skewX=0,a.skewY=0,a.flipX=!1,a.flipY=!1,a.rotate(0)},ur=a=>({scaleX:a.scaleX,scaleY:a.scaleY,skewX:a.skewX,skewY:a.skewY,angle:a.angle,left:a.left,flipX:a.flipX,flipY:a.flipY,top:a.top}),Fi=(a,t,e)=>{const s=a/2,i=t/2,n=[new C(-s,-i),new C(s,-i),new C(-s,i),new C(s,i)].map((o=>o.transform(e))),r=Ae(n);return new C(r.width,r.height)},ei=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jt;return vt(qt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:jt),a)},as=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:jt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jt;return a.transform(ei(t,e))},oa=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:jt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jt;return a.transform(ei(t,e),!0)},dr=(a,t,e)=>{const s=ei(t,e);return Ms(a,vt(s,a.calcOwnMatrix())),s},aa=(a,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(a),w(w({},t),{},{target:s})),s.fire(a,t)},yc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},xt=a=>typeof a=="string"?yc[a]:a-.5,Ii="not-allowed";function ha(a){return xt(a.originX)===xt($)&&xt(a.originY)===xt($)}function la(a){return .5-xt(a)}const de=(a,t)=>a[t],ca=(a,t,e,s)=>({e:a,transform:t,pointer:new C(e,s)});function ua(a,t){const e=a.getTotalAngle()+Ce(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function fr(a,t,e,s,i){var n;let{target:r,corner:o}=a;const h=r.controls[o],l=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/l,u=(function(d,f,g,p){const b=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(b,$,$,g,p):new C(d.left,d.top);return(d.angle?f.rotate(-pt(d.angle),b):f).subtract(m)})(r,new C(s,i),t,e);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=h.offsetX,u.y-=h.offsetY,u}const _c=(a,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,o=e-n,h=s-r,l=!de(i,"lockMovementX")&&i.left!==o,c=!de(i,"lockMovementY")&&i.top!==h;return l&&i.set(it,o),c&&i.set($t,h),(l||c)&&aa(jo,ca(a,t,e,s)),l||c},Ni=a=>a.replace(/\s+/g," "),da={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#F0F",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#639",red:"#F00",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},gr=(a,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?a+6*(t-a)*e:e<.5?t:e<2/3?a+(t-a)*(2/3-e)*6:a),fa=(a,t,e,s)=>{a/=255,t/=255,e/=255;const i=Math.max(a,t,e),n=Math.min(a,t,e);let r,o;const h=(i+n)/2;if(i===n)r=o=0;else{const l=i-n;switch(o=h>.5?l/(2-i-n):l/(i+n),i){case a:r=(t-e)/l+(t<e?6:0);break;case t:r=(e-a)/l+2;break;case e:r=(a-t)/l+4}r/=6}return[Math.round(360*r),Math.round(100*o),Math.round(100*h),s]},ga=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(a)/(a.endsWith("%")?100:1)},ji=a=>Math.min(Math.round(a),255).toString(16).toUpperCase().padStart(2,"0"),pa=a=>{let[t,e,s,i=1]=a;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class nt{constructor(t){if(x(this,"isUnrecognised",!1),t)if(t instanceof nt)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,i,n=1]=t;this.setSource([e,s,i,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in da&&(t=da[t]),t==="transparent"?[255,255,255,0]:nt.sourceFromHex(t)||nt.sourceFromRgb(t)||nt.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=fa(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=fa(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(ji(t)).concat(ji(e)).concat(ji(s)).concat(ji(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(pa(this.getSource())),this}toBlackWhite(t){const[e,,,s]=pa(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof nt||(t=new nt(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map(((o,h)=>Math.round(.5*o+.5*s[h])));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return nt.fromRgba(t)}static fromRgba(t){return new nt(nt.sourceFromRgb(t))}static sourceFromRgb(t){const e=Ni(t).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(e){const[s,i,n]=e.slice(1,4).map((r=>{const o=parseFloat(r);return r.endsWith("%")?Math.round(2.55*o):o}));return[s,i,n,ga(e[4])]}}static fromHsl(t){return nt.fromHsla(t)}static fromHsla(t){return new nt(nt.sourceFromHsl(t))}static sourceFromHsl(t){const e=Ni(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!e)return;const s=(nt.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,o,h;if(i===0)r=o=h=n;else{const l=n<=.5?n*(i+1):n+i-n*i,c=2*n-l;r=gr(c,l,s+1/3),o=gr(c,l,s),h=gr(c,l,s-1/3)}return[Math.round(255*r),Math.round(255*o),Math.round(255*h),ga(e[4])]}static fromHex(t){return new nt(nt.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map((h=>h+h)):e.match(/.{2}/g);const[i,n,r,o=255]=s.map((h=>parseInt(h,16)));return[i,n,r,o/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?Ce(s):e.includes("turn")?360*s:s}}const Gt=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Qn;const e=/\D{0,2}$/.exec(a),s=parseFloat(a),i=et.DPI;switch(e?.[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},pr=a=>{const[t,e]=a.trim().split(" "),[s,i]=(n=t)&&n!==Bt?[n.slice(1,4),n.slice(5,8)]:n===Bt?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},si=function(a,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new nt(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(a,": ").concat(e,"; ").concat(s?"".concat(a,"-opacity: ").concat(s,"; "):""):"".concat(a,'="').concat(e,'" ').concat(s?"".concat(a,'-opacity="').concat(s,'" '):"")};class ma{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Bt,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=si(wt,this.fill);return[si(zt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",e,"; ","opacity: ",l,";",u,c].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(ks(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),o=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let b;h&&(h.clipPathId="CLIPPATH_".concat(Ue()),b='<clipPath id="'.concat(h.clipPathId,`" >
27
27
  `).concat(h.toClipPathSVG(s),`</clipPath>
28
28
  `)),c&&g.push("<g ",o,this.getSvgCommons(),` >
29
29
  `),g.push("<g ",this.getSvgTransform(!1),c?"":o+this.getSvgCommons(),` >
30
30
  `);const m=[r,l,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,re(d)&&g.push(d.toSVG(this)),re(u)&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(b),g.push(t.join("")),g.push(`</g>
31
31
  `),c&&g.push(`</g>
32
- `),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==wt?' paint-order="'.concat(this.paintFirst,'" '):""}}function Bi(a){return new RegExp("^("+a.join("|")+")\\b","i")}const hs="textDecorationThickness",ba=["fontSize","fontWeight","fontFamily","fontStyle"],va=["underline","overline","linethrough"],ya=[...ba,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_a=[...ya,...va,"textBackgroundColor","direction",hs],wc=[...ba,...va,Ht,"strokeWidth",wt,"deltaY","textBackgroundColor",hs],xc={_reNewline:er,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:it,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:it,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[hs]:66.667},Te="justify",Hi="justify-left",ii="justify-right",ni="justify-center";var wa,xa,Sa;const fe=String.raw(wa||(wa=_e(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),mr=String.raw(xa||(xa=_e(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),br="http://www.w3.org/2000/svg",Sc=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+fe+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+fe+"))?\\s+(.*)"),Cc={cx:it,x:it,r:"radius",cy:Yt,y:Yt,display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing","text-decoration-thickness":hs},vr="font-size",yr="clip-path",Ac=Bi(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Tc=Bi(["symbol","image","marker","pattern","view","svg"]),Ca=Bi(["symbol","g","a","svg","clipPath","defs"]),Aa=new RegExp(String.raw(Sa||(Sa=_e(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),fe,mr,fe,mr,fe,mr,fe)),Ec=new C(1,0),Ta=new C,_r=(a,t)=>a.rotate(t),zi=(a,t)=>new C(t).subtract(a),Gi=a=>a.distanceFrom(Ta),Vi=(a,t)=>Math.atan2(Ps(a,t),ka(a,t)),Ea=a=>Vi(Ec,a),Wi=a=>a.eq(Ta)?a:a.scalarDivide(Gi(a)),wr=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Wi(new C(-a.y,a.x).scalarMultiply(t?1:-1))},Ps=(a,t)=>a.x*t.y-a.y*t.x,ka=(a,t)=>a.x*t.x+a.y*t.y,xr=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Ps(t,e),i=Ps(t,a),n=Ps(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Ma="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Pa=new RegExp("(?:\\s|^)"+Ma+Ma+"("+fe+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Le{constructor(t){const e=typeof t=="string"?Le.parseShadow(t):t;Object.assign(this,Le.ownDefaults,e),this.id=Ue()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Pa.exec(e)||[]).map((r=>parseFloat(r)||0));return{color:(e.replace(Pa,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:i,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=_r(new C(this.offsetX,this.offsetY),pt(-t.angle)),s=new nt(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*ot((Math.abs(e.x)+this.blur)/t.width,et.NUM_FRACTION_DIGITS)+20,n=100*ot((Math.abs(e.y)+this.blur)/t.height,et.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
32
+ `),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==wt?' paint-order="'.concat(this.paintFirst,'" '):""}}function Bi(a){return new RegExp("^("+a.join("|")+")\\b","i")}const hs="textDecorationThickness",ba=["fontSize","fontWeight","fontFamily","fontStyle"],va=["underline","overline","linethrough"],ya=[...ba,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_a=[...ya,...va,"textBackgroundColor","direction",hs],wc=[...ba,...va,zt,"strokeWidth",wt,"deltaY","textBackgroundColor",hs],xc={_reNewline:er,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:it,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:it,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[hs]:66.667},Te="justify",Hi="justify-left",ii="justify-right",ni="justify-center";var wa,xa,Sa;const fe=String.raw(wa||(wa=_e(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),mr=String.raw(xa||(xa=_e(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),br="http://www.w3.org/2000/svg",Sc=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+fe+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+fe+"))?\\s+(.*)"),Cc={cx:it,x:it,r:"radius",cy:$t,y:$t,display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing","text-decoration-thickness":hs},vr="font-size",yr="clip-path",Ac=Bi(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Tc=Bi(["symbol","image","marker","pattern","view","svg"]),Ca=Bi(["symbol","g","a","svg","clipPath","defs"]),Aa=new RegExp(String.raw(Sa||(Sa=_e(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),fe,mr,fe,mr,fe,mr,fe)),Ec=new C(1,0),Ta=new C,_r=(a,t)=>a.rotate(t),zi=(a,t)=>new C(t).subtract(a),Gi=a=>a.distanceFrom(Ta),Vi=(a,t)=>Math.atan2(Ps(a,t),ka(a,t)),Ea=a=>Vi(Ec,a),Wi=a=>a.eq(Ta)?a:a.scalarDivide(Gi(a)),wr=function(a){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Wi(new C(-a.y,a.x).scalarMultiply(t?1:-1))},Ps=(a,t)=>a.x*t.y-a.y*t.x,ka=(a,t)=>a.x*t.x+a.y*t.y,xr=(a,t,e)=>{if(a.eq(t)||a.eq(e))return!0;const s=Ps(t,e),i=Ps(t,a),n=Ps(e,a);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},Ma="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Pa=new RegExp("(?:\\s|^)"+Ma+Ma+"("+fe+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Le{constructor(t){const e=typeof t=="string"?Le.parseShadow(t):t;Object.assign(this,Le.ownDefaults,e),this.id=Ue()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(Pa.exec(e)||[]).map((r=>parseFloat(r)||0));return{color:(e.replace(Pa,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:i,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=_r(new C(this.offsetX,this.offsetY),pt(-t.angle)),s=new nt(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*ot((Math.abs(e.x)+this.blur)/t.width,et.NUM_FRACTION_DIGITS)+20,n=100*ot((Math.abs(e.y)+this.blur)/t.height,et.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
33
33
  <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(ot(this.blur?this.blur/2:0,et.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
34
34
  <feOffset dx="`).concat(ot(e.x,et.NUM_FRACTION_DIGITS),'" dy="').concat(ot(e.y,et.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
35
35
  <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
@@ -39,44 +39,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
39
39
  <feMergeNode in="SourceGraphic"></feMergeNode>
40
40
  </feMerge>
41
41
  </filter>
42
- `)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Le.ownDefaults;return this.includeDefaultValues?t:lr(t,((s,i)=>s!==e[i]))}static async fromObject(t){return new this(t)}}x(Le,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),x(Le,"type","shadow"),L.setClass(Le,"shadow");const ls=(a,t,e)=>Math.max(a,Math.min(t,e)),kc=[Yt,it,Bt,Qt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ss,Cs],Fe=[wt,Ht,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Mc={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:it,originY:Yt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:wt,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},Sr=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/Re*Math.asin(1):e/Re*Math.asin(t/a),{a,c:t,p:e,s}),Oa=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Re/e),Da=(a,t,e,s)=>-e*Math.cos(a/s*We)+e+t,Cr=(a,t,e,s)=>(a/=s)<1/2.75?e*(7.5625*a*a)+t:a<2/2.75?e*(7.5625*(a-=1.5/2.75)*a+.75)+t:a<2.5/2.75?e*(7.5625*(a-=2.25/2.75)*a+.9375)+t:e*(7.5625*(a-=2.625/2.75)*a+.984375)+t,Ra=(a,t,e,s)=>e-Cr(s-a,0,e,s)+t;var Pc=Object.freeze({__proto__:null,defaultEasing:Da,easeInBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(a/=s)*a*((i+1)*a-i)+t},easeInBounce:Ra,easeInCirc:(a,t,e,s)=>-e*(Math.sqrt(1-(a/=s)*a)-1)+t,easeInCubic:(a,t,e,s)=>e*(a/s)**3+t,easeInElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h}=Sr(i,e,n,1.70158);return-Oa(r,o,h,a,s)+t},easeInExpo:(a,t,e,s)=>a===0?t:e*2**(10*(a/s-1))+t,easeInOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(a/=s/2)<1?e/2*(a*a*((1+(i*=1.525))*a-i))+t:e/2*((a-=2)*a*((1+(i*=1.525))*a+i)+2)+t},easeInOutBounce:(a,t,e,s)=>a<s/2?.5*Ra(2*a,0,e,s)+t:.5*Cr(2*a-s,0,e,s)+.5*e+t,easeInOutCirc:(a,t,e,s)=>(a/=s/2)<1?-e/2*(Math.sqrt(1-a**2)-1)+t:e/2*(Math.sqrt(1-(a-=2)*a)+1)+t,easeInOutCubic:(a,t,e,s)=>(a/=s/2)<1?e/2*a**3+t:e/2*((a-2)**3+2)+t,easeInOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:o,p:h,c:l}=Sr(i,e,n,1.70158);return a<1?-.5*Oa(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*Re/h)*.5+l+t},easeInOutExpo:(a,t,e,s)=>a===0?t:a===s?t+e:(a/=s/2)<1?e/2*2**(10*(a-1))+t:e/2*-(2**(-10*--a)+2)+t,easeInOutQuad:(a,t,e,s)=>(a/=s/2)<1?e/2*a**2+t:-e/2*(--a*(a-2)-1)+t,easeInOutQuart:(a,t,e,s)=>(a/=s/2)<1?e/2*a**4+t:-e/2*((a-=2)*a**3-2)+t,easeInOutQuint:(a,t,e,s)=>(a/=s/2)<1?e/2*a**5+t:e/2*((a-2)**5+2)+t,easeInOutSine:(a,t,e,s)=>-e/2*(Math.cos(Math.PI*a/s)-1)+t,easeInQuad:(a,t,e,s)=>e*(a/=s)*a+t,easeInQuart:(a,t,e,s)=>e*(a/=s)*a**3+t,easeInQuint:(a,t,e,s)=>e*(a/s)**5+t,easeInSine:(a,t,e,s)=>-e*Math.cos(a/s*We)+e+t,easeOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((a=a/s-1)*a*((i+1)*a+i)+1)+t},easeOutBounce:Cr,easeOutCirc:(a,t,e,s)=>e*Math.sqrt(1-(a=a/s-1)*a)+t,easeOutCubic:(a,t,e,s)=>e*((a/s-1)**3+1)+t,easeOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h,c:l}=Sr(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*Re/h)+l+t},easeOutExpo:(a,t,e,s)=>a===s?t+e:e*-(2**(-10*a/s)+1)+t,easeOutQuad:(a,t,e,s)=>-e*(a/=s)*(a-2)+t,easeOutQuart:(a,t,e,s)=>-e*((a=a/s-1)*a**3-1)+t,easeOutQuint:(a,t,e,s)=>e*((a/s-1)**5+1)+t,easeOutSine:(a,t,e,s)=>e*Math.sin(a/s*We)+t});const Oc=()=>!1;class Ar{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Da,onStart:o=es,onChange:h=es,onComplete:l=es,abort:c=Oc,target:u}=t;x(this,"_state","pending"),x(this,"durationProgress",0),x(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=c,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout((()=>Ks(t)),this.delay):Ks(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:i,valueProgress:n}=this.calculate(s);this.value=Object.freeze(i),this.valueProgress=n,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),Ks(this.tick)))}register(){Pi.push(this)}unregister(){Pi.remove(this)}abort(){this._state="aborted",this.unregister()}}const Dc=["startValue","endValue"];class Rc extends Ar{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(w(w({},lt(t,Dc)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const Lc=["startValue","endValue"];class Fc extends Ar{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(w(w({},lt(t,Lc)),{},{startValue:e,byValue:s.map(((i,n)=>i-e[n]))}))}calculate(t){const e=this.startValue.map(((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i)));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const Ic=["startValue","endValue","easing","onChange","onComplete","abort"],Nc=(a,t,e,s)=>t+e*(1-Math.cos(a/s*We)),Tr=a=>a&&((t,e,s)=>a(new nt(t).toRgba(),e,s));class jc extends Ar{constructor(t){let{startValue:e,endValue:s,easing:i=Nc,onChange:n,onComplete:r,abort:o}=t,h=lt(t,Ic);const l=new nt(e).getSource(),c=new nt(s).getSource();super(w(w({},h),{},{startValue:l,byValue:c.map(((u,d)=>u-l[d])),easing:i,onChange:Tr(n),onComplete:Tr(r),abort:Tr(o)}))}calculate(t){const[e,s,i,n]=this.startValue.map(((o,h)=>this.easing(t,o,this.byValue[h],this.duration,h))),r=[...[e,s,i].map(Math.round),ls(0,n,1)];return{value:r,valueProgress:r.map(((o,h)=>this.byValue[h]!==0?Math.abs((o-this.startValue[h])/this.byValue[h]):0)).find((o=>o!==0))||0}}}function Er(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Fc(a):new Rc(a);return t.start(),t}function La(a){const t=new jc(a);return t.start(),t}class gt{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some((e=>e.eq(t)))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter((i=>!this.includes(i)))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=zi(e,s),r=zi(e,t).divide(n);return i?Math.abs(r.x)===Math.abs(r.y):r.x===r.y&&r.x>=0&&r.x<=1}}static isPointInPolygon(t,e){const s=new C(t).setX(Math.min(t.x-1,...e.map((n=>n.x))));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const o=e.x-t.x,h=e.y-t.y,l=i.x-s.x,c=i.y-s.y,u=t.x-s.x,d=t.y-s.y,f=l*d-c*u,g=o*d-h*u,p=c*o-l*h;if(p!==0){const b=f/p,m=g/p;return(n||0<=b&&b<=1)&&(r||0<=m&&m<=1)?new gt("Intersection").append(new C(t.x+b*o,t.y+b*h)):new gt}if(f===0||g===0){const b=n||r||gt.isPointContained(t,s,i)||gt.isPointContained(e,s,i)||gt.isPointContained(s,t,e)||gt.isPointContained(i,t,e);return new gt(b?"Coincident":void 0)}return new gt("Parallel")}static intersectSegmentLine(t,e,s,i){return gt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return gt.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new gt,r=s.length;for(let o,h,l,c=0;c<r;c++){if(o=s[c],h=s[(c+1)%r],l=gt.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return gt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new gt,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=gt.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new gt("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new C(n.x,i.y),o=new C(i.x,n.y);return gt.intersectPolygonPolygon(t,[i,r,n,o])}}class Bc extends Go{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?Mt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Mt(t,$t(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new C(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map((o=>Mt(o,r)))}return n}intersectsWithRect(t,e){return gt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=gt.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every((e=>t.containsPoint(e)))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return gt.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some((s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y))||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every((s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y)))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Ae(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Bt,t),this._set(Qt,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?Ce(Uo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Nt.concat()}calcACoords(){const t=ns({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Ts(e,s),n=vt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:Mt({x:-o,y:-h},n),tr:Mt({x:o,y:-h},n),bl:Mt({x:-o,y:h},n),br:Mt({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,xt(this.originX),xt(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every(((n,r)=>n===s[r]))?i.value:(this.group&&(e=vt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=$o(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new C(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new C(r*e.scaleX,o*e.scaleY):Fi(r,o,Js(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=xt(i)-xt(e),l=xt(n)-xt(s);if(h||l){const c=this._getTransformedDimensions();r+=h*c.x,o+=l*c.y}return new C(r,o)}translateToCenterPoint(t,e,s){if(e===$&&s===$)return t;const i=this.translateToGivenOrigin(t,e,s,$,$);return this.angle?i.rotate(pt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,$,$,e,s);return this.angle?i.rotate(pt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Mt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new C(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),it,Yt)}}const Hc=["type"],zc=["extraParam"];let Ie=class Yn extends Bc{static getDefaults(){return Yn.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){De("warn","Setting type has no effect",t)}constructor(t){super(),x(this,"_cacheContext",null),Object.assign(this,Yn.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Se(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=et.maxCacheSideLimit,n=et.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=et.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=$s.limitDimsByArea(r),l=ls(n,o,i),c=ls(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>c&&(t.zoomY/=s/c,t.height=c,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:o,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(l||c){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=o/2,d=h/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new C(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=is(this.calcTransformMatrix());return new C(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==Bt&&t!==Qt||(e=this._constrainScale(e)),t===Bt&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Le||(e=new Le(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===Ht&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=te(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach((n=>{n.transform(i)})),e.parentClipPaths.push(t),t.absolutePositioned){const n=$t(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,re(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(re(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=s?.viewportTransform||Nt,o=n*i,h=r*i,l=e.nonScaling?new C(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*et.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!re(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,i,n):t.transform(1,0,0,1,i,n),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:i,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===Ht?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=te({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new C(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(L.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=ur(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?No():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(v=>new ti(v,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&ra(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&dr(this,this.getViewportTransform()),this.setCoords();const l=Se(),c=this.getBoundingRect(),u=this.shadow,d=new C;if(u){const v=u.blur,y=u.nonScaling?new C(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+v)*n(y.x),d.y=2*Math.round(n(u.offsetY)+v)*n(y.y)}const f=c.width+d.x,g=c.height+d.y;l.width=Math.ceil(f),l.height=Math.ceil(g);const p=h(l);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new C(p.width/2,p.height/2),$,$);const b=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(o||1,t);return this.set("canvas",b),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),p._objects=[],p.destroy(),m}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return rr(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return or(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:i}=this;if(e){const{x:n,y:r}=this.getRelativeCenterPoint();this.originX=$,this.originY=$,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Pi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&xe().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce(((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s}),{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,c=w(w({},s),{},{target:this,startValue:o??i.reduce(((u,d)=>u[d]),this),endValue:e,abort:r?.bind(this),onChange:(u,d,f)=>{i.reduce(((g,p,b)=>(b===i.length-1&&(g[p]=u),g[p])),this),h&&h(u,d,f)},onComplete:(u,d,f)=>{this.setCoords(),l&&l(u,d,f)}});return n?La(c):Er(c)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Yn.customProperties,this.constructor.customProperties||[]);let e;const s=et.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:_,scaleX:S,scaleY:A,angle:T,flipX:k,flipY:P,opacity:B,visible:F,backgroundColor:I,fillRule:O,paintFirst:D,globalCompositeOperation:z,skewX:M,skewY:R}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const U=dt=>ot(dt,s),ht=w(w({},rs(this,t)),{},{type:this.constructor.type,version:Jn,originX:u,originY:d,left:U(l),top:U(c),width:U(f),height:U(g),fill:qo(n)?n.toObject():n,stroke:qo(r)?r.toObject():r,strokeWidth:U(p),strokeDashArray:h&&h.concat(),strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:U(_),scaleX:U(S),scaleY:U(A),angle:U(T),flipX:k,flipY:P,opacity:U(B),shadow:o&&o.toObject(),visible:F,backgroundColor:I,fillRule:O,paintFirst:D,globalCompositeOperation:z,skewX:U(M),skewY:U(R)},e?{clipPath:e}:null);return this.includeDefaultValues?ht:this._removeDefaultValues(ht)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return lr(t,((i,n)=>{if(n===it||n===Yt||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)}))}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=lt(t,Hc),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=lt(s,zc);return Qs(e,n).then((r=>i?(delete r[i],new this(e[i],r)):new this(r)))}static fromObject(t,e){return this._fromObject(t,e)}};x(Ie,"stateProperties",kc),x(Ie,"cacheProperties",Fe),x(Ie,"ownDefaults",Mc),x(Ie,"type","FabricObject"),x(Ie,"colorProperties",[wt,Ht,"backgroundColor"]),x(Ie,"customProperties",[]),L.setClass(Ie),L.setClass(Ie,"object");const Os=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&aa(a,w(w({},ca(s,i,n,r)),e)),o};function Ds(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),l=n.translateToOriginPoint(h,r,o),c=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),c}}const Fa=Os(qs,Ds(((a,t,e,s)=>{const i=fr(t,t.originX,t.originY,e,s);if(xt(t.originX)===xt($)||xt(t.originX)===xt(bt)&&i.x<0||xt(t.originX)===xt(it)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=ha(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1})));function Gc(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Ht:wt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,u=t,d=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,a.scale(1,r/n),d=e*n/r):r>n?(c=r,a.scale(n/r,1),u=t*r/n):c=n,a.beginPath(),a.arc(u,d,c/2,0,Re,!1),a[h](),l&&a.stroke(),a.restore()}function Vc(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?Ht:wt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,u=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.translate(t,e);const d=i.getTotalAngle();a.rotate(pt(d)),a["".concat(h,"Rect")](-c,-u,n,r),l&&a.strokeRect(-c,-u,n,r),a.restore()}class ge{constructor(t){x(this,"visible",!0),x(this,"actionName",ki),x(this,"angle",0),x(this,"x",0),x(this,"y",0),x(this,"offsetX",0),x(this,"offsetY",0),x(this,"sizeX",0),x(this,"sizeY",0),x(this,"touchSizeX",0),x(this,"touchSizeY",0),x(this,"cursorStyle","crosshair"),x(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&gt.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new C(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=Di([Ts(s,i),ns({angle:t}),Ri((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new C(-.5,-.5).transform(o),tr:new C(.5,-.5).transform(o),br:new C(.5,.5).transform(o),bl:new C(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?Gc.call(this,t,e,s,i,n):Vc.call(this,t,e,s,i,n)}}const Wc=(a,t,e)=>e.lockRotation?Ii:t.cursorStyle,Xc=Os(Bo,Ds(((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:l}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,l);if(de(i,"lockRotation"))return!1;const u=Math.atan2(r-c.y,n-c.x),d=Math.atan2(s-c.y,e-c.x);let f=Ce(d-u+o);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,b=i.snapThreshold||p,m=Math.ceil(f/p)*p,v=Math.floor(f/p)*p;Math.abs(f-v)<b?f=v:Math.abs(f-m)<b&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g})));function Ia(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Na(a,t,e){const s=de(a,"lockScalingX"),i=de(a,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:o}=a;return n===0&&o===0&&t!=="y"||r===0&&o===0&&t!=="x"}const Uc=["e","se","s","sw","w","nw","n","ne","e"],ri=(a,t,e)=>{const s=Ia(a,e);if(Na(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Ii;const i=ua(e,t);return"".concat(Uc[i],"-resize")};function kr(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Ia(a,n);let h,l,c,u,d,f;if(Na(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(h=fr(t,t.originX,t.originY,e,s),d=r!=="y"?Math.sign(h.x||t.signX||1):1,f=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=f),de(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),o&&!r){const b=Math.abs(h.x)+Math.abs(h.y),{original:m}=t,v=b/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));l=m.scaleX*v,c=m.scaleY*v}else l=Math.abs(h.x*n.scaleX/u.x),c=Math.abs(h.y*n.scaleY/u.y);ha(t)&&(l*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=la(t.originX),l*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=la(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set(Bt,l),r==="y"&&n.set(Qt,c)):(!de(n,"lockScalingX")&&n.set(Bt,l),!de(n,"lockScalingY")&&n.set(Qt,c)),g!==n.scaleX||p!==n.scaleY}const Xi=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s)))),Yc=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s,{by:"x"})))),$c=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s,{by:"y"})))),qc=["target","ex","ey","skewingSide"],Mr={x:{counterAxis:"y",scale:Bt,skew:Ss,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Qt,skew:Cs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Kc=["ns","nesw","ew","nwse"],Jc=(a,t,e)=>{if(t.x!==0&&de(e,"lockSkewingY")||t.y!==0&&de(e,"lockSkewingX"))return Ii;const s=ua(e,t)%4;return"".concat(Kc[s],"-resize")};function ja(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:c}=Mr[a];if(de(n,h))return!1;const{origin:u,flip:d}=Mr[r],f=xt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[l]===0&&fr(e,$,$,s,i)[a]>0||n[l]>0?1:-1)*g)+.5;return Os(Ho,Ds(((m,v,y,_)=>(function(S,A,T){let{target:k,ex:P,ey:B,skewingSide:F}=A,I=lt(A,qc);const{skew:O}=Mr[S],D=T.subtract(new C(P,B)).divide(new C(k.scaleX,k.scaleY))[S],z=k[O],M=I[O],R=Math.tan(pt(M)),U=S==="y"?k._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:k._getTransformedDimensions({scaleX:1,scaleY:1}).y,ht=2*D*F/Math.max(U,1)+R,dt=Ce(Math.atan(ht));k.set(O,dt);const E=z!==k[O];if(E&&S==="y"){const{skewX:H,scaleX:V}=k,Q=k._getTransformedDimensions({skewY:z}),kt=k._getTransformedDimensions(),rt=H!==0?Q.x/kt.x:1;rt!==1&&k.set(Bt,rt*V)}return E})(a,v,new C(y,_)))))(t,w(w({},e),{},{[o]:p,skewingSide:g}),s,i)}const Zc=(a,t,e,s)=>ja("x",a,t,e,s),Qc=(a,t,e,s)=>ja("y",a,t,e,s);function Ui(a,t){return a[t.canvas.altActionKey]}const Yi=(a,t,e)=>{const s=Ui(a,e);return t.x===0?s?Ss:Qt:t.y===0?s?Cs:Bt:""},Rs=(a,t,e)=>Ui(a,e)?Jc(0,t,e):ri(a,t,e),Ba=(a,t,e,s)=>Ui(a,t.target)?Qc(a,t,e,s):Yc(a,t,e,s),Ha=(a,t,e,s)=>Ui(a,t.target)?Zc(a,t,e,s):$c(a,t,e,s),za=()=>({ml:new ge({x:-.5,y:0,cursorStyleHandler:Rs,actionHandler:Ba,getActionName:Yi}),mr:new ge({x:.5,y:0,cursorStyleHandler:Rs,actionHandler:Ba,getActionName:Yi}),mb:new ge({x:0,y:.5,cursorStyleHandler:Rs,actionHandler:Ha,getActionName:Yi}),mt:new ge({x:0,y:-.5,cursorStyleHandler:Rs,actionHandler:Ha,getActionName:Yi}),tl:new ge({x:-.5,y:-.5,cursorStyleHandler:ri,actionHandler:Xi}),tr:new ge({x:.5,y:-.5,cursorStyleHandler:ri,actionHandler:Xi}),bl:new ge({x:-.5,y:.5,cursorStyleHandler:ri,actionHandler:Xi}),br:new ge({x:.5,y:.5,cursorStyleHandler:ri,actionHandler:Xi}),mtr:new ge({x:0,y:-.5,actionHandler:Xc,cursorStyleHandler:Wc,offsetY:-40,withConnection:!0,actionName:sr})}),tu=()=>({mr:new ge({x:.5,y:0,actionHandler:Fa,cursorStyleHandler:Rs,actionName:qs}),ml:new ge({x:-.5,y:0,actionHandler:Fa,cursorStyleHandler:Rs,actionName:qs})}),eu=()=>w(w({},za()),tu());class oi extends Ie{static getDefaults(){return w(w({},super.getDefaults()),oi.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),oi.ownDefaults),this.setOptions(t)}static createControls(){return{controls:za()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,i=e.action;if(this===s&&i&&i.startsWith(ki))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let i=s.length-1;i>=0;i--){const[n,r]=s[i],o=this.controls[n];if(o.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:o,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Ts(e.x,e.y),i=ns({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=vt(s,i),r=vt(t,n),o=vt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?is(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),c={};return this.forEachControl(((u,d)=>{const f=u.positionHandler(l,o,this,u);c[d]=Object.assign(f,this._calcCornerCoords(u,f))})),c}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),i=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/i[0],1/i[3]),t.rotate(pt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=w({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=w({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=vt(r,this.calcTransformMatrix()),c=is(l);t.save(),t.translate(c.translateX,c.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180),t.rotate(pt(this.group?c.angle:this.angle)),o&&this.drawBorders(t,c,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=Fi(this.width,this.height,Js(e)),r=this.isStrokeAccountedForInDimensions()?nr:(this.strokeUniform?new C().scalarAdd(this.canvas?this.canvas.getZoom():1):new C(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl(((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))})),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,o=w({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl(((h,l)=>{if(h.getVisibility(this,l)){const c=this.oCoords[l];h.render(t,c.x,c.y,o,this)}})),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach((e=>{let[s,i]=e;return this.setControlVisible(s,i)}))}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function Ga(a,t){return t.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))}))})),a}x(oi,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class Pt extends oi{}Ga(Pt,[ma]),L.setClass(Pt),L.setClass(Pt,"object");const Va=(a,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=a.getImageData(t-s,e-s,i,i);for(let r=3;r<n.length;r+=4)if(n[r]>0)return!1;return!0};class Wa{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new C(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new C(1/this.options.scaleX,1/this.options.scaleY):new C(1,1)}createSideVector(t,e){const s=zi(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new C(t);return e.y+=e.x*Math.tan(pt(this.options.skewY)),e.x+=e.y*Math.tan(pt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const su=new C;class Ls extends Wa{static getOrthogonalRotationFactor(t,e){const s=e?Vi(t,e):Ea(t);return Math.abs(s)<We?-1:1}constructor(t,e,s,i){super(i),x(this,"AB",void 0),x(this,"AC",void 0),x(this,"alpha",void 0),x(this,"bisector",void 0),this.A=new C(t),this.B=new C(e),this.C=new C(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Vi(this.AB,this.AC),this.bisector=Wi(_r(this.AB.eq(su)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e),n=wr(i),r=Ls.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Re==0?[this.B]:[this.B,this.C]).forEach((e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))})),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),n=this.options.strokeUniform?Gi(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Gi(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new C(Ls.getOrthogonalRotationFactor(this.bisector),Ls.getOrthogonalRotationFactor(new C(this.bisector.y,this.bisector.x)));return[new C(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new C(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach((n=>{xr(n,t,e)&&s.push(this.A.add(n))})),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:h}=this.options,l=new C(Math.tan(pt(i)),Math.tan(pt(n))),c=this.strokeProjectionMagnitude,u=h?c/o/Math.sqrt(1/o**2+1/r**2*l.y**2):c/Math.sqrt(1+l.y**2),d=new C(Math.sqrt(Math.max(c**2-u**2,0)),u),f=h?c/Math.sqrt(1+l.x**2*(1/o)**2/(1/r+1/r*l.x*l.y)**2):c/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),g=new C(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map((p=>this.applySkew(h?p.multiply(this.strokeUniformScalar):p))).forEach((p=>{xr(p,t,e)&&s.push(this.applySkew(this.A).add(p))})),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Re==0,s=this.applySkew(this.A),i=t[e?0:2].subtract(s),n=t[e?1:0].subtract(s),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),o=Ps(i,r)>0,h=o?i:n,l=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector})))}}class Xa extends Wa{constructor(t,e,s){super(s),this.A=new C(t),this.T=new C(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e);return this.scaleUnitVector(wr(i),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new C(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new Ls(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new C(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(Wi(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),i=this.A.add(s);t.push(i.add(e),i.subtract(e))}return t.map((e=>this.applySkew(e)))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t})))}}const Ua=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(a.length===0)return s;const i=a.reduce(((n,r)=>(n[n.length-1].eq(r)||n.push(new C(r)),n)),[new C(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let l=o.length-1;l>=0;l--)if(h(o[l],l,o))return l;return-1})(i,(o=>!o.eq(n)));i.splice(r+1)}return i.forEach(((n,r,o)=>{let h,l;r===0?(l=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],l=e?n:o[0]):(h=o[r-1],l=o[r+1]),e&&o.length===1?s.push(...new Xa(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ls(n,h,l,t).project()):s.push(...new Xa(n,r===0?l:h,t).project())})),s},Pr=a=>{const t={};return Object.keys(a).forEach((e=>{t[e]={},Object.keys(a[e]).forEach((s=>{t[e][s]=w({},a[e][s])}))})),t},Ya=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ai;const $i=a=>{if(ai||ai||(ai="Intl"in Ys()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ai){const t=ai.segment(a);return Array.from(t).map((e=>{let{segment:s}=e;return s}))}return iu(a)},iu=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=nu(a,s))!==!1&&t.push(e);return t},nu=(a,t)=>{const e=a.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return a.charAt(t);if(55296<=e&&e<=56319){if(a.length<=t+1)throw"High surrogate without following low surrogate";const i=a.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return a.charAt(t)+a.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=a.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var ru=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(a.charAt(0).toUpperCase()).concat(t?a.slice(1):a.slice(1).toLowerCase())},escapeXml:Ya,graphemeSplit:$i});const qi=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return a.fill!==t.fill||a.stroke!==t.stroke||a.strokeWidth!==t.strokeWidth||a.fontSize!==t.fontSize||a.fontFamily!==t.fontFamily||a.fontWeight!==t.fontWeight||a.fontStyle!==t.fontStyle||a.textDecorationThickness!==t.textDecorationThickness||a.textBackgroundColor!==t.textBackgroundColor||a.deltaY!==t.deltaY||e&&(a.overline!==t.overline||a.underline!==t.underline||a.linethrough!==t.linethrough)},$a=(a,t)=>{const e=t.split(`
43
- `),s=[];let i=-1,n={};a=Pr(a);for(let r=0;r<e.length;r++){const o=$i(e[r]);if(a[r])for(let h=0;h<o.length;h++){i++;const l=a[r][h];l&&Object.keys(l).length>0&&(qi(n,l,!0)?s.push({start:i,end:i+1,style:l}):s[s.length-1].end++),n=l||{}}else i+=o.length,n={}}return s},qa=(a,t)=>{if(!Array.isArray(a))return Pr(a);const e=t.split(er),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=$i(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=w({},a[n].style),i===a[n].end-1&&n++)}return s},Ye=["display","transform",wt,"fill-opacity","fill-rule","opacity",Ht,"stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"];function Ka(a,t){const e=a.nodeName,s=a.getAttribute("class"),i=a.getAttribute("id"),n="(?![a-zA-Z\\-]+)";let r;if(r=new RegExp("^"+e,"i"),t=t.replace(r,""),i&&t.length&&(r=new RegExp("#"+i+n,"i"),t=t.replace(r,"")),s&&t.length){const o=s.split(" ");for(let h=o.length;h--;)r=new RegExp("\\."+o[h]+n,"i"),t=t.replace(r,"")}return t.length===0}function ou(a,t){let e=!0;const s=Ka(a,t.pop());return s&&t.length&&(e=(function(i,n){let r,o=!0;for(;i.parentElement&&i.parentElement.nodeType===1&&n.length;)o&&(r=n.pop()),o=Ka(i=i.parentElement,r);return n.length===0})(a,t)),s&&e&&t.length===0}const au=a=>{var t;return(t=Cc[a])!==null&&t!==void 0?t:a},hu=new RegExp("(".concat(fe,")"),"gi"),lu=a=>Ni(a.replace(hu," $1 ").replace(/,/gi," "));var Ja,Za,Qa,th,eh,sh,ih;const Gt="(".concat(fe,")"),cu=String.raw(Ja||(Ja=_e(["(skewX)(",")"],["(skewX)\\(","\\)"])),Gt),uu=String.raw(Za||(Za=_e(["(skewY)(",")"],["(skewY)\\(","\\)"])),Gt),du=String.raw(Qa||(Qa=_e(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Gt,Gt,Gt),fu=String.raw(th||(th=_e(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Gt,Gt),gu=String.raw(eh||(eh=_e(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Gt,Gt),pu=String.raw(sh||(sh=_e(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Gt,Gt,Gt,Gt,Gt,Gt),Or="(?:".concat(pu,"|").concat(gu,"|").concat(du,"|").concat(fu,"|").concat(cu,"|").concat(uu,")"),mu="(?:".concat(Or,"*)"),bu=String.raw(ih||(ih=_e(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),mu),vu=new RegExp(bu),yu=new RegExp(Or),_u=new RegExp(Or,"g");function Ki(a){const t=[];if(!(a=lu(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!vu.test(a))return[...Nt];for(const e of a.matchAll(_u)){const s=yu.exec(e[0]);if(!s)continue;let i=Nt;const n=s.filter((g=>!!g)),[,r,...o]=n,[h,l,c,u,d,f]=o.map((g=>parseFloat(g)));switch(r){case"translate":i=Ts(h,l);break;case sr:i=ns({angle:h},{x:l,y:c});break;case ki:i=Ri(h,l);break;case Ss:i=ar(h);break;case Cs:i=hr(h);break;case"matrix":i=[h,l,c,u,d,f]}t.push(i)}return Di(t)}function wu(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==wt&&a!==Ht||t!==jt){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===jt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?vt(e.transformMatrix,Ki(t)):Ki(t);else if(a==="visible")r=t!==jt&&t!=="hidden",e&&e.visible===!1&&(r=!1);else if(a==="opacity")r=parseFloat(t),e&&e.opacity!==void 0&&(r*=e.opacity);else if(a==="textAnchor")r=t==="start"?it:t==="end"?bt:$;else if(a==="charSpacing"||a===hs)n=zt(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(wt),h=t.indexOf(Ht);r=wt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=Ht)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(zt):zt(t,s)}}else r="";return!i&&isNaN(n)?r:n}function xu(a,t){const e=a.match(Sc);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],o=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=zt(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Dr(a,t){a.replace(/;\s*$/,"").split(";").forEach((e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()}))}function Su(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Dr(e,t):(function(s,i){Object.entries(s).forEach((n=>{let[r,o]=n;o!==void 0&&(i[r.toLowerCase()]=o)}))})(e,t)),t}const Cu={stroke:"strokeOpacity",fill:"fillOpacity"};function Ne(a,t,e){if(!a)return{};let s,i={},n=Qn;a.parentNode&&Ca.test(a.parentNode.nodeName)&&(i=Ne(a.parentElement,t,e),i.fontSize&&(s=n=zt(i.fontSize)));const r=w(w(w({},t.reduce(((l,c)=>{const u=a.getAttribute(c);return u&&(l[c]=u),l}),{})),(function(l){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in c)ou(l,d.split(" "))&&(u=w(w({},u),c[d]));return u})(a,e)),Su(a));r[yr]&&a.setAttribute(yr,r[yr]),r[vr]&&(s=zt(r[vr],n),r[vr]="".concat(s));const o={};for(const l in r){const c=au(l),u=wu(c,r[l],i,s);o[c]=u}o&&o.font&&xu(o.font,o);const h=w(w({},i),o);return Ca.test(a.nodeName)?h:(function(l){const c=Pt.getDefaults();return Object.entries(Cu).forEach((u=>{let[d,f]=u;if(l[f]===void 0||l[d]==="")return;if(l[d]===void 0){if(!c[d])return;l[d]=c[d]}if(l[d].indexOf("url(")===0)return;const g=new nt(l[d]);l[d]=g.setAlpha(ot(g.getAlpha()*l[f],2)).toRgba()})),l})(h)}const Au=["left","top","width","height","visible"],nh=["rx","ry"];class Ee extends Pt{static getDefaults(){return w(w({},super.getDefaults()),Ee.ownDefaults)}constructor(t){super(),Object.assign(this,Ee.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,i=-e/2,n=-s/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,s/2):0,h=r!==0||o!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),h&&t.bezierCurveTo(i+e-Xe*r,n,i+e,n+Xe*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-Xe*o,i+e-Xe*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+Xe*r,n+s,i,n+s-Xe*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+Xe*o,i+Xe*r,n,i+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...nh,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(i,'" width="').concat(t,'" height="').concat(e,`" />
44
- `)]}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,c=lt(i,Au);return new this(w(w(w({},e),c),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}x(Ee,"type","Rect"),x(Ee,"cacheProperties",[...Fe,...nh]),x(Ee,"ownDefaults",{rx:0,ry:0}),x(Ee,"ATTRIBUTE_NAMES",[...Ye,"x","y","rx","ry","width","height"]),L.setClass(Ee),L.setSVGClass(Ee);const je="initialization",Ji="added",Rr="removed",Zi="imperative",rh=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?ei(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),c=e&&l?oa(new C(s,s),void 0,a.calcTransformMatrix()):nr,u=!e&&l?s:0,d=Fi(i+u,n+u,Di([o,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(d),h.add(d)]};class Qi{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===je||e===Zi||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==je&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Zi&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Ae(t.map((u=>rh(i,u))).reduce(((u,d)=>u.concat(d)),[])),l=new C(o,h),c=new C(n,r).add(l.scalarDivide(2));if(s===je){const u=this.getInitialSize(e,{size:l,center:c});return{center:c,relativeCorrection:new C(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:l}}}x(Qi,"type","strategy");class Lr extends Qi{shouldPerformLayout(t){return!0}}x(Lr,"type","fit-content"),L.setClass(Lr);const Tu=["strategy"],Eu=["target","strategy","bubbles","prevStrategy"],oh="layoutManager";class hi{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Lr;x(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=w(w({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[Mi,jo,qs,Bo,Ti,Ho,Ei,uc,dc].map((i=>t.on(i,(n=>this.performLayout(i===Mi?{type:"object_modified",trigger:i,e:n,target:s}:{type:"object_modifying",trigger:i,e:n,target:s})))))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach((s=>s())),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach((e=>this.unsubscribe(e,t)))}subscribeTargets(t){t.targets.forEach((e=>this.subscribe(e,t)))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:i}=e;if(s===je||s===Ji?this.subscribeTargets(t):s===Rr&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Zi&&t.deep){const n=lt(t,Tu);e.forEachObject((r=>r.layoutManager&&r.layoutManager.performLayout(w(w({},n),{},{bubbles:!1,target:r}))))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===je?new C:e.getRelativeCenterPoint(),{center:o,correction:h=new C,relativeCorrection:l=new C}=n,c=r.subtract(o).add(h).transform(i===je?Nt:$t(e.calcOwnMatrix()),!0).add(l);return{result:n,prevCenter:r,nextCenter:o,offset:c}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,o;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===je?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*xt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*xt(s.originY)}):(s.setPositionByOrigin(n,$,$),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject((i=>{i.group===s&&this.layoutObject(t,e,i)})),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,o=lt(t,Eu),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(w(w({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach((e=>e.forEach((s=>s())))),t.clear()}toObject(){return{type:oh,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}L.setClass(hi,oh);const ku=["type","objects","layoutManager"];class Mu extends hi{performLayout(){}}class ee extends zo(Pt){static getDefaults(){return w(w({},super.getDefaults()),ee.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"_activeObjects",[]),x(this,"__objectSelectionTracker",void 0),x(this,"__objectSelectionDisposer",void 0),Object.assign(this,ee.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject((i=>{this.enterGroup(i,!1)})),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new hi,this.layoutManager.performLayout({type:je,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(De("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(De("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter(((e,s,i)=>this.canEnterGroup(e)&&i.indexOf(e)===s))}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const i=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...i);return this._onAfterObjectsChange(Ji,i),n}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=this._filterObjectsBeforeEnteringGroup(s),r=super.insertAt(t,...n);return this._onAfterObjectsChange(Ji,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Rr,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach((i=>{i._set(t,e)})),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const i=this._activeObjects;if(t)i.push(s),this._set("dirty",!0);else if(i.length>0){const n=i.indexOf(s);n>-1&&(i.splice(n,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&Ms(t,vt($t(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Ms(t,vt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=Pt.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...$t(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject((t=>t.setCoords()))}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(w({target:this,type:Zi},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter((function(i){return!i.excludeFromExport})).map((function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r}))}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return w(w(w({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject((t=>{this._watchObject(!1,t),t.dispose()})),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ee.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
42
+ `)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Le.ownDefaults;return this.includeDefaultValues?t:lr(t,((s,i)=>s!==e[i]))}static async fromObject(t){return new this(t)}}x(Le,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),x(Le,"type","shadow"),L.setClass(Le,"shadow");const ls=(a,t,e)=>Math.max(a,Math.min(t,e)),kc=[$t,it,Ht,Qt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ss,Cs],Fe=[wt,zt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Mc={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:it,originY:$t,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:wt,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},Sr=(a,t,e,s)=>(a<Math.abs(t)?(a=t,s=e/4):s=t===0&&a===0?e/Re*Math.asin(1):e/Re*Math.asin(t/a),{a,c:t,p:e,s}),Oa=(a,t,e,s,i)=>a*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Re/e),Da=(a,t,e,s)=>-e*Math.cos(a/s*We)+e+t,Cr=(a,t,e,s)=>(a/=s)<1/2.75?e*(7.5625*a*a)+t:a<2/2.75?e*(7.5625*(a-=1.5/2.75)*a+.75)+t:a<2.5/2.75?e*(7.5625*(a-=2.25/2.75)*a+.9375)+t:e*(7.5625*(a-=2.625/2.75)*a+.984375)+t,Ra=(a,t,e,s)=>e-Cr(s-a,0,e,s)+t;var Pc=Object.freeze({__proto__:null,defaultEasing:Da,easeInBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(a/=s)*a*((i+1)*a-i)+t},easeInBounce:Ra,easeInCirc:(a,t,e,s)=>-e*(Math.sqrt(1-(a/=s)*a)-1)+t,easeInCubic:(a,t,e,s)=>e*(a/s)**3+t,easeInElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h}=Sr(i,e,n,1.70158);return-Oa(r,o,h,a,s)+t},easeInExpo:(a,t,e,s)=>a===0?t:e*2**(10*(a/s-1))+t,easeInOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(a/=s/2)<1?e/2*(a*a*((1+(i*=1.525))*a-i))+t:e/2*((a-=2)*a*((1+(i*=1.525))*a+i)+2)+t},easeInOutBounce:(a,t,e,s)=>a<s/2?.5*Ra(2*a,0,e,s)+t:.5*Cr(2*a-s,0,e,s)+.5*e+t,easeInOutCirc:(a,t,e,s)=>(a/=s/2)<1?-e/2*(Math.sqrt(1-a**2)-1)+t:e/2*(Math.sqrt(1-(a-=2)*a)+1)+t,easeInOutCubic:(a,t,e,s)=>(a/=s/2)<1?e/2*a**3+t:e/2*((a-2)**3+2)+t,easeInOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:o,p:h,c:l}=Sr(i,e,n,1.70158);return a<1?-.5*Oa(r,o,h,a,s)+t:r*Math.pow(2,-10*(a-=1))*Math.sin((a*s-o)*Re/h)*.5+l+t},easeInOutExpo:(a,t,e,s)=>a===0?t:a===s?t+e:(a/=s/2)<1?e/2*2**(10*(a-1))+t:e/2*-(2**(-10*--a)+2)+t,easeInOutQuad:(a,t,e,s)=>(a/=s/2)<1?e/2*a**2+t:-e/2*(--a*(a-2)-1)+t,easeInOutQuart:(a,t,e,s)=>(a/=s/2)<1?e/2*a**4+t:-e/2*((a-=2)*a**3-2)+t,easeInOutQuint:(a,t,e,s)=>(a/=s/2)<1?e/2*a**5+t:e/2*((a-2)**5+2)+t,easeInOutSine:(a,t,e,s)=>-e/2*(Math.cos(Math.PI*a/s)-1)+t,easeInQuad:(a,t,e,s)=>e*(a/=s)*a+t,easeInQuart:(a,t,e,s)=>e*(a/=s)*a**3+t,easeInQuint:(a,t,e,s)=>e*(a/s)**5+t,easeInSine:(a,t,e,s)=>-e*Math.cos(a/s*We)+e+t,easeOutBack:function(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((a=a/s-1)*a*((i+1)*a+i)+1)+t},easeOutBounce:Cr,easeOutCirc:(a,t,e,s)=>e*Math.sqrt(1-(a=a/s-1)*a)+t,easeOutCubic:(a,t,e,s)=>e*((a/s-1)**3+1)+t,easeOutElastic:(a,t,e,s)=>{const i=e;let n=0;if(a===0)return t;if((a/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:o,p:h,c:l}=Sr(i,e,n,1.70158);return r*2**(-10*a)*Math.sin((a*s-o)*Re/h)+l+t},easeOutExpo:(a,t,e,s)=>a===s?t+e:e*-(2**(-10*a/s)+1)+t,easeOutQuad:(a,t,e,s)=>-e*(a/=s)*(a-2)+t,easeOutQuart:(a,t,e,s)=>-e*((a=a/s-1)*a**3-1)+t,easeOutQuint:(a,t,e,s)=>e*((a/s-1)**5+1)+t,easeOutSine:(a,t,e,s)=>e*Math.sin(a/s*We)+t});const Oc=()=>!1;class Ar{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=Da,onStart:o=es,onChange:h=es,onComplete:l=es,abort:c=Oc,target:u}=t;x(this,"_state","pending"),x(this,"durationProgress",0),x(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=o,this._onChange=h,this._onComplete=l,this._abort=c,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout((()=>Ks(t)),this.delay):Ks(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:i,valueProgress:n}=this.calculate(s);this.value=Object.freeze(i),this.valueProgress=n,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),Ks(this.tick)))}register(){Pi.push(this)}unregister(){Pi.remove(this)}abort(){this._state="aborted",this.unregister()}}const Dc=["startValue","endValue"];class Rc extends Ar{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(w(w({},ct(t,Dc)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const Lc=["startValue","endValue"];class Fc extends Ar{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(w(w({},ct(t,Lc)),{},{startValue:e,byValue:s.map(((i,n)=>i-e[n]))}))}calculate(t){const e=this.startValue.map(((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i)));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const Ic=["startValue","endValue","easing","onChange","onComplete","abort"],Nc=(a,t,e,s)=>t+e*(1-Math.cos(a/s*We)),Tr=a=>a&&((t,e,s)=>a(new nt(t).toRgba(),e,s));class jc extends Ar{constructor(t){let{startValue:e,endValue:s,easing:i=Nc,onChange:n,onComplete:r,abort:o}=t,h=ct(t,Ic);const l=new nt(e).getSource(),c=new nt(s).getSource();super(w(w({},h),{},{startValue:l,byValue:c.map(((u,d)=>u-l[d])),easing:i,onChange:Tr(n),onComplete:Tr(r),abort:Tr(o)}))}calculate(t){const[e,s,i,n]=this.startValue.map(((o,h)=>this.easing(t,o,this.byValue[h],this.duration,h))),r=[...[e,s,i].map(Math.round),ls(0,n,1)];return{value:r,valueProgress:r.map(((o,h)=>this.byValue[h]!==0?Math.abs((o-this.startValue[h])/this.byValue[h]):0)).find((o=>o!==0))||0}}}function Er(a){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(a)?new Fc(a):new Rc(a);return t.start(),t}function La(a){const t=new jc(a);return t.start(),t}class gt{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some((e=>e.eq(t)))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter((i=>!this.includes(i)))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=zi(e,s),r=zi(e,t).divide(n);return i?Math.abs(r.x)===Math.abs(r.y):r.x===r.y&&r.x>=0&&r.x<=1}}static isPointInPolygon(t,e){const s=new C(t).setX(Math.min(t.x-1,...e.map((n=>n.x))));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const o=e.x-t.x,h=e.y-t.y,l=i.x-s.x,c=i.y-s.y,u=t.x-s.x,d=t.y-s.y,f=l*d-c*u,g=o*d-h*u,p=c*o-l*h;if(p!==0){const b=f/p,m=g/p;return(n||0<=b&&b<=1)&&(r||0<=m&&m<=1)?new gt("Intersection").append(new C(t.x+b*o,t.y+b*h)):new gt}if(f===0||g===0){const b=n||r||gt.isPointContained(t,s,i)||gt.isPointContained(e,s,i)||gt.isPointContained(s,t,e)||gt.isPointContained(i,t,e);return new gt(b?"Coincident":void 0)}return new gt("Parallel")}static intersectSegmentLine(t,e,s,i){return gt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return gt.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new gt,r=s.length;for(let o,h,l,c=0;c<r;c++){if(o=s[c],h=s[(c+1)%r],l=gt.intersectLineLine(t,e,o,h,i,!1),l.status==="Coincident")return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return gt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new gt,i=t.length,n=[];for(let r=0;r<i;r++){const o=t[r],h=t[(r+1)%i],l=gt.intersectSegmentPolygon(o,h,e);l.status==="Coincident"?(n.push(l),s.append(o,h)):s.append(...l.points)}return n.length>0&&n.length===t.length?new gt("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new C(n.x,i.y),o=new C(i.x,n.y);return gt.intersectPolygonPolygon(t,[i,r,n,o])}}class Bc extends Go{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?Ot(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Ot(t,qt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new C(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map((o=>Ot(o,r)))}return n}intersectsWithRect(t,e){return gt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=gt.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every((e=>t.containsPoint(e)))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return gt.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some((s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y))||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every((s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y)))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Ae(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Ht,t),this._set(Qt,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?Ce(Uo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||jt.concat()}calcACoords(){const t=ns({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Ts(e,s),n=vt(i,t),r=this._getTransformedDimensions(),o=r.x/2,h=r.y/2;return{tl:Ot({x:-o,y:-h},n),tr:Ot({x:o,y:-h},n),bl:Ot({x:-o,y:h},n),br:Ot({x:o,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,xt(this.originX),xt(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every(((n,r)=>n===s[r]))?i.value:(this.group&&(e=vt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=$o(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new C(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,o=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new C(r*e.scaleX,o*e.scaleY):Fi(r,o,Js(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,o=t.y;const h=xt(i)-xt(e),l=xt(n)-xt(s);if(h||l){const c=this._getTransformedDimensions();r+=h*c.x,o+=l*c.y}return new C(r,o)}translateToCenterPoint(t,e,s){if(e===$&&s===$)return t;const i=this.translateToGivenOrigin(t,e,s,$,$);return this.angle?i.rotate(pt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,$,$,e,s);return this.angle?i.rotate(pt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Ot(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new C(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),it,$t)}}const Hc=["type"],zc=["extraParam"];let Ie=class Yn extends Bc{static getDefaults(){return Yn.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){De("warn","Setting type has no effect",t)}constructor(t){super(),x(this,"_cacheContext",null),Object.assign(this,Yn.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Se(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=et.maxCacheSideLimit,n=et.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=et.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[o,h]=$s.limitDimsByArea(r),l=ls(n,o,i),c=ls(n,h,i);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>c&&(t.zoomY/=s/c,t.height=c,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:o,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(l||c){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=o/2,d=h/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new C(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=is(this.calcTransformMatrix());return new C(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==Ht&&t!==Qt||(e=this._constrainScale(e)),t===Ht&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Le||(e=new Le(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===zt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=te(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach((n=>{n.transform(i)})),e.parentClipPaths.push(t),t.absolutePositioned){const n=qt(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,re(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(re(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=s?.viewportTransform||jt,o=n*i,h=r*i,l=e.nonScaling?new C(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*et.browserShadowBlurConstant*(o+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!re(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,i,n):t.transform(1,0,0,1,i,n),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:i,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===zt?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,o=i.y/this.scaleY/n,h=te({width:Math.ceil(r),height:Math.ceil(o)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(r,0),l.lineTo(r,o),l.lineTo(0,o),l.closePath(),l.translate(r/2,o/2),l.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new C(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(L.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=ur(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?No():1,o=(t.multiplier||1)*r,h=t.canvasProvider||(v=>new ti(v,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&ra(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&dr(this,this.getViewportTransform()),this.setCoords();const l=Se(),c=this.getBoundingRect(),u=this.shadow,d=new C;if(u){const v=u.blur,y=u.nonScaling?new C(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+v)*n(y.x),d.y=2*Math.round(n(u.offsetY)+v)*n(y.y)}const f=c.width+d.x,g=c.height+d.y;l.width=Math.ceil(f),l.height=Math.ceil(g);const p=h(l);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new C(p.width/2,p.height/2),$,$);const b=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(o||1,t);return this.set("canvas",b),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),p._objects=[],p.destroy(),m}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return rr(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return or(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:i}=this;if(e){const{x:n,y:r}=this.getRelativeCenterPoint();this.originX=$,this.originY=$,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Pi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&xe().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce(((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s}),{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:o,onChange:h,onComplete:l}=s,c=w(w({},s),{},{target:this,startValue:o??i.reduce(((u,d)=>u[d]),this),endValue:e,abort:r?.bind(this),onChange:(u,d,f)=>{i.reduce(((g,p,b)=>(b===i.length-1&&(g[p]=u),g[p])),this),h&&h(u,d,f)},onComplete:(u,d,f)=>{this.setCoords(),l&&l(u,d,f)}});return n?La(c):Er(c)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),o=s._objects.indexOf(n);return r>-1&&r>o}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Yn.customProperties,this.constructor.customProperties||[]);let e;const s=et.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:o,strokeDashArray:h,left:l,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:_,scaleX:S,scaleY:A,angle:T,flipX:k,flipY:P,opacity:B,visible:F,backgroundColor:I,fillRule:O,paintFirst:D,globalCompositeOperation:z,skewX:M,skewY:R}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const U=ft=>ot(ft,s),lt=w(w({},rs(this,t)),{},{type:this.constructor.type,version:Jn,originX:u,originY:d,left:U(l),top:U(c),width:U(f),height:U(g),fill:qo(n)?n.toObject():n,stroke:qo(r)?r.toObject():r,strokeWidth:U(p),strokeDashArray:h&&h.concat(),strokeLineCap:b,strokeDashOffset:m,strokeLineJoin:v,strokeUniform:y,strokeMiterLimit:U(_),scaleX:U(S),scaleY:U(A),angle:U(T),flipX:k,flipY:P,opacity:U(B),shadow:o&&o.toObject(),visible:F,backgroundColor:I,fillRule:O,paintFirst:D,globalCompositeOperation:z,skewX:U(M),skewY:U(R)},e?{clipPath:e}:null);return this.includeDefaultValues?lt:this._removeDefaultValues(lt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return lr(t,((i,n)=>{if(n===it||n===$t||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)}))}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=ct(t,Hc),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=ct(s,zc);return Qs(e,n).then((r=>i?(delete r[i],new this(e[i],r)):new this(r)))}static fromObject(t,e){return this._fromObject(t,e)}};x(Ie,"stateProperties",kc),x(Ie,"cacheProperties",Fe),x(Ie,"ownDefaults",Mc),x(Ie,"type","FabricObject"),x(Ie,"colorProperties",[wt,zt,"backgroundColor"]),x(Ie,"customProperties",[]),L.setClass(Ie),L.setClass(Ie,"object");const Os=(a,t,e)=>(s,i,n,r)=>{const o=t(s,i,n,r);return o&&aa(a,w(w({},ca(s,i,n,r)),e)),o};function Ds(a){return(t,e,s,i)=>{const{target:n,originX:r,originY:o}=e,h=n.getRelativeCenterPoint(),l=n.translateToOriginPoint(h,r,o),c=a(t,e,s,i);return n.setPositionByOrigin(l,e.originX,e.originY),c}}const Fa=Os(qs,Ds(((a,t,e,s)=>{const i=fr(t,t.originX,t.originY,e,s);if(xt(t.originX)===xt($)||xt(t.originX)===xt(bt)&&i.x<0||xt(t.originX)===xt(it)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),o=ha(t)?2:1,h=n.width,l=Math.abs(i.x*o/n.scaleX)-r;return n.set("width",Math.max(l,1)),h!==n.width}return!1})));function Gc(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?zt:wt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,u=t,d=e;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,a.scale(1,r/n),d=e*n/r):r>n?(c=r,a.scale(n/r,1),u=t*r/n):c=n,a.beginPath(),a.arc(u,d,c/2,0,Re,!1),a[h](),l&&a.stroke(),a.restore()}function Vc(a,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,o=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=o?zt:wt,l=!o&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,u=r/2;a.save(),a.fillStyle=s.cornerColor||i.cornerColor||"",a.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",a.translate(t,e);const d=i.getTotalAngle();a.rotate(pt(d)),a["".concat(h,"Rect")](-c,-u,n,r),l&&a.strokeRect(-c,-u,n,r),a.restore()}class ge{constructor(t){x(this,"visible",!0),x(this,"actionName",ki),x(this,"angle",0),x(this,"x",0),x(this,"y",0),x(this,"offsetX",0),x(this,"offsetY",0),x(this,"sizeX",0),x(this,"sizeY",0),x(this,"touchSizeX",0),x(this,"touchSizeY",0),x(this,"cursorStyle","crosshair"),x(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:o,br:h,bl:l}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&gt.isPointInPolygon(s,[r,o,h,l])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new C(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const o=Di([Ts(s,i),ns({angle:t}),Ri((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new C(-.5,-.5).transform(o),tr:new C(.5,-.5).transform(o),br:new C(.5,.5).transform(o),bl:new C(-.5,.5).transform(o)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?Gc.call(this,t,e,s,i,n):Vc.call(this,t,e,s,i,n)}}const Wc=(a,t,e)=>e.lockRotation?Ii:t.cursorStyle,Xc=Os(Bo,Ds(((a,t,e,s)=>{let{target:i,ex:n,ey:r,theta:o,originX:h,originY:l}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,l);if(de(i,"lockRotation"))return!1;const u=Math.atan2(r-c.y,n-c.x),d=Math.atan2(s-c.y,e-c.x);let f=Ce(d-u+o);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,b=i.snapThreshold||p,m=Math.ceil(f/p)*p,v=Math.floor(f/p)*p;Math.abs(f-v)<b?f=v:Math.abs(f-m)<b&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g})));function Ia(a,t){const e=t.canvas,s=a[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function Na(a,t,e){const s=de(a,"lockScalingX"),i=de(a,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:o}=a;return n===0&&o===0&&t!=="y"||r===0&&o===0&&t!=="x"}const Uc=["e","se","s","sw","w","nw","n","ne","e"],ri=(a,t,e)=>{const s=Ia(a,e);if(Na(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Ii;const i=ua(e,t);return"".concat(Uc[i],"-resize")};function kr(a,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,o=Ia(a,n);let h,l,c,u,d,f;if(Na(n,r,o))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(h=fr(t,t.originX,t.originY,e,s),d=r!=="y"?Math.sign(h.x||t.signX||1):1,f=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=f),de(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),o&&!r){const b=Math.abs(h.x)+Math.abs(h.y),{original:m}=t,v=b/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));l=m.scaleX*v,c=m.scaleY*v}else l=Math.abs(h.x*n.scaleX/u.x),c=Math.abs(h.y*n.scaleY/u.y);ha(t)&&(l*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=la(t.originX),l*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=la(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set(Ht,l),r==="y"&&n.set(Qt,c)):(!de(n,"lockScalingX")&&n.set(Ht,l),!de(n,"lockScalingY")&&n.set(Qt,c)),g!==n.scaleX||p!==n.scaleY}const Xi=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s)))),Yc=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s,{by:"x"})))),$c=Os(Ti,Ds(((a,t,e,s)=>kr(a,t,e,s,{by:"y"})))),qc=["target","ex","ey","skewingSide"],Mr={x:{counterAxis:"y",scale:Ht,skew:Ss,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Qt,skew:Cs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Kc=["ns","nesw","ew","nwse"],Jc=(a,t,e)=>{if(t.x!==0&&de(e,"lockSkewingY")||t.y!==0&&de(e,"lockSkewingX"))return Ii;const s=ua(e,t)%4;return"".concat(Kc[s],"-resize")};function ja(a,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:o,lockSkewing:h,skew:l,flip:c}=Mr[a];if(de(n,h))return!1;const{origin:u,flip:d}=Mr[r],f=xt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[l]===0&&fr(e,$,$,s,i)[a]>0||n[l]>0?1:-1)*g)+.5;return Os(Ho,Ds(((m,v,y,_)=>(function(S,A,T){let{target:k,ex:P,ey:B,skewingSide:F}=A,I=ct(A,qc);const{skew:O}=Mr[S],D=T.subtract(new C(P,B)).divide(new C(k.scaleX,k.scaleY))[S],z=k[O],M=I[O],R=Math.tan(pt(M)),U=S==="y"?k._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:k._getTransformedDimensions({scaleX:1,scaleY:1}).y,lt=2*D*F/Math.max(U,1)+R,ft=Ce(Math.atan(lt));k.set(O,ft);const E=z!==k[O];if(E&&S==="y"){const{skewX:H,scaleX:V}=k,Q=k._getTransformedDimensions({skewY:z}),kt=k._getTransformedDimensions(),rt=H!==0?Q.x/kt.x:1;rt!==1&&k.set(Ht,rt*V)}return E})(a,v,new C(y,_)))))(t,w(w({},e),{},{[o]:p,skewingSide:g}),s,i)}const Zc=(a,t,e,s)=>ja("x",a,t,e,s),Qc=(a,t,e,s)=>ja("y",a,t,e,s);function Ui(a,t){return a[t.canvas.altActionKey]}const Yi=(a,t,e)=>{const s=Ui(a,e);return t.x===0?s?Ss:Qt:t.y===0?s?Cs:Ht:""},Rs=(a,t,e)=>Ui(a,e)?Jc(0,t,e):ri(a,t,e),Ba=(a,t,e,s)=>Ui(a,t.target)?Qc(a,t,e,s):Yc(a,t,e,s),Ha=(a,t,e,s)=>Ui(a,t.target)?Zc(a,t,e,s):$c(a,t,e,s),za=()=>({ml:new ge({x:-.5,y:0,cursorStyleHandler:Rs,actionHandler:Ba,getActionName:Yi}),mr:new ge({x:.5,y:0,cursorStyleHandler:Rs,actionHandler:Ba,getActionName:Yi}),mb:new ge({x:0,y:.5,cursorStyleHandler:Rs,actionHandler:Ha,getActionName:Yi}),mt:new ge({x:0,y:-.5,cursorStyleHandler:Rs,actionHandler:Ha,getActionName:Yi}),tl:new ge({x:-.5,y:-.5,cursorStyleHandler:ri,actionHandler:Xi}),tr:new ge({x:.5,y:-.5,cursorStyleHandler:ri,actionHandler:Xi}),bl:new ge({x:-.5,y:.5,cursorStyleHandler:ri,actionHandler:Xi}),br:new ge({x:.5,y:.5,cursorStyleHandler:ri,actionHandler:Xi}),mtr:new ge({x:0,y:-.5,actionHandler:Xc,cursorStyleHandler:Wc,offsetY:-40,withConnection:!0,actionName:sr})}),tu=()=>({mr:new ge({x:.5,y:0,actionHandler:Fa,cursorStyleHandler:Rs,actionName:qs}),ml:new ge({x:-.5,y:0,actionHandler:Fa,cursorStyleHandler:Rs,actionName:qs})}),eu=()=>w(w({},za()),tu());class oi extends Ie{static getDefaults(){return w(w({},super.getDefaults()),oi.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),oi.ownDefaults),this.setOptions(t)}static createControls(){return{controls:za()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,i=e.action;if(this===s&&i&&i.startsWith(ki))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let i=s.length-1;i>=0;i--){const[n,r]=s[i],o=this.controls[n];if(o.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:o,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Ts(e.x,e.y),i=ns({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=vt(s,i),r=vt(t,n),o=vt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?is(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),c={};return this.forEachControl(((u,d)=>{const f=u.positionHandler(l,o,this,u);c[d]=Object.assign(f,this._calcCornerCoords(u,f))})),c}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),i=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/i[0],1/i[3]),t.rotate(pt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=w({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=w({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),o=n.hasBorders,h=n.hasControls,l=vt(r,this.calcTransformMatrix()),c=is(l);t.save(),t.translate(c.translateX,c.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180),t.rotate(pt(this.group?c.angle:this.angle)),o&&this.drawBorders(t,c,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=Fi(this.width,this.height,Js(e)),r=this.isStrokeAccountedForInDimensions()?nr:(this.strokeUniform?new C().scalarAdd(this.canvas?this.canvas.getZoom():1):new C(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl(((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))})),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,o=w({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=o.cornerColor,this.transparentCorners||(t.strokeStyle=o.cornerStrokeColor),this._setLineDash(t,o.cornerDashArray),this.forEachControl(((h,l)=>{if(h.getVisibility(this,l)){const c=this.oCoords[l];h.render(t,c.x,c.y,o,this)}})),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach((e=>{let[s,i]=e;return this.setControlVisible(s,i)}))}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function Ga(a,t){return t.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((s=>{s!=="constructor"&&Object.defineProperty(a.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))}))})),a}x(oi,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class Dt extends oi{}Ga(Dt,[ma]),L.setClass(Dt),L.setClass(Dt,"object");const Va=(a,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=a.getImageData(t-s,e-s,i,i);for(let r=3;r<n.length;r+=4)if(n[r]>0)return!1;return!0};class Wa{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new C(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new C(1/this.options.scaleX,1/this.options.scaleY):new C(1,1)}createSideVector(t,e){const s=zi(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new C(t);return e.y+=e.x*Math.tan(pt(this.options.skewY)),e.x+=e.y*Math.tan(pt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const su=new C;class Ls extends Wa{static getOrthogonalRotationFactor(t,e){const s=e?Vi(t,e):Ea(t);return Math.abs(s)<We?-1:1}constructor(t,e,s,i){super(i),x(this,"AB",void 0),x(this,"AC",void 0),x(this,"alpha",void 0),x(this,"bisector",void 0),this.A=new C(t),this.B=new C(e),this.C=new C(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Vi(this.AB,this.AC),this.bisector=Wi(_r(this.AB.eq(su)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e),n=wr(i),r=Ls.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Re==0?[this.B]:[this.B,this.C]).forEach((e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))})),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),n=this.options.strokeUniform?Gi(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Gi(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new C(Ls.getOrthogonalRotationFactor(this.bisector),Ls.getOrthogonalRotationFactor(new C(this.bisector.y,this.bisector.x)));return[new C(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new C(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach((n=>{xr(n,t,e)&&s.push(this.A.add(n))})),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:o,strokeUniform:h}=this.options,l=new C(Math.tan(pt(i)),Math.tan(pt(n))),c=this.strokeProjectionMagnitude,u=h?c/o/Math.sqrt(1/o**2+1/r**2*l.y**2):c/Math.sqrt(1+l.y**2),d=new C(Math.sqrt(Math.max(c**2-u**2,0)),u),f=h?c/Math.sqrt(1+l.x**2*(1/o)**2/(1/r+1/r*l.x*l.y)**2):c/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),g=new C(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map((p=>this.applySkew(h?p.multiply(this.strokeUniformScalar):p))).forEach((p=>{xr(p,t,e)&&s.push(this.applySkew(this.A).add(p))})),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Re==0,s=this.applySkew(this.A),i=t[e?0:2].subtract(s),n=t[e?1:0].subtract(s),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),o=Ps(i,r)>0,h=o?i:n,l=o?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector})))}}class Xa extends Wa{constructor(t,e,s){super(s),this.A=new C(t),this.T=new C(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e);return this.scaleUnitVector(wr(i),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new C(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new Ls(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new C(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(Wi(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),i=this.A.add(s);t.push(i.add(e),i.subtract(e))}return t.map((e=>this.applySkew(e)))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map((t=>({originPoint:this.A,projectedPoint:t})))}}const Ua=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(a.length===0)return s;const i=a.reduce(((n,r)=>(n[n.length-1].eq(r)||n.push(new C(r)),n)),[new C(a[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((o,h)=>{for(let l=o.length-1;l>=0;l--)if(h(o[l],l,o))return l;return-1})(i,(o=>!o.eq(n)));i.splice(r+1)}return i.forEach(((n,r,o)=>{let h,l;r===0?(l=o[1],h=e?n:o[o.length-1]):r===o.length-1?(h=o[r-1],l=e?n:o[0]):(h=o[r-1],l=o[r+1]),e&&o.length===1?s.push(...new Xa(n,n,t).project()):!e||r!==0&&r!==o.length-1?s.push(...new Ls(n,h,l,t).project()):s.push(...new Xa(n,r===0?l:h,t).project())})),s},Pr=a=>{const t={};return Object.keys(a).forEach((e=>{t[e]={},Object.keys(a[e]).forEach((s=>{t[e][s]=w({},a[e][s])}))})),t},Ya=a=>a.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ai;const $i=a=>{if(ai||ai||(ai="Intl"in Ys()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ai){const t=ai.segment(a);return Array.from(t).map((e=>{let{segment:s}=e;return s}))}return iu(a)},iu=a=>{const t=[];for(let e,s=0;s<a.length;s++)(e=nu(a,s))!==!1&&t.push(e);return t},nu=(a,t)=>{const e=a.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return a.charAt(t);if(55296<=e&&e<=56319){if(a.length<=t+1)throw"High surrogate without following low surrogate";const i=a.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return a.charAt(t)+a.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=a.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var ru=Object.freeze({__proto__:null,capitalize:function(a){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(a.charAt(0).toUpperCase()).concat(t?a.slice(1):a.slice(1).toLowerCase())},escapeXml:Ya,graphemeSplit:$i});const qi=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return a.fill!==t.fill||a.stroke!==t.stroke||a.strokeWidth!==t.strokeWidth||a.fontSize!==t.fontSize||a.fontFamily!==t.fontFamily||a.fontWeight!==t.fontWeight||a.fontStyle!==t.fontStyle||a.textDecorationThickness!==t.textDecorationThickness||a.textBackgroundColor!==t.textBackgroundColor||a.deltaY!==t.deltaY||e&&(a.overline!==t.overline||a.underline!==t.underline||a.linethrough!==t.linethrough)},$a=(a,t)=>{const e=t.split(`
43
+ `),s=[];let i=-1,n={};a=Pr(a);for(let r=0;r<e.length;r++){const o=$i(e[r]);if(a[r])for(let h=0;h<o.length;h++){i++;const l=a[r][h];l&&Object.keys(l).length>0&&(qi(n,l,!0)?s.push({start:i,end:i+1,style:l}):s[s.length-1].end++),n=l||{}}else i+=o.length,n={}}return s},qa=(a,t)=>{if(!Array.isArray(a))return Pr(a);const e=t.split(er),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const o=$i(e[r]);for(let h=0;h<o.length;h++)i++,a[n]&&a[n].start<=i&&i<a[n].end&&(s[r]=s[r]||{},s[r][h]=w({},a[n].style),i===a[n].end-1&&n++)}return s},Ye=["display","transform",wt,"fill-opacity","fill-rule","opacity",zt,"stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"];function Ka(a,t){const e=a.nodeName,s=a.getAttribute("class"),i=a.getAttribute("id"),n="(?![a-zA-Z\\-]+)";let r;if(r=new RegExp("^"+e,"i"),t=t.replace(r,""),i&&t.length&&(r=new RegExp("#"+i+n,"i"),t=t.replace(r,"")),s&&t.length){const o=s.split(" ");for(let h=o.length;h--;)r=new RegExp("\\."+o[h]+n,"i"),t=t.replace(r,"")}return t.length===0}function ou(a,t){let e=!0;const s=Ka(a,t.pop());return s&&t.length&&(e=(function(i,n){let r,o=!0;for(;i.parentElement&&i.parentElement.nodeType===1&&n.length;)o&&(r=n.pop()),o=Ka(i=i.parentElement,r);return n.length===0})(a,t)),s&&e&&t.length===0}const au=a=>{var t;return(t=Cc[a])!==null&&t!==void 0?t:a},hu=new RegExp("(".concat(fe,")"),"gi"),lu=a=>Ni(a.replace(hu," $1 ").replace(/,/gi," "));var Ja,Za,Qa,th,eh,sh,ih;const Vt="(".concat(fe,")"),cu=String.raw(Ja||(Ja=_e(["(skewX)(",")"],["(skewX)\\(","\\)"])),Vt),uu=String.raw(Za||(Za=_e(["(skewY)(",")"],["(skewY)\\(","\\)"])),Vt),du=String.raw(Qa||(Qa=_e(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Vt,Vt,Vt),fu=String.raw(th||(th=_e(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Vt,Vt),gu=String.raw(eh||(eh=_e(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Vt,Vt),pu=String.raw(sh||(sh=_e(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Vt,Vt,Vt,Vt,Vt,Vt),Or="(?:".concat(pu,"|").concat(gu,"|").concat(du,"|").concat(fu,"|").concat(cu,"|").concat(uu,")"),mu="(?:".concat(Or,"*)"),bu=String.raw(ih||(ih=_e(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),mu),vu=new RegExp(bu),yu=new RegExp(Or),_u=new RegExp(Or,"g");function Ki(a){const t=[];if(!(a=lu(a).replace(/\s*([()])\s*/gi,"$1"))||a&&!vu.test(a))return[...jt];for(const e of a.matchAll(_u)){const s=yu.exec(e[0]);if(!s)continue;let i=jt;const n=s.filter((g=>!!g)),[,r,...o]=n,[h,l,c,u,d,f]=o.map((g=>parseFloat(g)));switch(r){case"translate":i=Ts(h,l);break;case sr:i=ns({angle:h},{x:l,y:c});break;case ki:i=Ri(h,l);break;case Ss:i=ar(h);break;case Cs:i=hr(h);break;case"matrix":i=[h,l,c,u,d,f]}t.push(i)}return Di(t)}function wu(a,t,e,s){const i=Array.isArray(t);let n,r=t;if(a!==wt&&a!==zt||t!==Bt){if(a==="strokeUniform")return t==="non-scaling-stroke";if(a==="strokeDashArray")r=t===Bt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(a==="transformMatrix")r=e&&e.transformMatrix?vt(e.transformMatrix,Ki(t)):Ki(t);else if(a==="visible")r=t!==Bt&&t!=="hidden",e&&e.visible===!1&&(r=!1);else if(a==="opacity")r=parseFloat(t),e&&e.opacity!==void 0&&(r*=e.opacity);else if(a==="textAnchor")r=t==="start"?it:t==="end"?bt:$;else if(a==="charSpacing"||a===hs)n=Gt(t,s)/s*1e3;else if(a==="paintFirst"){const o=t.indexOf(wt),h=t.indexOf(zt);r=wt,(o>-1&&h>-1&&h<o||o===-1&&h>-1)&&(r=zt)}else{if(a==="href"||a==="xlink:href"||a==="font"||a==="id")return t;if(a==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Gt):Gt(t,s)}}else r="";return!i&&isNaN(n)?r:n}function xu(a,t){const e=a.match(Sc);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],o=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=Gt(n)),o&&(t.fontFamily=o),r&&(t.lineHeight=r==="normal"?1:r)}function Dr(a,t){a.replace(/;\s*$/,"").split(";").forEach((e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()}))}function Su(a){const t={},e=a.getAttribute("style");return e&&(typeof e=="string"?Dr(e,t):(function(s,i){Object.entries(s).forEach((n=>{let[r,o]=n;o!==void 0&&(i[r.toLowerCase()]=o)}))})(e,t)),t}const Cu={stroke:"strokeOpacity",fill:"fillOpacity"};function Ne(a,t,e){if(!a)return{};let s,i={},n=Qn;a.parentNode&&Ca.test(a.parentNode.nodeName)&&(i=Ne(a.parentElement,t,e),i.fontSize&&(s=n=Gt(i.fontSize)));const r=w(w(w({},t.reduce(((l,c)=>{const u=a.getAttribute(c);return u&&(l[c]=u),l}),{})),(function(l){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in c)ou(l,d.split(" "))&&(u=w(w({},u),c[d]));return u})(a,e)),Su(a));r[yr]&&a.setAttribute(yr,r[yr]),r[vr]&&(s=Gt(r[vr],n),r[vr]="".concat(s));const o={};for(const l in r){const c=au(l),u=wu(c,r[l],i,s);o[c]=u}o&&o.font&&xu(o.font,o);const h=w(w({},i),o);return Ca.test(a.nodeName)?h:(function(l){const c=Dt.getDefaults();return Object.entries(Cu).forEach((u=>{let[d,f]=u;if(l[f]===void 0||l[d]==="")return;if(l[d]===void 0){if(!c[d])return;l[d]=c[d]}if(l[d].indexOf("url(")===0)return;const g=new nt(l[d]);l[d]=g.setAlpha(ot(g.getAlpha()*l[f],2)).toRgba()})),l})(h)}const Au=["left","top","width","height","visible"],nh=["rx","ry"];class Ee extends Dt{static getDefaults(){return w(w({},super.getDefaults()),Ee.ownDefaults)}constructor(t){super(),Object.assign(this,Ee.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,i=-e/2,n=-s/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,s/2):0,h=r!==0||o!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),h&&t.bezierCurveTo(i+e-Xe*r,n,i+e,n+Xe*o,i+e,n+o),t.lineTo(i+e,n+s-o),h&&t.bezierCurveTo(i+e,n+s-Xe*o,i+e-Xe*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),h&&t.bezierCurveTo(i+Xe*r,n+s,i,n+s-Xe*o,i,n+s-o),t.lineTo(i,n+o),h&&t.bezierCurveTo(i,n+Xe*o,i+Xe*r,n,i+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...nh,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(i,'" width="').concat(t,'" height="').concat(e,`" />
44
+ `)]}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:o=0,height:h=0,visible:l=!0}=i,c=ct(i,Au);return new this(w(w(w({},e),c),{},{left:n,top:r,width:o,height:h,visible:!!(l&&o&&h)}))}}x(Ee,"type","Rect"),x(Ee,"cacheProperties",[...Fe,...nh]),x(Ee,"ownDefaults",{rx:0,ry:0}),x(Ee,"ATTRIBUTE_NAMES",[...Ye,"x","y","rx","ry","width","height"]),L.setClass(Ee),L.setSVGClass(Ee);const je="initialization",Ji="added",Rr="removed",Zi="imperative",rh=(a,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,o=r&&r!==a?ei(r.calcTransformMatrix(),a.calcTransformMatrix()):null,h=o?t.getRelativeCenterPoint().transform(o):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),c=e&&l?oa(new C(s,s),void 0,a.calcTransformMatrix()):nr,u=!e&&l?s:0,d=Fi(i+u,n+u,Di([o,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(d),h.add(d)]};class Qi{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===je||e===Zi||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==je&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Zi&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:o,height:h}=Ae(t.map((u=>rh(i,u))).reduce(((u,d)=>u.concat(d)),[])),l=new C(o,h),c=new C(n,r).add(l.scalarDivide(2));if(s===je){const u=this.getInitialSize(e,{size:l,center:c});return{center:c,relativeCorrection:new C(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:l}}}x(Qi,"type","strategy");class Lr extends Qi{shouldPerformLayout(t){return!0}}x(Lr,"type","fit-content"),L.setClass(Lr);const Tu=["strategy"],Eu=["target","strategy","bubbles","prevStrategy"],oh="layoutManager";class hi{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Lr;x(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=w(w({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[Mi,jo,qs,Bo,Ti,Ho,Ei,uc,dc].map((i=>t.on(i,(n=>this.performLayout(i===Mi?{type:"object_modified",trigger:i,e:n,target:s}:{type:"object_modifying",trigger:i,e:n,target:s})))))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach((s=>s())),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach((e=>this.unsubscribe(e,t)))}subscribeTargets(t){t.targets.forEach((e=>this.subscribe(e,t)))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:i}=e;if(s===je||s===Ji?this.subscribeTargets(t):s===Rr&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Zi&&t.deep){const n=ct(t,Tu);e.forEachObject((r=>r.layoutManager&&r.layoutManager.performLayout(w(w({},n),{},{bubbles:!1,target:r}))))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===je?new C:e.getRelativeCenterPoint(),{center:o,correction:h=new C,relativeCorrection:l=new C}=n,c=r.subtract(o).add(h).transform(i===je?jt:qt(e.calcOwnMatrix()),!0).add(l);return{result:n,prevCenter:r,nextCenter:o,offset:c}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,o;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===je?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*xt(s.originX),top:(o=t.y)!==null&&o!==void 0?o:n.y+i.y*xt(s.originY)}):(s.setPositionByOrigin(n,$,$),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject((i=>{i.group===s&&this.layoutObject(t,e,i)})),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,o=ct(t,Eu),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;n&&l!=null&&l.layoutManager&&((o.path||(o.path=[])).push(s),l.layoutManager.performLayout(w(w({},o),{},{target:l}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach((e=>e.forEach((s=>s())))),t.clear()}toObject(){return{type:oh,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}L.setClass(hi,oh);const ku=["type","objects","layoutManager"];class Mu extends hi{performLayout(){}}class ee extends zo(Dt){static getDefaults(){return w(w({},super.getDefaults()),ee.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"_activeObjects",[]),x(this,"__objectSelectionTracker",void 0),x(this,"__objectSelectionDisposer",void 0),Object.assign(this,ee.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject((i=>{this.enterGroup(i,!1)})),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new hi,this.layoutManager.performLayout({type:je,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(De("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(De("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter(((e,s,i)=>this.canEnterGroup(e)&&i.indexOf(e)===s))}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const i=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...i);return this._onAfterObjectsChange(Ji,i),n}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=this._filterObjectsBeforeEnteringGroup(s),r=super.insertAt(t,...n);return this._onAfterObjectsChange(Ji,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Rr,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach((i=>{i._set(t,e)})),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const i=this._activeObjects;if(t)i.push(s),this._set("dirty",!0);else if(i.length>0){const n=i.indexOf(s);n>-1&&(i.splice(n,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&Ms(t,vt(qt(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Ms(t,vt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=Dt.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...qt(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject((t=>t.setCoords()))}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(w({target:this,type:Zi},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter((function(i){return!i.excludeFromExport})).map((function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r}))}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return w(w(w({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject((t=>{this._watchObject(!1,t),t.dispose()})),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ee.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
45
45
  `],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toSVG(t));return e.push(`</g>
46
- `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=lt(t,ku);return Promise.all([Es(i,e),Qs(r,e)]).then((o=>{let[h,l]=o;const c=new this(h,w(w(w({},r),l),{},{layoutManager:new Mu}));if(n){const u=L.getClass(n.type),d=L.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new hi;return c.layoutManager.subscribeTargets({type:je,target:c,targets:c.getObjects()}),c.setCoords(),c}))}}x(ee,"type","Group"),x(ee,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),L.setClass(ee);const ah=(a,t)=>Math.min(t.width/a.width,t.height/a.height),hh=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Fr="\\s*,?\\s*",li="".concat(Fr,"(").concat(fe,")"),Pu="".concat(li).concat(li).concat(li).concat(Fr,"([01])").concat(Fr,"([01])").concat(li).concat(li),Ou={m:"l",M:"L"},Du=(a,t,e,s,i,n,r,o,h,l,c)=>{const u=le(a),d=ce(a),f=le(t),g=ce(t),p=e*i*f-s*n*g+r,b=s*i*f+e*n*g+o;return["C",l+h*(-e*i*d-s*n*u),c+h*(-s*i*d+e*n*u),p+h*(e*i*g+s*n*f),b+h*(s*i*g-e*n*f),p,b]},lh=(a,t,e,s)=>{const i=Math.atan2(t,a),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function Ir(a,t,e,s,i,n,r,o){let h;if(et.cachesBoundsOfCurve&&(h=[...arguments].join(),$s.boundsOfCurveCache[h]))return $s.boundsOfCurveCache[h];const l=Math.sqrt,c=Math.abs,u=[],d=[[0,0],[0,0]];let f=6*a-12*e+6*i,g=-3*a+9*e-9*i+3*r,p=3*e-3*a;for(let _=0;_<2;++_){if(_>0&&(f=6*t-12*s+6*n,g=-3*t+9*s-9*n+3*o,p=3*s-3*t),c(g)<1e-12){if(c(f)<1e-12)continue;const P=-p/f;0<P&&P<1&&u.push(P);continue}const S=f*f-4*p*g;if(S<0)continue;const A=l(S),T=(-f+A)/(2*g);0<T&&T<1&&u.push(T);const k=(-f-A)/(2*g);0<k&&k<1&&u.push(k)}let b=u.length;const m=b,v=uh(a,t,e,s,i,n,r,o);for(;b--;){const{x:_,y:S}=v(u[b]);d[0][b]=_,d[1][b]=S}d[0][m]=a,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=o;const y=[new C(Math.min(...d[0]),Math.min(...d[1])),new C(Math.max(...d[0]),Math.max(...d[1]))];return et.cachesBoundsOfCurve&&($s.boundsOfCurveCache[h]=y),y}const Ru=(a,t,e)=>{let[s,i,n,r,o,h,l,c]=e;const u=((d,f,g,p,b,m,v)=>{if(g===0||p===0)return[];let y=0,_=0,S=0;const A=Math.PI,T=v*Zn,k=ce(T),P=le(T),B=.5*(-P*d-k*f),F=.5*(-P*f+k*d),I=g**2,O=p**2,D=F**2,z=B**2,M=I*O-I*D-O*z;let R=Math.abs(g),U=Math.abs(p);if(M<0){const Zt=Math.sqrt(1-M/(I*O));R*=Zt,U*=Zt}else S=(b===m?-1:1)*Math.sqrt(M/(I*D+O*z));const ht=S*R*F/U,dt=-S*U*B/R,E=P*ht-k*dt+.5*d,H=k*ht+P*dt+.5*f;let V=lh(1,0,(B-ht)/R,(F-dt)/U),Q=lh((B-ht)/R,(F-dt)/U,(-B-ht)/R,(-F-dt)/U);m===0&&Q>0?Q-=2*A:m===1&&Q<0&&(Q+=2*A);const kt=Math.ceil(Math.abs(Q/A*2)),rt=[],N=Q/kt,ft=8/3*Math.sin(N/4)*Math.sin(N/4)/Math.sin(N/2);let It=V+N;for(let Zt=0;Zt<kt;Zt++)rt[Zt]=Du(V,It,P,k,R,U,E,H,ft,y,_),y=rt[Zt][5],_=rt[Zt][6],V=It,It+=N;return rt})(l-a,c-t,i,n,o,h,r);for(let d=0,f=u.length;d<f;d++)u[d][1]+=a,u[d][2]+=t,u[d][3]+=a,u[d][4]+=t,u[d][5]+=a,u[d][6]+=t;return u},ch=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const l of a){const c=[...l];let u;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],u=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],u=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],u=["L",t,e];break;case"m":c[1]+=t,c[2]+=e;case"M":t=c[1],e=c[2],s=c[1],i=c[2],u=["M",t,e];break;case"c":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e,c[5]+=t,c[6]+=e;case"C":o=c[3],h=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],o,h,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":r==="C"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[3],e=c[4],u=["C",o,h,c[1],c[2],t,e],o=u[3],h=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":o=c[1],h=c[2],t=c[3],e=c[4],u=["Q",o,h,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[1],e=c[2],u=["Q",o,h,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":Ru(t,e,c).forEach((d=>n.push(d))),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=i,u=["Z"]}u?(n.push(u),r=u[0]):r=""}return n},tn=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),uh=(a,t,e,s,i,n,r,o)=>h=>{const l=h**3,c=(f=>3*f**2*(1-f))(h),u=(f=>3*f*(1-f)**2)(h),d=(f=>(1-f)**3)(h);return new C(r*l+i*c+e*u+a*d,o*l+n*c+s*u+t*d)},dh=a=>a**2,fh=a=>2*a*(1-a),gh=a=>(1-a)**2,Lu=(a,t,e,s,i,n,r,o)=>h=>{const l=dh(h),c=fh(h),u=gh(h),d=3*(u*(e-a)+c*(i-e)+l*(r-i)),f=3*(u*(s-t)+c*(n-s)+l*(o-n));return Math.atan2(f,d)},Fu=(a,t,e,s,i,n)=>r=>{const o=dh(r),h=fh(r),l=gh(r);return new C(i*o+e*h+a*l,n*o+s*h+t*l)},Iu=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),l=2*(o*(s-t)+r*(n-s));return Math.atan2(l,h)},ph=(a,t,e)=>{let s=new C(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=tn(s.x,s.y,r.x,r.y),s=r}return i},Nu=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=w({},n),o=.01,h=0;const l=a.iterator,c=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=tn(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return w(w({},r),{},{angle:c(h)})},Nr=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const l of a){const c={x:i,y:n,command:l[0],length:0};switch(l[0]){case"M":e=c,e.x=r=i=l[1],e.y=o=n=l[2];break;case"L":e=c,e.length=tn(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=uh(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=c,e.iterator=t,e.angleFinder=Lu(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=ph(t,i,n),i=l[5],n=l[6];break;case"Q":t=Fu(i,n,l[1],l[2],l[3],l[4]),e=c,e.iterator=t,e.angleFinder=Iu(i,n,l[1],l[2],l[3],l[4]),e.length=ph(t,i,n),i=l[3],n=l[4];break;case"Z":e=c,e.destX=r,e.destY=o,e.length=tn(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},mh=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Nr(a),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=a[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return w(w({},new C(i.x,i.y).lerp(new C(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return w(w({},new C(i.x,i.y).lerp(new C(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return Nu(i,t)}},ju=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),bh=new RegExp(Pu,"g"),Bu=new RegExp(fe,"gi"),Hu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},vh=a=>{var t;const e=[],s=(t=a.match(ju))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=Hu[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){bh.lastIndex=0;for(let h=null;h=bh.exec(i);)o.push(...h.slice(1))}else o=i.match(Bu)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),c=Ou[n];l[0]=h>0&&c?c:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},zu=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new C(a[0]),s=new C(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let l;for(h&&(i=a[2].x<s.x?-1:a[2].x===s.x?0:1,n=a[2].y<s.y?-1:a[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),l=1;l<o;l++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=a[l],l+1<a.length&&(s=a[l+1])}return h&&(i=e.x>a[l-2].x?1:e.x===a[l-2].x?0:-1,n=e.y>a[l-2].y?1:e.y===a[l-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},yh=(a,t)=>a.map((e=>e.map(((s,i)=>i===0||t===void 0?s:ot(s,t))).join(" "))).join(" ");function en(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach((s=>{let[i,n]=s;return e.setProperty(i,n)})))}const Gu=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function _h(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||es,s=new(Ys()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=es};if(i&&i.aborted)throw new Kn("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=es)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const sn=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=is(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Bt,i),s.set(Qt,n),s.angle=r,s.skewX=o,s.skewY=0}})(a),e=e.transform(a.transformMatrix)),delete a.transformMatrix,t&&(a.scaleX*=t.scaleX,a.scaleY*=t.scaleY,a.cropX=t.cropX,a.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,a.width=t.width,a.height=t.height),a.setPositionByOrigin(e,$,$)};var Vu=Object.freeze({__proto__:null,addTransformToObject:na,animate:Er,animateColor:La,applyTransformToObject:Ms,calcAngleBetweenVectors:Vi,calcDimensionsMatrix:Js,calcPlaneChangeMatrix:ei,calcVectorRotation:Ea,cancelAnimFrame:Vo,capValue:ls,composeMatrix:$o,copyCanvasElement:a=>{var t;const e=te(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:le,createCanvasElement:Se,createImage:Wo,createRotateMatrix:ns,createScaleMatrix:Ri,createSkewXMatrix:ar,createSkewYMatrix:hr,createTranslateMatrix:Ts,createVector:zi,crossProduct:Ps,degreesToRadians:pt,dotProduct:ka,ease:Pc,enlivenObjectEnlivables:Qs,enlivenObjects:Es,findScaleToCover:hh,findScaleToFit:ah,getBoundsOfCurve:Ir,getOrthonormalVector:wr,getPathSegmentsInfo:Nr,getPointOnPath:mh,getPointer:sa,getRandomInt:Gu,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-We;a%2==0&&(s+=e/2);const i=new Array(a+1);for(let n=0;n<a;n++){const r=n*e+s,{x:o,y:h}=new C(le(r),ce(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:zu,getSvgAttributes:a=>{const t=["instantiated_by_use","style","id","class"];switch(a){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:Wi,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new ee(a,t),hasStyleChanged:qi,invertTransform:$t,isBetweenVectors:xr,isIdentityMatrix:Xo,isTouchEvent:Li,isTransparent:Va,joinPath:yh,loadImage:Zs,magnitude:Gi,makeBoundingBoxFromPoints:Ae,makePathSimpler:ch,matrixToSVG:ks,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),dr(i,(e=i.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const n=s.inverted&&i.inverted;return n&&(s.inverted=i.inverted=!1),new ee([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:vt,multiplyTransformMatrixArray:Di,parsePath:vh,parsePreserveAspectRatioAttribute:pr,parseUnit:zt,pick:rs,projectStrokeOnPoints:Ua,qrDecompose:is,radiansToDegrees:Ce,removeFromArray:ss,removeTransformFromObject:(a,t)=>{const e=$t(t),s=vt(e,a.calcOwnMatrix());Ms(a,s)},removeTransformMatrixForSvgParsing:sn,request:_h,requestAnimFrame:Ks,resetObjectTransform:ra,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:_r,saveObjectTransform:ur,sendObjectToPlane:dr,sendPointToPlane:as,sendVectorToPlane:oa,setStyle:en,sin:ce,sizeAfterTransform:Fi,string:ru,stylesFromArray:qa,stylesToArray:$a,toBlob:or,toDataURL:rr,toFixed:ot,transformPath:(a,t,e)=>(e&&(t=vt(t,[1,0,0,1,-e.x,-e.y])),a.map((s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:o}=Mt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i}))),transformPoint:Mt});class Wu extends ea{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),x(this,"upper",void 0),x(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=Se();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=xs().createElement("div");return t.setAttribute("data-fabric","wrapper"),en(t,{position:"relative"}),ta(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;en(t,w(w({},s),{},{"touch-action":i?"manipulation":jt})),ta(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Qo(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),cr(this.upper.el,t),cr(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:i}=this.upper;super.cleanupDOM(t),e.removeChild(i),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),xe().dispose(this.upper.el),delete this.upper,delete this.container}}class nn extends ti{constructor(){super(...arguments),x(this,"targets",[]),x(this,"_hoveredTargets",[]),x(this,"_currentTransform",null),x(this,"_groupSelector",null),x(this,"contextTopDirty",!1)}static getDefaults(){return w(w({},super.getDefaults()),nn.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new Wu(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter((e=>!e.group&&e!==t)).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const i=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+i,-s+i),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const o=Math.round(i*this.getRetinaScaling());return Va(n,o,o,o)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find((s=>!!s&&t[s]===!0)):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),i=this._activeObject;return!!(!e||e&&i&&s.length>1&&s.indexOf(e)===-1&&i!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&i&&i!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let i;return e===ki||e===Bt||e===Qt||e===qs?i=this.centeredScaling||t.centeredScaling:e===sr&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=bt:["mr","tr","br"].includes(e)&&(s.x=it),["tl","mt","tr"].includes(e)?s.y=tr:["bl","mb","br"].includes(e)&&(s.y=Yt)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?as(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},h=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):_c,l=((f,g,p,b)=>{if(!g||!f)return"drag";const m=b.controls[g];return m.getActionName(p,m,b)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,l,c)?{x:$,y:$}:this._getOriginFromCorner(e,r),d={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:pt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:w(w({},ur(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new C(e,s).transform(this.viewportTransform),o=new C(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),c=Math.min(r.y,o.y),u=Math.max(r.x,o.x),d=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,c,u-l,d-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,c+=h,u-=h,d-=h,Pt.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,c,u-l,d-c))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,Li(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,h,l]=s,c=Math.atan2(o.y-r.y,o.x-r.x),u=le(c)*n,d=ce(c)*n,f=u+d,g=u-d;s=[new C(r.x-g,r.y-f),new C(o.x+f,o.y-g),new C(h.x+g,h.y+f),new C(l.x-f,l.y+g)]}return gt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,as(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(Oi(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&Oi(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Oi(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=sa(t),r=i.width||0,o=i.height||0;r&&o||(Yt in i&&tr in i&&(o=Math.abs(i.top-i.bottom)),bt in i&&it in i&&(r=Math.abs(i.right-i.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=as(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new C(1,1):new C(s.width/r,s.height/o);return n.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Se(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return os(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach((h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),o.push(h))})),n.forEach((h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))})),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:o})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:o})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,os(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),os(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const i=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),i}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,i={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",i),s.fire(Mi,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;os(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const i=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,s);return t.set(i),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&os(e)&&this._activeObject===e){const s=rs(t,["angle","flipX","flipY",it,Bt,Qt,Ss,Cs,Yt]);return na(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}x(nn,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Xu{constructor(t){x(this,"targets",[]),x(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach((t=>{t.isEditing&&t.exitEditing()}))}add(t){this.targets.push(t)}remove(t){this.unregister(t),ss(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const Uu=["target","oldTarget","fireCanvas","e"],se={passive:!1},Fs=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},$e=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.addEventListener(...e)},oe=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.removeEventListener(...e)},Yu={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class jr extends nn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),x(this,"_isClick",void 0),x(this,"textEditingManager",new Xu(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach((e=>{this[e]=this[e].bind(this)})),this.addOrRemove($e,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Zo(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,se),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,se)}removeListeners(){this.addOrRemove(oe,"remove");const t=this._getEventPrefix(),e=ue(this.upperCanvasEl);oe(e,"".concat(t,"up"),this._onMouseUp),oe(e,"touchend",this._onTouchEnd,se),oe(e,"".concat(t,"move"),this._onMouseMove,se),oe(e,"touchmove",this._onMouseMove,se),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=w({e:t},Fs(this,t));this.fire("mouse:out",w(w({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",w({},s)),this._hoveredTargets.forEach((i=>{this.fire("mouse:out",w(w({},s),{},{target:i})),i&&i.fire("mouseout",w({},s))})),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",w({e:t},Fs(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void $e(this.upperCanvasEl,"drag",this._onDragProgress)}ia(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&s?.clearContextTop();const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==jt,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};oe(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",w({e:t,target:e,subTargets:s,dragSource:this._dragSource},Fs(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&ia(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=ue(i);$e(r,"touchend",this._onTouchEnd,se),e&&$e(r,"touchmove",this._onMouseMove,se),oe(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();oe(e,"".concat(s,"move"),this._onMouseMove,se);const i=ue(e);$e(i,"".concat(s,"up"),this._onMouseUp),$e(i,"".concat(s,"move"),this._onMouseMove,se)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=ue(this.upperCanvasEl);oe(s,"touchend",this._onTouchEnd,se),oe(s,"touchmove",this._onMouseMove,se),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((()=>{$e(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0}),400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=ue(this.upperCanvasEl);oe(i,"".concat(s,"up"),this._onMouseUp),oe(i,"".concat(s,"move"),this._onMouseMove,se),$e(e,"".concat(s,"move"),this._onMouseMove,se)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Li(t)),{key:u,control:d}=c||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(d){const f=d.getMouseUpHandler(t,n,d);f&&(o=this.getScenePoint(t),f.call(d,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const c=s.target&&s.target.controls[s.corner],u=c&&c.getMouseUpHandler(t,s.target,c);o=o||this.getScenePoint(t),u&&u.call(c,t,s,o.x,o.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=w(w(w({e:t,target:i,subTargets:n},Fs(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const o=this.getScenePoint(t);this._groupSelector={x:o.x,y:o.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),Li(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const h=o?o.control:void 0,l=this.getScenePoint(t),c=h&&h.getMouseDownHandler(t,e,h);c&&c.call(h,t,this._currentTransform,l.x,l.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=as(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)n[o]===e||i[o]&&i[o]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=lt(e,Uu);const{targetIn:h,targetOut:l,canvasIn:c,canvasOut:u}=Yu[t],d=i!==s;if(i&&d){const f=w(w({},o),{},{e:r,target:i,nextTarget:s},Fs(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&d){const f=w(w({},o),{},{e:r,target:s,previousTarget:i},Fs(this,r));n&&this.fire(c,f),s.fire(h,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?as(e,void 0,i.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,n),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:i,actionHandler:n,target:r}=e,o=!!n&&n(t,e,s.x,s.y);o&&r.setCoords(),i==="drag"&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=os(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map((r=>{s=r.hoverCursor||s})),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=os(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(L.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new C(e,s),o=r.add(new C(i,n)),h=r.min(o),l=r.max(o).subtract(h),c=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(o)?c[0]?[c[0]]:[]:c.length>1?c.filter((d=>!d.onSelect({e:t}))).reverse():c;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=L.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const wh={x1:0,y1:0,x2:0,y2:0},$u=w(w({},wh),{},{r1:0,r2:0}),Is=(a,t)=>isNaN(a)&&typeof t=="number"?t:a;function xh(a){return a&&/%$/.test(a)&&Number.isFinite(parseFloat(a))}function Sh(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(xh(a)?100:1):NaN;return ls(0,Is(e,t),1)}const qu=/\s*;\s*/,Ku=/\s*:\s*/;function Ju(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(qu);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(Ku).map((c=>c.trim()));h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new nt(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Sh(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Is(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function Zu(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Sh(t,1);for(let n=s.length;n--;)e.push(Ju(s[n],i));return e}function Ch(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Ah(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function pe(a,t){return a.getAttribute(t)}function Qu(a,t){return(function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.entries(e).reduce(((h,l)=>{let[c,u]=l;if(u==="Infinity")i=1;else if(u==="-Infinity")i=0;else{const d=typeof u=="string";i=d?parseFloat(u):u,d&&xh(u)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))}return h[c]=i,h}),{})})(Ch(a)==="linear"?(function(e){return{x1:pe(e,"x1")||0,y1:pe(e,"y1")||0,x2:pe(e,"x2")||"100%",y2:pe(e,"y2")||0}})(a):(function(e){return{x1:pe(e,"fx")||pe(e,"cx")||"50%",y1:pe(e,"fy")||pe(e,"cy")||"50%",r1:0,x2:pe(e,"cx")||"50%",y2:pe(e,"cy")||"50%",r2:pe(e,"r")||"50%"}})(a),w(w({},t),{},{gradientUnits:Ah(a)}))}class ci{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:w(w({},e==="radial"?$u:wh),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(Ue()):Ue()})}addColorStop(t){for(const e in t){const s=new nt(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return w(w({},rs(this,t)),{},{type:this.type,coords:w({},this.coords),colorStops:this.colorStops.map((e=>w({},e))),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():Nt.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map((u=>w({},u))).sort(((u,d)=>u.offset-d.offset));let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(ks(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',d,'" x2="',f,'" y2="',g,`">
46
+ `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=ct(t,ku);return Promise.all([Es(i,e),Qs(r,e)]).then((o=>{let[h,l]=o;const c=new this(h,w(w(w({},r),l),{},{layoutManager:new Mu}));if(n){const u=L.getClass(n.type),d=L.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new hi;return c.layoutManager.subscribeTargets({type:je,target:c,targets:c.getObjects()}),c.setCoords(),c}))}}x(ee,"type","Group"),x(ee,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),L.setClass(ee);const ah=(a,t)=>Math.min(t.width/a.width,t.height/a.height),hh=(a,t)=>Math.max(t.width/a.width,t.height/a.height),Fr="\\s*,?\\s*",li="".concat(Fr,"(").concat(fe,")"),Pu="".concat(li).concat(li).concat(li).concat(Fr,"([01])").concat(Fr,"([01])").concat(li).concat(li),Ou={m:"l",M:"L"},Du=(a,t,e,s,i,n,r,o,h,l,c)=>{const u=le(a),d=ce(a),f=le(t),g=ce(t),p=e*i*f-s*n*g+r,b=s*i*f+e*n*g+o;return["C",l+h*(-e*i*d-s*n*u),c+h*(-s*i*d+e*n*u),p+h*(e*i*g+s*n*f),b+h*(s*i*g-e*n*f),p,b]},lh=(a,t,e,s)=>{const i=Math.atan2(t,a),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function Ir(a,t,e,s,i,n,r,o){let h;if(et.cachesBoundsOfCurve&&(h=[...arguments].join(),$s.boundsOfCurveCache[h]))return $s.boundsOfCurveCache[h];const l=Math.sqrt,c=Math.abs,u=[],d=[[0,0],[0,0]];let f=6*a-12*e+6*i,g=-3*a+9*e-9*i+3*r,p=3*e-3*a;for(let _=0;_<2;++_){if(_>0&&(f=6*t-12*s+6*n,g=-3*t+9*s-9*n+3*o,p=3*s-3*t),c(g)<1e-12){if(c(f)<1e-12)continue;const P=-p/f;0<P&&P<1&&u.push(P);continue}const S=f*f-4*p*g;if(S<0)continue;const A=l(S),T=(-f+A)/(2*g);0<T&&T<1&&u.push(T);const k=(-f-A)/(2*g);0<k&&k<1&&u.push(k)}let b=u.length;const m=b,v=uh(a,t,e,s,i,n,r,o);for(;b--;){const{x:_,y:S}=v(u[b]);d[0][b]=_,d[1][b]=S}d[0][m]=a,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=o;const y=[new C(Math.min(...d[0]),Math.min(...d[1])),new C(Math.max(...d[0]),Math.max(...d[1]))];return et.cachesBoundsOfCurve&&($s.boundsOfCurveCache[h]=y),y}const Ru=(a,t,e)=>{let[s,i,n,r,o,h,l,c]=e;const u=((d,f,g,p,b,m,v)=>{if(g===0||p===0)return[];let y=0,_=0,S=0;const A=Math.PI,T=v*Zn,k=ce(T),P=le(T),B=.5*(-P*d-k*f),F=.5*(-P*f+k*d),I=g**2,O=p**2,D=F**2,z=B**2,M=I*O-I*D-O*z;let R=Math.abs(g),U=Math.abs(p);if(M<0){const Pt=Math.sqrt(1-M/(I*O));R*=Pt,U*=Pt}else S=(b===m?-1:1)*Math.sqrt(M/(I*D+O*z));const lt=S*R*F/U,ft=-S*U*B/R,E=P*lt-k*ft+.5*d,H=k*lt+P*ft+.5*f;let V=lh(1,0,(B-lt)/R,(F-ft)/U),Q=lh((B-lt)/R,(F-ft)/U,(-B-lt)/R,(-F-ft)/U);m===0&&Q>0?Q-=2*A:m===1&&Q<0&&(Q+=2*A);const kt=Math.ceil(Math.abs(Q/A*2)),rt=[],N=Q/kt,ht=8/3*Math.sin(N/4)*Math.sin(N/4)/Math.sin(N/2);let Mt=V+N;for(let Pt=0;Pt<kt;Pt++)rt[Pt]=Du(V,Mt,P,k,R,U,E,H,ht,y,_),y=rt[Pt][5],_=rt[Pt][6],V=Mt,Mt+=N;return rt})(l-a,c-t,i,n,o,h,r);for(let d=0,f=u.length;d<f;d++)u[d][1]+=a,u[d][2]+=t,u[d][3]+=a,u[d][4]+=t,u[d][5]+=a,u[d][6]+=t;return u},ch=a=>{let t=0,e=0,s=0,i=0;const n=[];let r,o=0,h=0;for(const l of a){const c=[...l];let u;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],u=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],u=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],u=["L",t,e];break;case"m":c[1]+=t,c[2]+=e;case"M":t=c[1],e=c[2],s=c[1],i=c[2],u=["M",t,e];break;case"c":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e,c[5]+=t,c[6]+=e;case"C":o=c[3],h=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],o,h,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":r==="C"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[3],e=c[4],u=["C",o,h,c[1],c[2],t,e],o=u[3],h=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":o=c[1],h=c[2],t=c[3],e=c[4],u=["Q",o,h,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(o=2*t-o,h=2*e-h):(o=t,h=e),t=c[1],e=c[2],u=["Q",o,h,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":Ru(t,e,c).forEach((d=>n.push(d))),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=i,u=["Z"]}u?(n.push(u),r=u[0]):r=""}return n},tn=(a,t,e,s)=>Math.sqrt((e-a)**2+(s-t)**2),uh=(a,t,e,s,i,n,r,o)=>h=>{const l=h**3,c=(f=>3*f**2*(1-f))(h),u=(f=>3*f*(1-f)**2)(h),d=(f=>(1-f)**3)(h);return new C(r*l+i*c+e*u+a*d,o*l+n*c+s*u+t*d)},dh=a=>a**2,fh=a=>2*a*(1-a),gh=a=>(1-a)**2,Lu=(a,t,e,s,i,n,r,o)=>h=>{const l=dh(h),c=fh(h),u=gh(h),d=3*(u*(e-a)+c*(i-e)+l*(r-i)),f=3*(u*(s-t)+c*(n-s)+l*(o-n));return Math.atan2(f,d)},Fu=(a,t,e,s,i,n)=>r=>{const o=dh(r),h=fh(r),l=gh(r);return new C(i*o+e*h+a*l,n*o+s*h+t*l)},Iu=(a,t,e,s,i,n)=>r=>{const o=1-r,h=2*(o*(e-a)+r*(i-e)),l=2*(o*(s-t)+r*(n-s));return Math.atan2(l,h)},ph=(a,t,e)=>{let s=new C(t,e),i=0;for(let n=1;n<=100;n+=1){const r=a(n/100);i+=tn(s.x,s.y,r.x,r.y),s=r}return i},Nu=(a,t)=>{let e,s=0,i=0,n={x:a.x,y:a.y},r=w({},n),o=.01,h=0;const l=a.iterator,c=a.angleFinder;for(;i<t&&o>1e-4;)r=l(s),h=s,e=tn(n.x,n.y,r.x,r.y),e+i>t?(s-=o,o/=2):(n=r,s+=o,i+=e);return w(w({},r),{},{angle:c(h)})},Nr=a=>{let t,e,s=0,i=0,n=0,r=0,o=0;const h=[];for(const l of a){const c={x:i,y:n,command:l[0],length:0};switch(l[0]){case"M":e=c,e.x=r=i=l[1],e.y=o=n=l[2];break;case"L":e=c,e.length=tn(i,n,l[1],l[2]),i=l[1],n=l[2];break;case"C":t=uh(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e=c,e.iterator=t,e.angleFinder=Lu(i,n,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=ph(t,i,n),i=l[5],n=l[6];break;case"Q":t=Fu(i,n,l[1],l[2],l[3],l[4]),e=c,e.iterator=t,e.angleFinder=Iu(i,n,l[1],l[2],l[3],l[4]),e.length=ph(t,i,n),i=l[3],n=l[4];break;case"Z":e=c,e.destX=r,e.destY=o,e.length=tn(i,n,r,o),i=r,n=o}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},mh=function(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Nr(a),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=a[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return w(w({},new C(i.x,i.y).lerp(new C(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return w(w({},new C(i.x,i.y).lerp(new C(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return Nu(i,t)}},ju=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),bh=new RegExp(Pu,"g"),Bu=new RegExp(fe,"gi"),Hu={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},vh=a=>{var t;const e=[],s=(t=a.match(ju))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=Hu[n.toLowerCase()];let o=[];if(n==="a"||n==="A"){bh.lastIndex=0;for(let h=null;h=bh.exec(i);)o.push(...h.slice(1))}else o=i.match(Bu)||[];for(let h=0;h<o.length;h+=r){const l=new Array(r),c=Ou[n];l[0]=h>0&&c?c:n;for(let u=0;u<r;u++)l[u+1]=parseFloat(o[h+u]);e.push(l)}}return e},zu=function(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new C(a[0]),s=new C(a[1]),i=1,n=0;const r=[],o=a.length,h=o>2;let l;for(h&&(i=a[2].x<s.x?-1:a[2].x===s.x?0:1,n=a[2].y<s.y?-1:a[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),l=1;l<o;l++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=a[l],l+1<a.length&&(s=a[l+1])}return h&&(i=e.x>a[l-2].x?1:e.x===a[l-2].x?0:-1,n=e.y>a[l-2].y?1:e.y===a[l-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},yh=(a,t)=>a.map((e=>e.map(((s,i)=>i===0||t===void 0?s:ot(s,t))).join(" "))).join(" ");function en(a,t){const e=a.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach((s=>{let[i,n]=s;return e.setProperty(i,n)})))}const Gu=(a,t)=>Math.floor(Math.random()*(t-a+1))+a;function _h(a){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||es,s=new(Ys()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=es};if(i&&i.aborted)throw new Kn("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=es)},s.onerror=s.ontimeout=r,s.open("get",a,!0),s.send(),s}const sn=(a,t)=>{let e=a._findCenterFromElement();a.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:o}=is(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Ht,i),s.set(Qt,n),s.angle=r,s.skewX=o,s.skewY=0}})(a),e=e.transform(a.transformMatrix)),delete a.transformMatrix,t&&(a.scaleX*=t.scaleX,a.scaleY*=t.scaleY,a.cropX=t.cropX,a.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,a.width=t.width,a.height=t.height),a.setPositionByOrigin(e,$,$)};var Vu=Object.freeze({__proto__:null,addTransformToObject:na,animate:Er,animateColor:La,applyTransformToObject:Ms,calcAngleBetweenVectors:Vi,calcDimensionsMatrix:Js,calcPlaneChangeMatrix:ei,calcVectorRotation:Ea,cancelAnimFrame:Vo,capValue:ls,composeMatrix:$o,copyCanvasElement:a=>{var t;const e=te(a);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(a,0,0),e},cos:le,createCanvasElement:Se,createImage:Wo,createRotateMatrix:ns,createScaleMatrix:Ri,createSkewXMatrix:ar,createSkewYMatrix:hr,createTranslateMatrix:Ts,createVector:zi,crossProduct:Ps,degreesToRadians:pt,dotProduct:ka,ease:Pc,enlivenObjectEnlivables:Qs,enlivenObjects:Es,findScaleToCover:hh,findScaleToFit:ah,getBoundsOfCurve:Ir,getOrthonormalVector:wr,getPathSegmentsInfo:Nr,getPointOnPath:mh,getPointer:sa,getRandomInt:Gu,getRegularPolygonPath:(a,t)=>{const e=2*Math.PI/a;let s=-We;a%2==0&&(s+=e/2);const i=new Array(a+1);for(let n=0;n<a;n++){const r=n*e+s,{x:o,y:h}=new C(le(r),ce(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",o,h]}return i[a]=["Z"],i},getSmoothPathFromPoints:zu,getSvgAttributes:a=>{const t=["instantiated_by_use","style","id","class"];switch(a){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:Wi,groupSVGElements:(a,t)=>a&&a.length===1?a[0]:new ee(a,t),hasStyleChanged:qi,invertTransform:qt,isBetweenVectors:xr,isIdentityMatrix:Xo,isTouchEvent:Li,isTransparent:Va,joinPath:yh,loadImage:Zs,magnitude:Gi,makeBoundingBoxFromPoints:Ae,makePathSimpler:ch,matrixToSVG:ks,mergeClipPaths:(a,t)=>{var e;let s=a,i=t;s.inverted&&!i.inverted&&(s=t,i=a),dr(i,(e=i.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const n=s.inverted&&i.inverted;return n&&(s.inverted=i.inverted=!1),new ee([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:vt,multiplyTransformMatrixArray:Di,parsePath:vh,parsePreserveAspectRatioAttribute:pr,parseUnit:Gt,pick:rs,projectStrokeOnPoints:Ua,qrDecompose:is,radiansToDegrees:Ce,removeFromArray:ss,removeTransformFromObject:(a,t)=>{const e=qt(t),s=vt(e,a.calcOwnMatrix());Ms(a,s)},removeTransformMatrixForSvgParsing:sn,request:_h,requestAnimFrame:Ks,resetObjectTransform:ra,rotatePoint:(a,t,e)=>a.rotate(e,t),rotateVector:_r,saveObjectTransform:ur,sendObjectToPlane:dr,sendPointToPlane:as,sendVectorToPlane:oa,setStyle:en,sin:ce,sizeAfterTransform:Fi,string:ru,stylesFromArray:qa,stylesToArray:$a,toBlob:or,toDataURL:rr,toFixed:ot,transformPath:(a,t,e)=>(e&&(t=vt(t,[1,0,0,1,-e.x,-e.y])),a.map((s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:o}=Ot({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=o}return i}))),transformPoint:Ot});class Wu extends ea{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),x(this,"upper",void 0),x(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=Se();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=xs().createElement("div");return t.setAttribute("data-fabric","wrapper"),en(t,{position:"relative"}),ta(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;en(t,w(w({},s),{},{"touch-action":i?"manipulation":Bt})),ta(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Qo(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),cr(this.upper.el,t),cr(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:i}=this.upper;super.cleanupDOM(t),e.removeChild(i),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),xe().dispose(this.upper.el),delete this.upper,delete this.container}}class nn extends ti{constructor(){super(...arguments),x(this,"targets",[]),x(this,"_hoveredTargets",[]),x(this,"_currentTransform",null),x(this,"_groupSelector",null),x(this,"contextTopDirty",!1)}static getDefaults(){return w(w({},super.getDefaults()),nn.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new Wu(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter((e=>!e.group&&e!==t)).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const i=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+i,-s+i),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const o=Math.round(i*this.getRetinaScaling());return Va(n,o,o,o)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find((s=>!!s&&t[s]===!0)):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),i=this._activeObject;return!!(!e||e&&i&&s.length>1&&s.indexOf(e)===-1&&i!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&i&&i!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let i;return e===ki||e===Ht||e===Qt||e===qs?i=this.centeredScaling||t.centeredScaling:e===sr&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=bt:["mr","tr","br"].includes(e)&&(s.x=it),["tl","mt","tr"].includes(e)?s.y=tr:["bl","mb","br"].includes(e)&&(s.y=$t)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?as(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},h=s&&o?(i=o.getActionHandler(t,e,o))===null||i===void 0?void 0:i.bind(o):_c,l=((f,g,p,b)=>{if(!g||!f)return"drag";const m=b.controls[g];return m.getActionName(p,m,b)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,l,c)?{x:$,y:$}:this._getOriginFromCorner(e,r),d={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:pt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:w(w({},ur(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new C(e,s).transform(this.viewportTransform),o=new C(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(r.x,o.x),c=Math.min(r.y,o.y),u=Math.max(r.x,o.x),d=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,c,u-l,d-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,c+=h,u-=h,d-=h,Dt.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,c,u-l,d-c))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,Li(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,o,h,l]=s,c=Math.atan2(o.y-r.y,o.x-r.x),u=le(c)*n,d=ce(c)*n,f=u+d,g=u-d;s=[new C(r.x-g,r.y-f),new C(o.x+f,o.y-g),new C(h.x+g,h.y+f),new C(l.x-f,l.y+g)]}return gt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,as(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(Oi(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&Oi(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Oi(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=sa(t),r=i.width||0,o=i.height||0;r&&o||($t in i&&tr in i&&(o=Math.abs(i.top-i.bottom)),bt in i&&it in i&&(r=Math.abs(i.right-i.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=as(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const l=r===0||o===0?new C(1,1):new C(s.width/r,s.height/o);return n.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Se(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return os(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach((h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),o.push(h))})),n.forEach((h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))})),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:o})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:o})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,os(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),os(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const i=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),i}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,i={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",i),s.fire(Mi,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;os(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const i=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,s);return t.set(i),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&os(e)&&this._activeObject===e){const s=rs(t,["angle","flipX","flipY",it,Ht,Qt,Ss,Cs,$t]);return na(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}x(nn,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Xu{constructor(t){x(this,"targets",[]),x(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach((t=>{t.isEditing&&t.exitEditing()}))}add(t){this.targets.push(t)}remove(t){this.unregister(t),ss(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const Uu=["target","oldTarget","fireCanvas","e"],se={passive:!1},Fs=(a,t)=>{const e=a.getViewportPoint(t),s=a.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},$e=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.addEventListener(...e)},oe=function(a){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return a.removeEventListener(...e)},Yu={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class jr extends nn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),x(this,"_isClick",void 0),x(this,"textEditingManager",new Xu(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach((e=>{this[e]=this[e].bind(this)})),this.addOrRemove($e,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Zo(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,se),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,se)}removeListeners(){this.addOrRemove(oe,"remove");const t=this._getEventPrefix(),e=ue(this.upperCanvasEl);oe(e,"".concat(t,"up"),this._onMouseUp),oe(e,"touchend",this._onTouchEnd,se),oe(e,"".concat(t,"move"),this._onMouseMove,se),oe(e,"touchmove",this._onMouseMove,se),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=w({e:t},Fs(this,t));this.fire("mouse:out",w(w({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",w({},s)),this._hoveredTargets.forEach((i=>{this.fire("mouse:out",w(w({},s),{},{target:i})),i&&i.fire("mouseout",w({},s))})),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",w({e:t},Fs(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void $e(this.upperCanvasEl,"drag",this._onDragProgress)}ia(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&s?.clearContextTop();const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Bt,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};oe(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(o=s),s.fire(e,r));for(let h=0;h<i.length;h++){const l=i[h];l.canDrop(t)&&(o=l),l.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",w({e:t,target:e,subTargets:s,dragSource:this._dragSource},Fs(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&ia(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=ue(i);$e(r,"touchend",this._onTouchEnd,se),e&&$e(r,"touchmove",this._onMouseMove,se),oe(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();oe(e,"".concat(s,"move"),this._onMouseMove,se);const i=ue(e);$e(i,"".concat(s,"up"),this._onMouseUp),$e(i,"".concat(s,"move"),this._onMouseMove,se)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=ue(this.upperCanvasEl);oe(s,"touchend",this._onTouchEnd,se),oe(s,"touchmove",this._onMouseMove,se),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((()=>{$e(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0}),400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=ue(this.upperCanvasEl);oe(i,"".concat(s,"up"),this._onMouseUp),oe(i,"".concat(s,"move"),this._onMouseMove,se),$e(e,"".concat(s,"move"),this._onMouseMove,se)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Li(t)),{key:u,control:d}=c||{};if(h=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),l=!0;else if(d){const f=d.getMouseUpHandler(t,n,d);f&&(o=this.getScenePoint(t),f.call(d,t,s,o.x,o.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const c=s.target&&s.target.controls[s.corner],u=c&&c.getMouseUpHandler(t,s.target,c);o=o||this.getScenePoint(t),u&&u.call(c,t,s,o.x,o.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),l?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=w(w(w({e:t,target:i,subTargets:n},Fs(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let o=0;o<n.length;o++)n[o]!==i&&n[o].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const o=this.getScenePoint(t);this._groupSelector={x:o.x,y:o.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const o=e.findControl(this.getViewportPoint(t),Li(t));if(e===this._activeObject&&(o||!r)){this._setupCurrentTransform(t,e,s);const h=o?o.control:void 0,l=this.getScenePoint(t),c=h&&h.getMouseDownHandler(t,e,h);c&&c.call(h,t,this._currentTransform,l.x,l.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=as(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let o=0;o<r;o++)n[o]===e||i[o]&&i[o]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:n[o],oldTarget:i[o]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let o=0;o<r;o++)this.fireSyntheticInOutEvents("drag",w(w({},e),{},{target:n[o],oldTarget:i[o]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,o=ct(e,Uu);const{targetIn:h,targetOut:l,canvasIn:c,canvasOut:u}=Yu[t],d=i!==s;if(i&&d){const f=w(w({},o),{},{e:r,target:i,nextTarget:s},Fs(this,r));n&&this.fire(u,f),i.fire(l,f)}if(s&&d){const f=w(w({},o),{},{e:r,target:s,previousTarget:i},Fs(this,r));n&&this.fire(c,f),s.fire(h,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?as(e,void 0,i.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,n),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:i,actionHandler:n,target:r}=e,o=!!n&&n(t,e,s.x,s.y);o&&r.setCoords(),i==="drag"&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=os(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map((r=>{s=r.hoverCursor||s})),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=os(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(L.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new C(e,s),o=r.add(new C(i,n)),h=r.min(o),l=r.max(o).subtract(h),c=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(o)?c[0]?[c[0]]:[]:c.length>1?c.filter((d=>!d.onSelect({e:t}))).reverse():c;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=L.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const wh={x1:0,y1:0,x2:0,y2:0},$u=w(w({},wh),{},{r1:0,r2:0}),Is=(a,t)=>isNaN(a)&&typeof t=="number"?t:a;function xh(a){return a&&/%$/.test(a)&&Number.isFinite(parseFloat(a))}function Sh(a,t){const e=typeof a=="number"?a:typeof a=="string"?parseFloat(a)/(xh(a)?100:1):NaN;return ls(0,Is(e,t),1)}const qu=/\s*;\s*/,Ku=/\s*:\s*/;function Ju(a,t){let e,s;const i=a.getAttribute("style");if(i){const r=i.split(qu);r[r.length-1]===""&&r.pop();for(let o=r.length;o--;){const[h,l]=r[o].split(Ku).map((c=>c.trim()));h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}const n=new nt(e||a.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Sh(a.getAttribute("offset"),0),color:n.toRgb(),opacity:Is(parseFloat(s||a.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function Zu(a,t){const e=[],s=a.getElementsByTagName("stop"),i=Sh(t,1);for(let n=s.length;n--;)e.push(Ju(s[n],i));return e}function Ch(a){return a.nodeName==="linearGradient"||a.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Ah(a){return a.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function pe(a,t){return a.getAttribute(t)}function Qu(a,t){return(function(e,s){let i,{width:n,height:r,gradientUnits:o}=s;return Object.entries(e).reduce(((h,l)=>{let[c,u]=l;if(u==="Infinity")i=1;else if(u==="-Infinity")i=0;else{const d=typeof u=="string";i=d?parseFloat(u):u,d&&xh(u)&&(i*=.01,o==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))}return h[c]=i,h}),{})})(Ch(a)==="linear"?(function(e){return{x1:pe(e,"x1")||0,y1:pe(e,"y1")||0,x2:pe(e,"x2")||"100%",y2:pe(e,"y2")||0}})(a):(function(e){return{x1:pe(e,"fx")||pe(e,"cx")||"50%",y1:pe(e,"fy")||pe(e,"cy")||"50%",r1:0,x2:pe(e,"cx")||"50%",y2:pe(e,"cy")||"50%",r2:pe(e,"r")||"50%"}})(a),w(w({},t),{},{gradientUnits:Ah(a)}))}class ci{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:w(w({},e==="radial"?$u:wh),i),colorStops:n,offsetX:r,offsetY:o,gradientTransform:h,id:l?"".concat(l,"_").concat(Ue()):Ue()})}addColorStop(t){for(const e in t){const s=new nt(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return w(w({},rs(this,t)),{},{type:this.type,coords:w({},this.coords),colorStops:this.colorStops.map((e=>w({},e))),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():jt.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map((u=>w({},u))).sort(((u,d)=>u.offset-d.offset));let o=-this.offsetX,h=-this.offsetY;var l;n==="objectBoundingBox"?(o/=t.width,h/=t.height):(o+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(o-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=o,i[5]-=h;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(ks(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',d,'" x2="',f,'" y2="',g,`">
47
47
  `)}else if(this.type==="radial"){const{x1:u,y1:d,x2:f,y2:g,r1:p,r2:b}=this.coords,m=p>b;s.push("<radialGradient ",c,' cx="',m?u:f,'" cy="',m?d:g,'" r="',m?p:b,'" fx="',m?f:u,'" fy="',m?g:d,`">
48
48
  `),m&&(r.reverse(),r.forEach((y=>{y.offset=1-y.offset})));const v=Math.min(p,b);if(v>0){const y=v/Math.max(p,b);r.forEach((_=>{_.offset+=y*(1-_.offset)}))}}return r.forEach((u=>{let{color:d,offset:f,opacity:g}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',d,g!==void 0?";stop-opacity: "+g:";",`"/>
49
49
  `)})),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
50
50
  `),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:o}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,o);return this.colorStops.forEach((l=>{let{color:c,opacity:u,offset:d}=l;h.addColorStop(d,u!==void 0?new nt(c).setAlpha(u).toRgba():c)})),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(w(w({},t),{},{colorStops:e?e.map((i=>w({},i))):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Ah(t),n=e._findCenterFromElement();return new this(w({id:t.getAttribute("id")||void 0,type:Ch(t),coords:Qu(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Zu(t,s.opacity),gradientUnits:i,gradientTransform:Ki(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}x(ci,"type","Gradient"),L.setClass(ci,"gradient"),L.setClass(ci,"linear"),L.setClass(ci,"radial");const td=["type","source","patternTransform"];class Br{get type(){return"pattern"}set type(t){De("warn","Setting type has no effect",t)}constructor(t){x(this,"repeat","repeat"),x(this,"offsetX",0),x(this,"offsetY",0),x(this,"crossOrigin",""),this.id=Ue(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return w(w({},rs(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:ot(this.offsetX,et.NUM_FRACTION_DIGITS),offsetY:ot(this.offsetY,et.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:i,repeat:n,id:r}=this,o=Is(this.offsetX/e,0),h=Is(this.offsetY/s,0),l=n==="repeat-y"||n==="no-repeat"?1+Math.abs(o||0):Is(i.width/e,0),c=n==="repeat-x"||n==="no-repeat"?1+Math.abs(h||0):Is(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(o,'" y="').concat(h,'" width="').concat(l,'" height="').concat(c,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
51
- `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=lt(t,td);const o=await Zs(i,w(w({},e),{},{crossOrigin:r.crossOrigin}));return new this(w(w({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}x(Br,"type","Pattern"),L.setClass(Br),L.setClass(Br,"pattern");const ed=["path","left","top"],sd=["d"];class cs extends Pt{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=lt(e,ed);super(),Object.assign(this,cs.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(it,i),typeof n=="number"&&this.set(Yt,n)}_setPath(t,e){this.path=ch(Array.isArray(t)?t:vh(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new C(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),{},{path:this.path.map((e=>e.slice()))})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=yh(this.path,et.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
52
- `)]}_getOffsetTransform(){const t=et.NUM_FRACTION_DIGITS;return" translate(".concat(ot(-this.pathOffset.x,t),", ").concat(ot(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:i}=this._calcDimensions();this.set({width:e,height:s,pathOffset:i}),t&&this.setPositionByOrigin(i,$,$)}_calcBoundsFromPath(){const t=[];let e=0,s=0,i=0,n=0;for(const r of this.path)switch(r[0]){case"L":i=r[1],n=r[2],t.push({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...Ir(i,n,r[1],r[2],r[3],r[4],r[5],r[6])),i=r[5],n=r[6];break;case"Q":t.push(...Ir(i,n,r[1],r[2],r[1],r[2],r[3],r[4])),i=r[3],n=r[4];break;case"Z":i=e,n=s}return Ae(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return w(w({},t),{},{pathOffset:new C(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,w(w(w({},lt(i,sd)),e),{},{left:void 0,top:void 0}))}}x(cs,"type","Path"),x(cs,"cacheProperties",[...Fe,"path","fillRule"]),x(cs,"ATTRIBUTE_NAMES",[...Ye,"d"]),L.setClass(cs),L.setSVGClass(cs);const id=["left","top","radius"],Th=["radius","startAngle","endAngle","counterClockwise"];class Be extends Pt{static getDefaults(){return w(w({},super.getDefaults()),Be.ownDefaults)}constructor(t){super(),Object.assign(this,Be.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,pt(this.startAngle),pt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Bt)}getRadiusY(){return this.get("radius")*this.get(Qt)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Th,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
51
+ `)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=ct(t,td);const o=await Zs(i,w(w({},e),{},{crossOrigin:r.crossOrigin}));return new this(w(w({},r),{},{patternTransform:n&&n.slice(0),source:o}))}}x(Br,"type","Pattern"),L.setClass(Br),L.setClass(Br,"pattern");const ed=["path","left","top"],sd=["d"];class cs extends Dt{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=ct(e,ed);super(),Object.assign(this,cs.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(it,i),typeof n=="number"&&this.set($t,n)}_setPath(t,e){this.path=ch(Array.isArray(t)?t:vh(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new C(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),{},{path:this.path.map((e=>e.slice()))})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=yh(this.path,et.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
52
+ `)]}_getOffsetTransform(){const t=et.NUM_FRACTION_DIGITS;return" translate(".concat(ot(-this.pathOffset.x,t),", ").concat(ot(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:i}=this._calcDimensions();this.set({width:e,height:s,pathOffset:i}),t&&this.setPositionByOrigin(i,$,$)}_calcBoundsFromPath(){const t=[];let e=0,s=0,i=0,n=0;for(const r of this.path)switch(r[0]){case"L":i=r[1],n=r[2],t.push({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...Ir(i,n,r[1],r[2],r[3],r[4],r[5],r[6])),i=r[5],n=r[6];break;case"Q":t.push(...Ir(i,n,r[1],r[2],r[1],r[2],r[3],r[4])),i=r[3],n=r[4];break;case"Z":i=e,n=s}return Ae(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return w(w({},t),{},{pathOffset:new C(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,w(w(w({},ct(i,sd)),e),{},{left:void 0,top:void 0}))}}x(cs,"type","Path"),x(cs,"cacheProperties",[...Fe,"path","fillRule"]),x(cs,"ATTRIBUTE_NAMES",[...Ye,"d"]),L.setClass(cs),L.setSVGClass(cs);const id=["left","top","radius"],Th=["radius","startAngle","endAngle","counterClockwise"];class Be extends Dt{static getDefaults(){return w(w({},super.getDefaults()),Be.ownDefaults)}constructor(t){super(),Object.assign(this,Be.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,pt(this.startAngle),pt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(Ht)}getRadiusY(){return this.get("radius")*this.get(Qt)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Th,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
53
53
  `];{const{radius:e}=this,s=pt(this.startAngle),i=pt(this.endAngle),n=le(s)*e,r=ce(s)*e,o=le(i)*e,h=ce(i)*e,l=t>180?1:0,c=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(l," ").concat(c," ").concat(o," ").concat(h,'" '),"COMMON_PARTS",` />
54
- `]}}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(w(w({},lt(i,id)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}x(Be,"type","Circle"),x(Be,"cacheProperties",[...Fe,...Th]),x(Be,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),x(Be,"ATTRIBUTE_NAMES",["cx","cy","r",...Ye]),L.setClass(Be),L.setSVGClass(Be);const nd=["x1","y1","x2","y2"],rd=["x1","y1","x2","y2"],Hr=["x1","x2","y1","y2"];class us extends Pt{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,us.ownDefaults),this.setOptions(n),this.x1=t,this.x2=s,this.y1=e,this.y2=i,this._setWidthHeight();const{left:r,top:o}=n;typeof r=="number"&&this.set(it,r),typeof o=="number"&&this.set(Yt,o)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:i}=this;this.width=Math.abs(s-t),this.height=Math.abs(i-e);const{left:n,top:r,width:o,height:h}=Ae([{x:t,y:e},{x:s,y:i}]),l=new C(n+o/2,r+h/2);this.setPositionByOrigin(l,$,$)}_set(t,e){return super._set(t,e),Hr.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var i;re(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(i=this.stroke)!==null&&i!==void 0?i:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new C((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
55
- `)]}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:o=0,y2:h=0}=i;return new this([n,r,o,h],lt(i,nd))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=lt(t,rd);return this._fromObject(w(w({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}x(us,"type","Line"),x(us,"cacheProperties",[...Fe,...Hr]),x(us,"ATTRIBUTE_NAMES",Ye.concat(Hr)),L.setClass(us),L.setSVGClass(us);class ds extends Pt{static getDefaults(){return w(w({},super.getDefaults()),ds.ownDefaults)}constructor(t){super(),Object.assign(this,ds.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}x(ds,"type","Triangle"),x(ds,"ownDefaults",{width:100,height:100}),L.setClass(ds),L.setSVGClass(ds);const Eh=["rx","ry"];class He extends Pt{static getDefaults(){return w(w({},super.getDefaults()),He.ownDefaults)}constructor(t){super(),Object.assign(this,He.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get(Bt)}getRy(){return this.get("ry")*this.get(Qt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Eh,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
56
- `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Re,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function od(a){if(!a)return[];const t=a.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}x(He,"type","Ellipse"),x(He,"cacheProperties",[...Fe,...Eh]),x(He,"ownDefaults",{rx:0,ry:0}),x(He,"ATTRIBUTE_NAMES",[...Ye,"cx","cy","rx","ry"]),L.setClass(He),L.setSVGClass(He);const ad=["left","top"],kh={exactBoundingBox:!1};class me extends Pt{static getDefaults(){return w(w({},super.getDefaults()),me.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"strokeDiff",void 0),Object.assign(this,me.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(it,s),typeof i=="number"&&this.set(Yt,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return Ua(this.points,t,this.isOpen())}_calcDimensions(t){t=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map((l=>l.projectedPoint)):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new C,strokeOffset:new C,strokeDiff:new C};const s=Ae(e),i=Js(w(w({},t),{},{scaleX:1,scaleY:1})),n=Ae(this.points.map((l=>Mt(l,i,!0)))),r=new C(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(pt(this.skewX)),h-=o*Math.tan(pt(this.skewY))),w(w({},s),{},{pathOffset:new C(o,h),strokeOffset:new C(n.left,n.top).subtract(new C(s.left,s.top)).multiply(r),strokeDiff:new C(s.width,s.height).subtract(new C(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Ae(this.points);return new C(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}),t&&this.setPositionByOrigin(new C(e+i/2,s+n/2),$,$)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new C(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some((o=>this.strokeUniform||this.constructor.layoutProperties.includes(o)))){var e,s;const{width:o,height:h}=this._calcDimensions(t);r=new C((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new C((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new C(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,i=super._set(t,e);return this.exactBoundingBox&&s&&((t===Bt||t===Qt)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),{},{points:this.points.map((e=>{let{x:s,y:i}=e;return{x:s,y:i}}))})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=et.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(ot(this.points[n].x-e,i),",",ot(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
57
- `)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(od(t.getAttribute("points")),w(w({},lt(Ne(t,this.ATTRIBUTE_NAMES,s),ad)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}x(me,"ownDefaults",kh),x(me,"type","Polyline"),x(me,"layoutProperties",[Ss,Cs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),x(me,"cacheProperties",[...Fe,"points"]),x(me,"ATTRIBUTE_NAMES",[...Ye]),L.setClass(me),L.setSVGClass(me);class rn extends me{isOpen(){return!1}}x(rn,"ownDefaults",kh),x(rn,"type","Polygon"),L.setClass(rn),L.setSVGClass(rn);class Mh extends Pt{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const c=e[h][l]||{};n++,c[t]!==void 0?(i?c[t]!==i&&(r=!1):i=c[t],c[t]===this[t]&&delete c[t]):r=!1,Object.keys(c).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=lr(w(w({},this._getStyleDeclaration(s,i)),e),(r=>r!==void 0));this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return w(w({},rs(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}x(Mh,"_styleProperties",wc);const hd=/ +/g,ld=/"/g;function zr(a,t,e,s,i){return" ".concat((function(n,r){let{left:o,top:h,width:l,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:et.NUM_FRACTION_DIGITS;const d=si(wt,n,!1),[f,g,p,b]=[o,h,l,c].map((m=>ot(m,u)));return"<rect ".concat(d,' x="').concat(f,'" y="').concat(g,'" width="').concat(p,'" height="').concat(b,'"></rect>')})(a,{left:t,top:e,width:s,height:i}),`
58
- `)}const cd=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let Gr;class Ot extends Mh{static getDefaults(){return w(w({},super.getDefaults()),Ot.ownDefaults)}constructor(t,e){super(),x(this,"__charBounds",[]),Object.assign(this,Ot.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=Nr(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Te)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===Te||h!==l-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(o=this.textLines[h].match(this._reSpacesAndTabs)))){s=o.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[h][c],this._reSpaceAndTab.test(n[c])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===Ht?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case $:t.textBaseline="middle";break;case"ascender":t.textBaseline=Yt;break;case"descender":t.textBaseline=tr}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const o=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=o;continue}const h=this._textLines[n].length,l=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(n);for(let b=0;b<h;b++){const m=this.__charBounds[n][b];u=this.getValueOfPropertyAt(n,b,"textBackgroundColor"),this.path?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),t.fillStyle=u,u&&t.fillRect(-m.width/2,-p*(1-this._fontSizeFraction),m.width,p),t.restore()):u!==g?(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=g,g&&t.fillRect(c,i,d,p),f=m.left,d=m.width,g=u):d+=m.kernedWidth}u&&!this.path&&(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=u,t.fillRect(c,i,d,p)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=$s.getFontCache(e),r=this._getFontDeclaration(e),o=s+t,h=s&&r===this._getFontDeclaration(i),l=e.fontSize/this.CACHE_FONT_SIZE;let c,u,d,f;if(s&&n.has(s)&&(d=n.get(s)),n.has(t)&&(f=c=n.get(t)),h&&n.has(o)&&(u=n.get(o),f=u-d),c===void 0||d===void 0||u===void 0){const g=(function(){return Gr||(Gr=te({width:0,height:0}).getContext("2d")),Gr})();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n.set(t,c)),d===void 0&&h&&s&&(d=g.measureText(s).width,n.set(s,d)),h&&u===void 0&&(u=g.measureText(o).width,n.set(o,u),f=u-d)}return{width:c*l,kernedWidth:f*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===bt,r=this.path,o=this._textLines[t],h=o.length,l=new Array(h);this.__charBounds[t]=l;for(let c=0;c<h;c++){const u=o[c];s=this._getGraphemeBox(u,t,c,e),l[c]=s,i+=s.kernedWidth,e=u}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case it:c=n?u-i:0;break;case $:c=(u-i)/2;break;case bt:c=n?0:u-i}c+=this.pathStartOffset*(n?-1:1);for(let d=n?h-1:0;n?d>=0:d<h;n?d--:d++)s=l[d],c>u?c%=u:c<0&&(c+=u),this._setGraphemeOnPath(c,s),c+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=mh(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===bt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,o);let l,c=h.kernedWidth,u=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),u+=l,c+=l);const d={width:u,left:0,height:r.fontSize,kernedWidth:c,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];d.left=f.left+f.width+h.kernedWidth-h.width}return d}getHeightOfLineImpl(t){const e=this.__lineHeights;if(e[t])return e[t];let s=this.getHeightOfChar(t,0);for(let i=1,n=this._textLines[t].length;i<n;i++)s=Math.max(this.getHeightOfChar(t,i),s);return e[t]=s*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,s=this._textLines.length;e<s;e++)t+=e===s-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,o=this._textLines.length;r<o;r++)this._renderTextLine(e,t,this._textLines[r],i+this._getLineLeftOffset(r),n+s+this.getHeightOfLineImpl(r),r),s+=this.getHeightOfLine(r);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(wt))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,i,n,r){const o=this.textAlign.includes(Te),h=this.path,l=!o&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,c=this.direction==="ltr",u=this.direction==="ltr"?1:-1,d=e.direction;let f,g,p,b,m,v="",y=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",c?"ltr":"rtl"),e.direction=c?"ltr":"rtl",e.textAlign=c?it:bt),n-=this.getHeightOfLineImpl(r)*this._fontSizeFraction,l)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let _=0,S=s.length-1;_<=S;_++)b=_===S||this.charSpacing||h,v+=s[_],p=this.__charBounds[r][_],y===0?(i+=u*(p.kernedWidth-p.width),y+=p.width):y+=p.kernedWidth,o&&!b&&this._reSpaceAndTab.test(s[_])&&(b=!0),b||(f=f||this.getCompleteStyleDeclaration(r,_),g=this.getCompleteStyleDeclaration(r,_+1),b=qi(f,g,!1)),b&&(h?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,r,_,v,-y/2,0),e.restore()):(m=i,this._renderChar(t,e,r,_,v,m,n)),v="",f=g,i+=u*y,y=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=te({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return re(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,o){const h=this._getStyleDeclaration(s,i),l=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&l.fill,u=t==="strokeText"&&l.stroke&&l.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),c){const d=this._setFillStyles(e,l);e.fillText(n,r-d.offsetX,o-d.offsetY)}if(u){const d=this._setStrokeStyles(e,l);e.strokeText(n,r-d.offsetX,o-d.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const i=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize"),r=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"deltaY"),o={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(o,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let o=0;return i===Te||i===ni&&!r||i===ii&&!r||i===Hi&&!r?0:(i===$&&(o=s/2),i===bt&&(o=s),i===ni&&(o=s/2),i===ii&&(o=s),n==="rtl"&&(i===bt||i===Te||i===ii?o=0:i===it||i===Hi?o=-s:i!==$&&i!==ni||(o=-s/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let l=0,c=this._textLines.length;l<c;l++){const u=this.getHeightOfLine(l);if(!this[e]&&!this.styleHas(e,l)){s+=u;continue}const d=this._textLines[l],f=u/this.lineHeight,g=this._getLineLeftOffset(l);let p=0,b=0,m=this.getValueOfPropertyAt(l,0,e),v=this.getValueOfPropertyAt(l,0,wt),y=this.getValueOfPropertyAt(l,0,hs),_=m,S=v,A=y;const T=s+f*(1-this._fontSizeFraction);let k=this.getHeightOfChar(l,0),P=this.getValueOfPropertyAt(l,0,"deltaY");for(let I=0,O=d.length;I<O;I++){const D=this.__charBounds[l][I];_=this.getValueOfPropertyAt(l,I,e),S=this.getValueOfPropertyAt(l,I,wt),A=this.getValueOfPropertyAt(l,I,hs);const z=this.getHeightOfChar(l,I),M=this.getValueOfPropertyAt(l,I,"deltaY");if(n&&_&&S){const R=this.fontSize*A/1e3;t.save(),t.fillStyle=v,t.translate(D.renderLeft,D.renderTop),t.rotate(D.angle),t.fillRect(-D.kernedWidth/2,h*z+M-o*R,D.kernedWidth,R),t.restore()}else if((_!==m||S!==v||z!==k||A!==y||M!==P)&&b>0){const R=this.fontSize*y/1e3;let U=i+g+p;this.direction==="rtl"&&(U=this.width-U-b),m&&v&&y&&(t.fillStyle=v,t.fillRect(U,T+h*k+P-o*R,b,R)),p=D.left,b=D.width,m=_,y=A,v=S,k=z,P=M}else b+=D.kernedWidth}let B=i+g+p;this.direction==="rtl"&&(B=this.width-B-b),t.fillStyle=S;const F=this.fontSize*A/1e3;_&&S&&A&&t.fillRect(B,T+h*k+P-o*F,b-r,F),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||Ot.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return $i(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
59
- `];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject([..._a,...t])),{},{styles:$a(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let i=!1,n=!1;if(typeof t=="object")for(const r in t)r==="path"&&this.setPathInfo(),i=i||s.includes(r),n=n||r==="path";else i=s.includes(t),n=t==="path";return n&&this.setPathInfo(),i&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const i=Ne(t,Ot.ATTRIBUTE_NAMES,s),n=w(w({},e),i),{textAnchor:r=it,textDecoration:o="",dx:h=0,dy:l=0,top:c=0,left:u=0,fontSize:d=Qn,strokeWidth:f=1}=n,g=lt(n,cd),p=new this(Ni(t.textContent||"").trim(),w({left:u+h,top:c+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:d},g)),b=p.getScaledHeight()/p.height,m=((p.height+p.strokeWidth)*p.lineHeight-p.height)*b,v=p.getScaledHeight()+m;let y=0;return r===$&&(y=p.getScaledWidth()/2),r===bt&&(y=p.getScaledWidth()),p.set({left:p.left-y,top:p.top-(v-p.fontSize*(.07+p._fontSizeFraction))/p.lineHeight,strokeWidth:f}),p}static fromObject(t){return this._fromObject(w(w({},t),{},{styles:qa(t.styles||{},t.text)}),{extraParam:"text"})}}x(Ot,"textLayoutProperties",ya),x(Ot,"cacheProperties",[...Fe,..._a]),x(Ot,"ownDefaults",xc),x(Ot,"type","Text"),x(Ot,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),x(Ot,"ATTRIBUTE_NAMES",Ye.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Ga(Ot,[class extends ma{_toSVG(){const a=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(a.textTop,a.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(a){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:a,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:a,withShadow:!0,additionalTransform:ks(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(a){let{textBgRects:t,textSpans:e}=a;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(ld,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
60
- `]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...zr(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,o=this._textLines.length;r<o;r++)i=this._getLineLeftOffset(r),this.direction==="rtl"&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,t+i,n),this._setSVGTextLineText(e,r,t+i,n),n+=this.getHeightOfLine(r);return{textSpans:e,textBgRects:s}}_createTextCharSpan(a,t,e,s,i){const n=et.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(hd)),o=r?'style="'.concat(r,'"'):"",h=t.deltaY,l=h?' dy="'.concat(ot(h,n),'" '):"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=' rotate="'.concat(ot(Ce(c),n),'"'));const b=ns({angle:Ce(c)});b[4]=u,b[5]=d;const m=new C(-p,0).transform(b);e=m.x,s=m.y}return'<tspan x="'.concat(ot(e,n),'" y="').concat(ot(s,n),'" ').concat(l).concat(g).concat(o,">").concat(Ya(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Te),r=this._textLines[t];let o,h,l,c,u,d="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let g=0,p=r.length-1;g<=p;g++)u=g===p||this.charSpacing||this.path,d+=r[g],l=this.__charBounds[t][g],f===0?(e+=l.kernedWidth-l.width,f+=l.width):f+=l.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[g])&&(u=!0),u||(o=o||this.getCompleteStyleDeclaration(t,g),h=this.getCompleteStyleDeclaration(t,g+1),u=qi(o,h,!0)),u&&(c=this._getStyleDeclaration(t,g),a.push(this._createTextCharSpan(d,c,e,s,l)),d="",o=h,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:u,width:d,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==l?(l&&a.push(...zr(l,e+h,s,o,n)),h=u,o=d,l=r):o+=f}r&&a.push(...zr(l,e+h,s,o,n))}_getSVGLineTopOffset(a){let t,e=0;for(t=0;t<a;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(a){return"".concat(super.getSvgStyles(a)," text-decoration-thickness: ").concat(ot(this.textDecorationThickness*this.getObjectScaling().y/10,et.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:l,textDecorationThickness:c,linethrough:u,overline:d,underline:f}=a,g=this.getSvgTextDecoration({underline:f??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),p=c||this.textDecorationThickness;return[i?si(Ht,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",o?"font-style: ".concat(o,"; "):"",h?"font-weight: ".concat(h,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(ot(p*this.getObjectScaling().y/10,et.NUM_FRACTION_DIGITS),"%; "):"",n?si(wt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter((t=>a[t.replace("-","")])).join(" ")}}]),L.setClass(Ot),L.setSVGClass(Ot);class ud{constructor(t){x(this,"target",void 0),x(this,"__mouseDownInPlace",!1),x(this,"__dragStartFired",!1),x(this,"__isDraggingOver",!1),x(this,"__dragStartSelection",void 0),x(this,"__dragImageDisposer",void 0),x(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach((s=>s())),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new C(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),c=new C(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(r.calcTransformMatrix()),u=o.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new C(f.left,f.top)),p=o.viewportTransform,b=g.add(u).transform(p,!0),m=r.backgroundColor,v=Pr(r.styles);r.backgroundColor="";const y={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(y,0,i),r.setSelectionStyles(y,n,r.text.length),r.dirty=!0;const _=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=v,r.dirty=!0,en(_,{position:"fixed",left:"".concat(-_.width,"px"),border:jt,width:"".concat(_.width/d,"px"),height:"".concat(_.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{_.remove()},ue(t.target||this.target.hiddenTextarea).body.appendChild(_),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(_,b.x,b.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=w({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>d&&h<=f?h=d:h>f&&(h-=f-d),r.removeChars(d,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(Ei,{index:h+u,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||jt;h===jt?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ei,{index:r,action:"dragend"}),n.fire("text:changed",{target:i}),n.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const Ph=/[ \n\.,;!\?\-]/;class dd extends Ot{constructor(){super(...arguments),x(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Er({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:i,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:r=>{this._currentCursorOpacity=r,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach((e=>{e&&!e.isDone()&&(t=!0,e.abort())})),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some((t=>!t||t.isDone()))&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let i=t>0&&this._reSpace.test(s[t])&&(e===-1||!er.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Ph.test(n);)i+=e,n=s[i];return e===-1&&Ph.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;ue(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,o=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,c=l.width/h,u=l.height/h,d=c-r,f=u-r,g=new C(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new C(l.clientWidth/c,l.clientHeight/u));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(Mi),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const c=parseInt(l,10);c>=r&&(o[c-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(h=!0,n[d-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let c=!1;for(h&&!o&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:w({},i[s-1])}:l?this.styles[t+s]={0:w({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?w({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=w({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=w({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
61
- `?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=it:this._selectionDirection===bt&&(this._selectionDirection=it,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===bt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=bt:this._selectionDirection===it&&(this._selectionDirection=bt,this.selectionStart=e),this.selectionEnd=s)}}class fd extends dd{initHiddenTextarea(){const t=this.canvas&&ue(this.canvas.getElement())||xs(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map((r=>{let[o,h]=r;return e.setAttribute(o,h)}));const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map((r=>{let[o,h]=r;return e.addEventListener(o,this[h].bind(this))})),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(Ei),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const o=this._splitTextIntoLines(s).graphemeText,h=this._text.length,l=o.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,b,m=l-h;const v=this.fromStringToGraphemeSelection(i,n,s),y=c>v.selectionStart;d?(g=this._text.slice(c,u),m+=u-c):l<h&&(g=y?this._text.slice(u+m,u):this._text.slice(c,c-m));const _=o.slice(v.selectionEnd-m,v.selectionEnd);if(g&&g.length&&(_.length&&(f=this.getSelectionStyles(c,c+1,!1),f=_.map((()=>f[0]))),d?(p=c,b=u):y?(p=u-g.length,b=u):(p=u,b=u+g.length),this.removeStyleFromTo(p,b)),_.length){const{copyPasteData:S}=xe();e&&_.join("")===S.copiedText&&!et.disableStyleCopyPaste&&(f=S.copiedTextStyle),this.insertNewStyleBlock(_,c,f)}r()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:i}=e;this.compositionStart=s,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=xe();t.copiedText=this.getSelectedText(),et.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const c=r-i,u=r,d=Math.abs(c-e);o=Math.abs(u-e)<d?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===bt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=ls(0,this.selectionStart,i),this.selectionEnd=ls(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===it?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=it,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===bt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=it,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===it&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=bt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=bt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Oh=a=>!!a.button;class gd extends fd{constructor(){super(...arguments),x(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new ud(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!Oh(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const i=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const n=this.canvas._activeObject;if(n&&n!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||Oh(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform($t(this.calcTransformMatrix())).add(new C(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),n=l,l>0&&(i+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let l=0;l<o;l++){const c=r+h[l].kernedWidth;if(e.x<=c){Math.abs(e.x-c)<=Math.abs(e.x-r)&&i++;break}r=c,i++}return Math.min(this.flipX?o-i:i,this._text.length)}}const on="moveCursorUp",an="moveCursorDown",hn="moveCursorLeft",ln="moveCursorRight",cn="exitEditing",Dh=(a,t)=>{const e=t.getRetinaScaling();a.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;a.transform(s[0],s[1],s[2],s[3],s[4],s[5])},pd=w({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:cn,27:cn,33:on,34:an,35:ln,36:hn,37:hn,38:on,39:ln,40:an},keysMapRtl:{9:cn,27:cn,33:on,34:an,35:hn,36:ln,37:ln,38:on,39:hn,40:an},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class ze extends gd{static getDefaults(){return w(w({},super.getDefaults()),ze.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,w(w({},ze.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof jr&&this.canvas.textEditingManager.remove(this),e instanceof jr&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=te(t.canvas),r=n.getContext("2d"),Dh(r,this.canvas);const o=this.calcTransformMatrix();r.transform(o[0],o[1],o[2],o[3],o[4],o[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const o of s){const h=o.clipPath,l=te(t.canvas),c=l.getContext("2d");if(Dh(c,this.canvas),!h.absolutePositioned){const u=o.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(c),h.drawObject(c,!0,{}),this.drawClipPathOnCache(r,h,l)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let l=0;l<n;l++)e+=this.getHeightOfLine(l);const r=this._getLineLeftOffset(n),o=this.__charBounds[n][i];o&&(s=o.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===bt||this.textAlign===Te||this.textAlign===ii?h.left*=-1:this.textAlign===it||this.textAlign===Hi?h.left=r-(s>0?s:0):this.textAlign!==$&&this.textAlign!==ni||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),c=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:c+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Te),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),l=o.lineIndex,c=h.lineIndex,u=o.charIndex<0?0:o.charIndex,d=h.charIndex<0?0:h.charIndex;for(let f=l;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),b=0,m=0,v=0;if(f===l&&(m=this.__charBounds[l][u].left),f>=l&&f<c)v=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(d===0)v=this.__charBounds[c][d].left;else{const T=this._getWidthOfCharSpacing();v=this.__charBounds[c][d-1].left+this.__charBounds[c][d-1].width-T}b=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let y=s.left+g+m,_=p,S=0;const A=v-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",_=1,S=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===bt||this.textAlign===Te||this.textAlign===ii?y=this.width-y-A:this.textAlign===it||this.textAlign===Hi?y=s.left+g-v:this.textAlign!==$&&this.textAlign!==ni||(y=s.left+g-v)),t.fillRect(y,s.top+s.topOffset+S,A,_),s.topOffset+=b}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,wt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}x(ze,"ownDefaults",pd),x(ze,"type","IText"),L.setClass(ze),L.setClass(ze,"i-text");class fs extends ze{static getDefaults(){return w(w({},super.getDefaults()),fs.ownDefaults)}constructor(t,e){super(t,w(w({},fs.ownDefaults),e))}static createControls(){return{controls:eu()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(Te)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
62
- `&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,s=r.offset),o&&(i=o.line,n=i===t,e=o.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const c in h[l]){const u=parseInt(c,10);if(u>=s&&(!n||u<e))for(const d in h[l][c])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const i=this._styleMap[t];super._setStyleDeclaration(i.line,i.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),i=[];for(let n=0;n<s.wordsData.length;n++)i.push(...this._wrapLine(n,e,s));return this.isWrapping=!1,i}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let i=0;return{wordsData:t.map(((n,r)=>{let o=0;const h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map((l=>{const c=e?[l]:this.graphemeSplit(l),u=this._measureWord(c,r,o);return i=Math.max(u,i),o+=c.length+s.length,{word:c,width:u}}))})),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,o=t.length;r<o;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const o=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,l=[],c=h?"":" ";let u=0,d=[],f=0,g=0,p=!0;e-=r;const b=Math.max(e,i,this.dynamicMinWidth),m=n[t];let v;for(f=0,v=0;v<m.length;v++){const{word:y,width:_}=m[v];f+=y.length,u+=g+_-o,u>b&&!p?(l.push(d),d=[],u=_,p=!0):u+=o,p||h||d.push(c),d=d.concat(y),g=h?0:this._measureWord([c],t,f),f++,p=!1}return v&&l.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}x(fs,"type","Textbox"),x(fs,"textLayoutProperties",[...ze.textLayoutProperties,"width"]),x(fs,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),L.setClass(fs);class Rh extends Qi{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:i,group:n}=s;if(!i||!this.shouldPerformLayout(t))return;const{width:r,height:o}=Ae(rh(s,i)),h=new C(r,o);if(i.absolutePositioned)return{center:as(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const l=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new C,correction:u=new C}=this.calcBoundingBox(e,t)||{};return{center:c.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}x(Rh,"type","clip-path"),L.setClass(Rh);class Lh extends Qi{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new C(s.width||i.x,s.height||i.y)}}x(Lh,"type","fixed"),L.setClass(Lh);class md extends hi{subscribeTargets(t){const e=t.target;t.targets.reduce(((s,i)=>(i.parent&&s.add(i.parent),s)),new Set).forEach((s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})}))}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce(((i,n)=>(n.parent&&i.add(n.parent),i)),new Set).forEach((i=>{!s.some((n=>n.parent===i))&&i.layoutManager.unsubscribeTargets({target:i,targets:[e]})}))}}class gs extends ee{static getDefaults(){return w(w({},super.getDefaults()),gs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,gs.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new md})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach((i=>{const n=this._objects.findIndex((o=>o.isInFrontOf(i))),r=n===-1?this.size():n;this.insertAt(r,i)}))}canEnterGroup(t){return this.getObjects().some((e=>e.isDescendantOf(t)||t.isDescendantOf(e)))?(De("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach((i=>{const{parent:n}=i;n&&s.add(n)})),t===Rr?s.forEach((i=>{i._onAfterObjectsChange(Ji,e)})):s.forEach((i=>{i._set("dirty",!0)}))}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=w(w({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}x(gs,"type","ActiveSelection"),x(gs,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),L.setClass(gs),L.setClass(gs,"activeSelection");class bd{constructor(){x(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach((l=>{l.applyTo(o)}));const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Fh{constructor(){let{tileSize:t=et.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};x(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),x(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=te({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const o=this.gl,h=n.getContext("2d");if(!o||!h)return;let l;r&&(l=this.getCachedTexture(r,e));const c={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:o,sourceTexture:this.createTexture(o,s,i,l?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:l||this.createTexture(o,s,i,l?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach((d=>{d&&d.applyTo(c)})),(function(d){const f=d.targetCanvas,g=f.width,p=f.height,b=d.destinationWidth,m=d.destinationHeight;g===b&&p===m||(f.width=b,f.height=m)})(c),this.copyGLTo2D(o,c),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(c.sourceTexture),o.deleteTexture(c.targetTexture),o.deleteFramebuffer(u),h.setTransform(1,0,0,1,0,0),c}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,i,n){const{NEAREST:r,TEXTURE_2D:o,RGBA:h,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:g}=t,p=t.createTexture();return t.bindTexture(o,p),t.texParameteri(o,u,n||r),t.texParameteri(o,d,n||r),t.texParameteri(o,f,c),t.texParameteri(o,g,c),i?t.texImage2D(o,0,h,h,l,i):t.texImage2D(o,0,h,e,s,0,h,l,null),p}getCachedTexture(t,e,s){const{textureCache:i}=this;if(i[t])return i[t];{const n=this.createTexture(this.gl,e.width,e.height,e,s);return n&&(i[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,i=e.targetCanvas,n=i.getContext("2d");if(!n)return;n.translate(0,i.height),n.scale(1,-1);const r=s.height-i.height;n.drawImage(s,0,r,i.width,i.height,0,0,i.width,i.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),i=e.destinationWidth,n=e.destinationHeight,r=i*n*4;if(!s)return;const o=new Uint8Array(this.imageBuffer,0,r),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);const l=new ImageData(h,i,n);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let Vr;function vd(){const{WebGLProbe:a}=xe();return a.queryWebGL(Se()),et.enableGLFiltering&&a.isSupported(et.textureSize)?new Fh({tileSize:et.textureSize}):new bd}function Wr(){return!Vr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(Vr=vd()),Vr}const yd=["filters","resizeFilter","src","crossOrigin","type"],Ih=["cropX","cropY"];class Dt extends Pt{static getDefaults(){return w(w({},super.getDefaults()),Dt.ownDefaults)}constructor(t,e){super(),x(this,"_lastScaleX",1),x(this,"_lastScaleY",1),x(this,"_filterScalingX",1),x(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Dt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Ue()),this.setElement(typeof t=="string"?(this.canvas&&ue(this.canvas.getElement())||xs()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Dt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=Wr(!1);e instanceof Fh&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach((t=>{const e=this[t];e&&xe().dispose(e),this[t]=void 0}))}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach((s=>{s&&e.push(s.toObject())})),w(w({},super.toObject([...Ih,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],o="",h="";if(!e)return[];if(this.hasCrop()){const l=Ue();n.push('<clipPath id="imageCrop_'+l+`">
54
+ `]}}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:o=0}=i;return new this(w(w({},ct(i,id)),{},{radius:o,left:n-o,top:r-o}))}static fromObject(t){return super._fromObject(t)}}x(Be,"type","Circle"),x(Be,"cacheProperties",[...Fe,...Th]),x(Be,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),x(Be,"ATTRIBUTE_NAMES",["cx","cy","r",...Ye]),L.setClass(Be),L.setSVGClass(Be);const nd=["x1","y1","x2","y2"],rd=["x1","y1","x2","y2"],Hr=["x1","x2","y1","y2"];class us extends Dt{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,us.ownDefaults),this.setOptions(n),this.x1=t,this.x2=s,this.y1=e,this.y2=i,this._setWidthHeight();const{left:r,top:o}=n;typeof r=="number"&&this.set(it,r),typeof o=="number"&&this.set($t,o)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:i}=this;this.width=Math.abs(s-t),this.height=Math.abs(i-e);const{left:n,top:r,width:o,height:h}=Ae([{x:t,y:e},{x:s,y:i}]),l=new C(n+o/2,r+h/2);this.setPositionByOrigin(l,$,$)}_set(t,e){return super._set(t,e),Hr.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var i;re(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(i=this.stroke)!==null&&i!==void 0?i:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new C((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,o=t<=e?-1:1,h=s<=i?-1:1;return{x1:o*n/2,x2:o*-n/2,y1:h*r/2,y2:h*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
55
+ `)]}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:o=0,y2:h=0}=i;return new this([n,r,o,h],ct(i,nd))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=ct(t,rd);return this._fromObject(w(w({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}x(us,"type","Line"),x(us,"cacheProperties",[...Fe,...Hr]),x(us,"ATTRIBUTE_NAMES",Ye.concat(Hr)),L.setClass(us),L.setSVGClass(us);class ds extends Dt{static getDefaults(){return w(w({},super.getDefaults()),ds.ownDefaults)}constructor(t){super(),Object.assign(this,ds.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}x(ds,"type","Triangle"),x(ds,"ownDefaults",{width:100,height:100}),L.setClass(ds),L.setSVGClass(ds);const Eh=["rx","ry"];class He extends Dt{static getDefaults(){return w(w({},super.getDefaults()),He.ownDefaults)}constructor(t){super(),Object.assign(this,He.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get(Ht)}getRy(){return this.get("ry")*this.get(Qt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Eh,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
56
+ `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Re,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Ne(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function od(a){if(!a)return[];const t=a.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}x(He,"type","Ellipse"),x(He,"cacheProperties",[...Fe,...Eh]),x(He,"ownDefaults",{rx:0,ry:0}),x(He,"ATTRIBUTE_NAMES",[...Ye,"cx","cy","rx","ry"]),L.setClass(He),L.setSVGClass(He);const ad=["left","top"],kh={exactBoundingBox:!1};class me extends Dt{static getDefaults(){return w(w({},super.getDefaults()),me.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),x(this,"strokeDiff",void 0),Object.assign(this,me.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(it,s),typeof i=="number"&&this.set($t,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return Ua(this.points,t,this.isOpen())}_calcDimensions(t){t=w({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map((l=>l.projectedPoint)):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new C,strokeOffset:new C,strokeDiff:new C};const s=Ae(e),i=Js(w(w({},t),{},{scaleX:1,scaleY:1})),n=Ae(this.points.map((l=>Ot(l,i,!0)))),r=new C(this.scaleX,this.scaleY);let o=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(o-=h*Math.tan(pt(this.skewX)),h-=o*Math.tan(pt(this.skewY))),w(w({},s),{},{pathOffset:new C(o,h),strokeOffset:new C(n.left,n.top).subtract(new C(s.left,s.top)).multiply(r),strokeDiff:new C(s.width,s.height).subtract(new C(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Ae(this.points);return new C(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:o,strokeDiff:h}),t&&this.setPositionByOrigin(new C(e+i/2,s+n/2),$,$)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new C(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some((o=>this.strokeUniform||this.constructor.layoutProperties.includes(o)))){var e,s;const{width:o,height:h}=this._calcDimensions(t);r=new C((e=t.width)!==null&&e!==void 0?e:o,(s=t.height)!==null&&s!==void 0?s:h)}else{var i,n;r=new C((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new C(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,i=super._set(t,e);return this.exactBoundingBox&&s&&((t===Ht||t===Qt)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject(t)),{},{points:this.points.map((e=>{let{x:s,y:i}=e;return{x:s,y:i}}))})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=et.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(ot(this.points[n].x-e,i),",",ot(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
57
+ `)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(od(t.getAttribute("points")),w(w({},ct(Ne(t,this.ATTRIBUTE_NAMES,s),ad)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}x(me,"ownDefaults",kh),x(me,"type","Polyline"),x(me,"layoutProperties",[Ss,Cs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),x(me,"cacheProperties",[...Fe,"points"]),x(me,"ATTRIBUTE_NAMES",[...Ye]),L.setClass(me),L.setSVGClass(me);class rn extends me{isOpen(){return!1}}x(rn,"ownDefaults",kh),x(rn,"type","Polygon"),L.setClass(rn),L.setSVGClass(rn);class Mh extends Dt{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,o=0;for(const h in e){s=0;for(const l in e[h]){const c=e[h][l]||{};n++,c[t]!==void 0?(i?c[t]!==i&&(r=!1):i=c[t],c[t]===this[t]&&delete c[t]):r=!1,Object.keys(c).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)o+=this._textLines[h].length;r&&n===o&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=lr(w(w({},this._getStyleDeclaration(s,i)),e),(r=>r!==void 0));this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return w(w({},rs(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}x(Mh,"_styleProperties",wc);const hd=/ +/g,ld=/"/g;function zr(a,t,e,s,i){return" ".concat((function(n,r){let{left:o,top:h,width:l,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:et.NUM_FRACTION_DIGITS;const d=si(wt,n,!1),[f,g,p,b]=[o,h,l,c].map((m=>ot(m,u)));return"<rect ".concat(d,' x="').concat(f,'" y="').concat(g,'" width="').concat(p,'" height="').concat(b,'"></rect>')})(a,{left:t,top:e,width:s,height:i}),`
58
+ `)}const cd=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let Gr;class Rt extends Mh{static getDefaults(){return w(w({},super.getDefaults()),Rt.ownDefaults)}constructor(t,e){super(),x(this,"__charBounds",[]),Object.assign(this,Rt.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=Nr(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Te)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,o;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===Te||h!==l-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(o=this.textLines[h].match(this._reSpacesAndTabs)))){s=o.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[h][c],this._reSpaceAndTab.test(n[c])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===zt?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case $:t.textBaseline="middle";break;case"ascender":t.textBaseline=$t;break;case"descender":t.textBaseline=tr}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const o=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=o;continue}const h=this._textLines[n].length,l=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(n);for(let b=0;b<h;b++){const m=this.__charBounds[n][b];u=this.getValueOfPropertyAt(n,b,"textBackgroundColor"),this.path?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),t.fillStyle=u,u&&t.fillRect(-m.width/2,-p*(1-this._fontSizeFraction),m.width,p),t.restore()):u!==g?(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=g,g&&t.fillRect(c,i,d,p),f=m.left,d=m.width,g=u):d+=m.kernedWidth}u&&!this.path&&(c=s+l+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=u,t.fillRect(c,i,d,p)),i+=o}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=$s.getFontCache(e),r=this._getFontDeclaration(e),o=s+t,h=s&&r===this._getFontDeclaration(i),l=e.fontSize/this.CACHE_FONT_SIZE;let c,u,d,f;if(s&&n.has(s)&&(d=n.get(s)),n.has(t)&&(f=c=n.get(t)),h&&n.has(o)&&(u=n.get(o),f=u-d),c===void 0||d===void 0||u===void 0){const g=(function(){return Gr||(Gr=te({width:0,height:0}).getContext("2d")),Gr})();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n.set(t,c)),d===void 0&&h&&s&&(d=g.measureText(s).width,n.set(s,d)),h&&u===void 0&&(u=g.measureText(o).width,n.set(o,u),f=u-d)}return{width:c*l,kernedWidth:f*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===bt,r=this.path,o=this._textLines[t],h=o.length,l=new Array(h);this.__charBounds[t]=l;for(let c=0;c<h;c++){const u=o[c];s=this._getGraphemeBox(u,t,c,e),l[c]=s,i+=s.kernedWidth,e=u}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case it:c=n?u-i:0;break;case $:c=(u-i)/2;break;case bt:c=n?0:u-i}c+=this.pathStartOffset*(n?-1:1);for(let d=n?h-1:0;n?d>=0:d<h;n?d--:d++)s=l[d],c>u?c%=u:c<0&&(c+=u),this._setGraphemeOnPath(c,s),c+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=mh(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===bt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),o=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,o);let l,c=h.kernedWidth,u=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),u+=l,c+=l);const d={width:u,left:0,height:r.fontSize,kernedWidth:c,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];d.left=f.left+f.width+h.kernedWidth-h.width}return d}getHeightOfLineImpl(t){const e=this.__lineHeights;if(e[t])return e[t];let s=this.getHeightOfChar(t,0);for(let i=1,n=this._textLines[t].length;i<n;i++)s=Math.max(this.getHeightOfChar(t,i),s);return e[t]=s*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,s=this._textLines.length;e<s;e++)t+=e===s-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,o=this._textLines.length;r<o;r++)this._renderTextLine(e,t,this._textLines[r],i+this._getLineLeftOffset(r),n+s+this.getHeightOfLineImpl(r),r),s+=this.getHeightOfLine(r);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(wt))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,i,n,r){const o=this.textAlign.includes(Te),h=this.path,l=!o&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,c=this.direction==="ltr",u=this.direction==="ltr"?1:-1,d=e.direction;let f,g,p,b,m,v="",y=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",c?"ltr":"rtl"),e.direction=c?"ltr":"rtl",e.textAlign=c?it:bt),n-=this.getHeightOfLineImpl(r)*this._fontSizeFraction,l)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let _=0,S=s.length-1;_<=S;_++)b=_===S||this.charSpacing||h,v+=s[_],p=this.__charBounds[r][_],y===0?(i+=u*(p.kernedWidth-p.width),y+=p.width):y+=p.kernedWidth,o&&!b&&this._reSpaceAndTab.test(s[_])&&(b=!0),b||(f=f||this.getCompleteStyleDeclaration(r,_),g=this.getCompleteStyleDeclaration(r,_+1),b=qi(f,g,!1)),b&&(h?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,r,_,v,-y/2,0),e.restore()):(m=i,this._renderChar(t,e,r,_,v,m,n)),v="",f=g,i+=u*y,y=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=te({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return re(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,o){const h=this._getStyleDeclaration(s,i),l=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&l.fill,u=t==="strokeText"&&l.stroke&&l.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(o+=h.deltaY),c){const d=this._setFillStyles(e,l);e.fillText(n,r-d.offsetX,o-d.offsetY)}if(u){const d=this._setStrokeStyles(e,l);e.strokeText(n,r-d.offsetX,o-d.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const i=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize"),r=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"deltaY"),o={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(o,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let o=0;return i===Te||i===ni&&!r||i===ii&&!r||i===Hi&&!r?0:(i===$&&(o=s/2),i===bt&&(o=s),i===ni&&(o=s/2),i===ii&&(o=s),n==="rtl"&&(i===bt||i===Te||i===ii?o=0:i===it||i===Hi?o=-s:i!==$&&i!==ni||(o=-s/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let l=0,c=this._textLines.length;l<c;l++){const u=this.getHeightOfLine(l);if(!this[e]&&!this.styleHas(e,l)){s+=u;continue}const d=this._textLines[l],f=u/this.lineHeight,g=this._getLineLeftOffset(l);let p=0,b=0,m=this.getValueOfPropertyAt(l,0,e),v=this.getValueOfPropertyAt(l,0,wt),y=this.getValueOfPropertyAt(l,0,hs),_=m,S=v,A=y;const T=s+f*(1-this._fontSizeFraction);let k=this.getHeightOfChar(l,0),P=this.getValueOfPropertyAt(l,0,"deltaY");for(let I=0,O=d.length;I<O;I++){const D=this.__charBounds[l][I];_=this.getValueOfPropertyAt(l,I,e),S=this.getValueOfPropertyAt(l,I,wt),A=this.getValueOfPropertyAt(l,I,hs);const z=this.getHeightOfChar(l,I),M=this.getValueOfPropertyAt(l,I,"deltaY");if(n&&_&&S){const R=this.fontSize*A/1e3;t.save(),t.fillStyle=v,t.translate(D.renderLeft,D.renderTop),t.rotate(D.angle),t.fillRect(-D.kernedWidth/2,h*z+M-o*R,D.kernedWidth,R),t.restore()}else if((_!==m||S!==v||z!==k||A!==y||M!==P)&&b>0){const R=this.fontSize*y/1e3;let U=i+g+p;this.direction==="rtl"&&(U=this.width-U-b),m&&v&&y&&(t.fillStyle=v,t.fillRect(U,T+h*k+P-o*R,b,R)),p=D.left,b=D.width,m=_,y=A,v=S,k=z,P=M}else b+=D.kernedWidth}let B=i+g+p;this.direction==="rtl"&&(B=this.width-B-b),t.fillStyle=S;const F=this.fontSize*A/1e3;_&&S&&A&&t.fillRect(B,T+h*k+P-o*F,b-r,F),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||Rt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return $i(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
59
+ `];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return w(w({},super.toObject([..._a,...t])),{},{styles:$a(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let i=!1,n=!1;if(typeof t=="object")for(const r in t)r==="path"&&this.setPathInfo(),i=i||s.includes(r),n=n||r==="path";else i=s.includes(t),n=t==="path";return n&&this.setPathInfo(),i&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const i=Ne(t,Rt.ATTRIBUTE_NAMES,s),n=w(w({},e),i),{textAnchor:r=it,textDecoration:o="",dx:h=0,dy:l=0,top:c=0,left:u=0,fontSize:d=Qn,strokeWidth:f=1}=n,g=ct(n,cd),p=new this(Ni(t.textContent||"").trim(),w({left:u+h,top:c+l,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:d},g)),b=p.getScaledHeight()/p.height,m=((p.height+p.strokeWidth)*p.lineHeight-p.height)*b,v=p.getScaledHeight()+m;let y=0;return r===$&&(y=p.getScaledWidth()/2),r===bt&&(y=p.getScaledWidth()),p.set({left:p.left-y,top:p.top-(v-p.fontSize*(.07+p._fontSizeFraction))/p.lineHeight,strokeWidth:f}),p}static fromObject(t){return this._fromObject(w(w({},t),{},{styles:qa(t.styles||{},t.text)}),{extraParam:"text"})}}x(Rt,"textLayoutProperties",ya),x(Rt,"cacheProperties",[...Fe,..._a]),x(Rt,"ownDefaults",xc),x(Rt,"type","Text"),x(Rt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),x(Rt,"ATTRIBUTE_NAMES",Ye.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Ga(Rt,[class extends ma{_toSVG(){const a=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(a.textTop,a.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(a){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:a,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:a,withShadow:!0,additionalTransform:ks(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(a){let{textBgRects:t,textSpans:e}=a;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(ld,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
60
+ `]}_getSVGTextAndBg(a,t){const e=[],s=[];let i,n=a;this.backgroundColor&&s.push(...zr(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,o=this._textLines.length;r<o;r++)i=this._getLineLeftOffset(r),this.direction==="rtl"&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,t+i,n),this._setSVGTextLineText(e,r,t+i,n),n+=this.getHeightOfLine(r);return{textSpans:e,textBgRects:s}}_createTextCharSpan(a,t,e,s,i){const n=et.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,a!==a.trim()||!!a.match(hd)),o=r?'style="'.concat(r,'"'):"",h=t.deltaY,l=h?' dy="'.concat(ot(h,n),'" '):"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=' rotate="'.concat(ot(Ce(c),n),'"'));const b=ns({angle:Ce(c)});b[4]=u,b[5]=d;const m=new C(-p,0).transform(b);e=m.x,s=m.y}return'<tspan x="'.concat(ot(e,n),'" y="').concat(ot(s,n),'" ').concat(l).concat(g).concat(o,">").concat(Ya(a),"</tspan>")}_setSVGTextLineText(a,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Te),r=this._textLines[t];let o,h,l,c,u,d="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let g=0,p=r.length-1;g<=p;g++)u=g===p||this.charSpacing||this.path,d+=r[g],l=this.__charBounds[t][g],f===0?(e+=l.kernedWidth-l.width,f+=l.width):f+=l.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[g])&&(u=!0),u||(o=o||this.getCompleteStyleDeclaration(t,g),h=this.getCompleteStyleDeclaration(t,g+1),u=qi(o,h,!0)),u&&(c=this._getStyleDeclaration(t,g),a.push(this._createTextCharSpan(d,c,e,s,l)),d="",o=h,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(a,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,o=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:u,width:d,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==l?(l&&a.push(...zr(l,e+h,s,o,n)),h=u,o=d,l=r):o+=f}r&&a.push(...zr(l,e+h,s,o,n))}_getSVGLineTopOffset(a){let t,e=0;for(t=0;t<a;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(a){return"".concat(super.getSvgStyles(a)," text-decoration-thickness: ").concat(ot(this.textDecorationThickness*this.getObjectScaling().y/10,et.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(a,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:o,fontWeight:h,deltaY:l,textDecorationThickness:c,linethrough:u,overline:d,underline:f}=a,g=this.getSvgTextDecoration({underline:f??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),p=c||this.textDecorationThickness;return[i?si(zt,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",o?"font-style: ".concat(o,"; "):"",h?"font-weight: ".concat(h,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(ot(p*this.getObjectScaling().y/10,et.NUM_FRACTION_DIGITS),"%; "):"",n?si(wt,n):"",l?"baseline-shift: ".concat(-l,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(a){return["overline","underline","line-through"].filter((t=>a[t.replace("-","")])).join(" ")}}]),L.setClass(Rt),L.setSVGClass(Rt);class ud{constructor(t){x(this,"target",void 0),x(this,"__mouseDownInPlace",!1),x(this,"__dragStartFired",!1),x(this,"__isDraggingOver",!1),x(this,"__dragStartSelection",void 0),x(this,"__dragImageDisposer",void 0),x(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach((s=>s())),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,o=r.canvas,h=new C(r.flipX?-1:1,r.flipY?-1:1),l=r._getCursorBoundaries(i),c=new C(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(r.calcTransformMatrix()),u=o.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new C(f.left,f.top)),p=o.viewportTransform,b=g.add(u).transform(p,!0),m=r.backgroundColor,v=Pr(r.styles);r.backgroundColor="";const y={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(y,0,i),r.setSelectionStyles(y,n,r.text.length),r.dirty=!0;const _=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=v,r.dirty=!0,en(_,{position:"fixed",left:"".concat(-_.width,"px"),border:Bt,width:"".concat(_.width/d,"px"),height:"".concat(_.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{_.remove()},ue(t.target||this.target.hiddenTextarea).body.appendChild(_),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(_,b.x,b.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=w({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,o=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;h>d&&h<=f?h=d:h>f&&(h-=f-d),r.removeChars(d,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,l,h),o.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(Ei,{index:h+u,action:"drop"}),o.fire("text:changed",{target:r}),o.contextTopDirty=!0,o.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:o}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Bt;h===Bt?(i.selectionStart=r,i.selectionEnd=o,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,o),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ei,{index:r,action:"dragend"}),n.fire("text:changed",{target:i}),n.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const Ph=/[ \n\.,;!\?\-]/;class dd extends Rt{constructor(){super(...arguments),x(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return Er({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:i,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:r=>{this._currentCursorOpacity=r,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach((e=>{e&&!e.isDone()&&(t=!0,e.abort())})),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some((t=>!t||t.isDone()))&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let i=t>0&&this._reSpace.test(s[t])&&(e===-1||!er.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!Ph.test(n);)i+=e,n=s[i];return e===-1&&Ph.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;ue(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,o=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,c=l.width/h,u=l.height/h,d=c-r,f=u-r,g=new C(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new C(l.clientWidth/c,l.clientHeight/u));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(Mi),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let o=i;o<this._unwrappedTextLines[s].length;o++)delete this.styles[s][o];if(this.styles[n])for(let o=r;o<this._unwrappedTextLines[n].length;o++){const h=this.styles[n][o];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+o-r]=h)}for(let o=s+1;o<=n;o++)delete this.styles[o];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const o=this.styles[s],h=r-i;for(let l=i;l<r;l++)delete o[l];for(const l in this.styles[s]){const c=parseInt(l,10);c>=r&&(o[c-h]=o[l],delete o[l])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(h=!0,n[d-e]=this.styles[t][u],o&&e===0||delete this.styles[t][u])}let c=!1;for(h&&!o&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:w({},i[s-1])}:l?this.styles[t+s]={0:w({},l)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?w({},n):{};s||(s=1);for(const h in r){const l=parseInt(h,10);l>=e&&(n[l+s]=r[l],r[l-s]||delete n[l])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=w({},i[s]));return}if(!n)return;const o=n[e?e-1:1];for(;o&&s--;)this.styles[t][e+s]=w({},o)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,o=0;for(let h=0;h<t.length;h++)t[h]===`
61
+ `?(o++,n[o]=0):n[o]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),o&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],o),r=1;r<o;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=it:this._selectionDirection===bt&&(this._selectionDirection=it,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===bt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=bt:this._selectionDirection===it&&(this._selectionDirection=bt,this.selectionStart=e),this.selectionEnd=s)}}class fd extends dd{initHiddenTextarea(){const t=this.canvas&&ue(this.canvas.getElement())||xs(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map((r=>{let[o,h]=r;return e.setAttribute(o,h)}));const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map((r=>{let[o,h]=r;return e.addEventListener(o,this[h].bind(this))})),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(Ei),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const o=this._splitTextIntoLines(s).graphemeText,h=this._text.length,l=o.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,b,m=l-h;const v=this.fromStringToGraphemeSelection(i,n,s),y=c>v.selectionStart;d?(g=this._text.slice(c,u),m+=u-c):l<h&&(g=y?this._text.slice(u+m,u):this._text.slice(c,c-m));const _=o.slice(v.selectionEnd-m,v.selectionEnd);if(g&&g.length&&(_.length&&(f=this.getSelectionStyles(c,c+1,!1),f=_.map((()=>f[0]))),d?(p=c,b=u):y?(p=u-g.length,b=u):(p=u,b=u+g.length),this.removeStyleFromTo(p,b)),_.length){const{copyPasteData:S}=xe();e&&_.join("")===S.copiedText&&!et.disableStyleCopyPaste&&(f=S.copiedTextStyle),this.insertNewStyleBlock(_,c,f)}r()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:i}=e;this.compositionStart=s,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=xe();t.copiedText=this.getSelectedText(),et.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,o=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,o),l=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-l.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),o=0;for(let h=0,l=s.length;h<l;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const c=r-i,u=r,d=Math.abs(c-e);o=Math.abs(u-e)<d?h:h-1;break}return n||(o=s.length-1),o}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===bt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=ls(0,this.selectionStart,i),this.selectionEnd=ls(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===it?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=it,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===bt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=it,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===it&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=bt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=bt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Oh=a=>!!a.button;class gd extends fd{constructor(){super(...arguments),x(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new ud(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!Oh(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const i=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const n=this.canvas._activeObject;if(n&&n!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||Oh(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(qt(this.calcTransformMatrix())).add(new C(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),n=l,l>0&&(i+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let r=Math.abs(this._getLineLeftOffset(n));const o=this._textLines[n].length,h=this.__charBounds[n];for(let l=0;l<o;l++){const c=r+h[l].kernedWidth;if(e.x<=c){Math.abs(e.x-c)<=Math.abs(e.x-r)&&i++;break}r=c,i++}return Math.min(this.flipX?o-i:i,this._text.length)}}const on="moveCursorUp",an="moveCursorDown",hn="moveCursorLeft",ln="moveCursorRight",cn="exitEditing",Dh=(a,t)=>{const e=t.getRetinaScaling();a.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;a.transform(s[0],s[1],s[2],s[3],s[4],s[5])},pd=w({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:cn,27:cn,33:on,34:an,35:ln,36:hn,37:hn,38:on,39:ln,40:an},keysMapRtl:{9:cn,27:cn,33:on,34:an,35:hn,36:ln,37:ln,38:on,39:hn,40:an},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class ze extends gd{static getDefaults(){return w(w({},super.getDefaults()),ze.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,w(w({},ze.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof jr&&this.canvas.textEditingManager.remove(this),e instanceof jr&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=te(t.canvas),r=n.getContext("2d"),Dh(r,this.canvas);const o=this.calcTransformMatrix();r.transform(o[0],o[1],o[2],o[3],o[4],o[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const o of s){const h=o.clipPath,l=te(t.canvas),c=l.getContext("2d");if(Dh(c,this.canvas),!h.absolutePositioned){const u=o.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(c),h.drawObject(c,!0,{}),this.drawClipPathOnCache(r,h,l)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let l=0;l<n;l++)e+=this.getHeightOfLine(l);const r=this._getLineLeftOffset(n),o=this.__charBounds[n][i];o&&(s=o.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===bt||this.textAlign===Te||this.textAlign===ii?h.left*=-1:this.textAlign===it||this.textAlign===Hi?h.left=r-(s>0?s:0):this.textAlign!==$&&this.textAlign!==ni||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/o,l=this.getValueOfPropertyAt(i,n,"deltaY"),c=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:c+e.top+l,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:o,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,o,h,l)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Te),o=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),l=o.lineIndex,c=h.lineIndex,u=o.charIndex<0?0:o.charIndex,d=h.charIndex<0?0:h.charIndex;for(let f=l;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),b=0,m=0,v=0;if(f===l&&(m=this.__charBounds[l][u].left),f>=l&&f<c)v=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(d===0)v=this.__charBounds[c][d].left;else{const T=this._getWidthOfCharSpacing();v=this.__charBounds[c][d-1].left+this.__charBounds[c][d-1].width-T}b=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let y=s.left+g+m,_=p,S=0;const A=v-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",_=1,S=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===bt||this.textAlign===Te||this.textAlign===ii?y=this.width-y-A:this.textAlign===it||this.textAlign===Hi?y=s.left+g-v:this.textAlign!==$&&this.textAlign!==ni||(y=s.left+g-v)),t.fillRect(y,s.top+s.topOffset+S,A,_),s.topOffset+=b}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,wt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}x(ze,"ownDefaults",pd),x(ze,"type","IText"),L.setClass(ze),L.setClass(ze,"i-text");class fs extends ze{static getDefaults(){return w(w({},super.getDefaults()),fs.ownDefaults)}constructor(t,e){super(t,w(w({},fs.ownDefaults),e))}static createControls(){return{controls:eu()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(Te)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
62
+ `&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,s=r.offset),o&&(i=o.line,n=i===t,e=o.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const c in h[l]){const u=parseInt(c,10);if(u>=s&&(!n||u<e))for(const d in h[l][c])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const i=this._styleMap[t];super._setStyleDeclaration(i.line,i.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),i=[];for(let n=0;n<s.wordsData.length;n++)i.push(...this._wrapLine(n,e,s));return this.isWrapping=!1,i}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let i=0;return{wordsData:t.map(((n,r)=>{let o=0;const h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map((l=>{const c=e?[l]:this.graphemeSplit(l),u=this._measureWord(c,r,o);return i=Math.max(u,i),o+=c.length+s.length,{word:c,width:u}}))})),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,o=t.length;r<o;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const o=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,l=[],c=h?"":" ";let u=0,d=[],f=0,g=0,p=!0;e-=r;const b=Math.max(e,i,this.dynamicMinWidth),m=n[t];let v;for(f=0,v=0;v<m.length;v++){const{word:y,width:_}=m[v];f+=y.length,u+=g+_-o,u>b&&!p?(l.push(d),d=[],u=_,p=!0):u+=o,p||h||d.push(c),d=d.concat(y),g=h?0:this._measureWord([c],t,f),f++,p=!1}return v&&l.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-o+r),l}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}x(fs,"type","Textbox"),x(fs,"textLayoutProperties",[...ze.textLayoutProperties,"width"]),x(fs,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),L.setClass(fs);class Rh extends Qi{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:i,group:n}=s;if(!i||!this.shouldPerformLayout(t))return;const{width:r,height:o}=Ae(rh(s,i)),h=new C(r,o);if(i.absolutePositioned)return{center:as(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const l=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new C,correction:u=new C}=this.calcBoundingBox(e,t)||{};return{center:c.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}x(Rh,"type","clip-path"),L.setClass(Rh);class Lh extends Qi{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new C(s.width||i.x,s.height||i.y)}}x(Lh,"type","fixed"),L.setClass(Lh);class md extends hi{subscribeTargets(t){const e=t.target;t.targets.reduce(((s,i)=>(i.parent&&s.add(i.parent),s)),new Set).forEach((s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})}))}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce(((i,n)=>(n.parent&&i.add(n.parent),i)),new Set).forEach((i=>{!s.some((n=>n.parent===i))&&i.layoutManager.unsubscribeTargets({target:i,targets:[e]})}))}}class gs extends ee{static getDefaults(){return w(w({},super.getDefaults()),gs.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,gs.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new md})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach((i=>{const n=this._objects.findIndex((o=>o.isInFrontOf(i))),r=n===-1?this.size():n;this.insertAt(r,i)}))}canEnterGroup(t){return this.getObjects().some((e=>e.isDescendantOf(t)||t.isDescendantOf(e)))?(De("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach((i=>{const{parent:n}=i;n&&s.add(n)})),t===Rr?s.forEach((i=>{i._onAfterObjectsChange(Ji,e)})):s.forEach((i=>{i._set("dirty",!0)}))}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=w(w({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}x(gs,"type","ActiveSelection"),x(gs,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),L.setClass(gs),L.setClass(gs,"activeSelection");class bd{constructor(){x(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const o={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach((l=>{l.applyTo(o)}));const{imageData:h}=o;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),o}}class Fh{constructor(){let{tileSize:t=et.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};x(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),x(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=te({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const o=this.gl,h=n.getContext("2d");if(!o||!h)return;let l;r&&(l=this.getCachedTexture(r,e));const c={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:o,sourceTexture:this.createTexture(o,s,i,l?void 0:e),targetTexture:this.createTexture(o,s,i),originalTexture:l||this.createTexture(o,s,i,l?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach((d=>{d&&d.applyTo(c)})),(function(d){const f=d.targetCanvas,g=f.width,p=f.height,b=d.destinationWidth,m=d.destinationHeight;g===b&&p===m||(f.width=b,f.height=m)})(c),this.copyGLTo2D(o,c),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(c.sourceTexture),o.deleteTexture(c.targetTexture),o.deleteFramebuffer(u),h.setTransform(1,0,0,1,0,0),c}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,i,n){const{NEAREST:r,TEXTURE_2D:o,RGBA:h,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:g}=t,p=t.createTexture();return t.bindTexture(o,p),t.texParameteri(o,u,n||r),t.texParameteri(o,d,n||r),t.texParameteri(o,f,c),t.texParameteri(o,g,c),i?t.texImage2D(o,0,h,h,l,i):t.texImage2D(o,0,h,e,s,0,h,l,null),p}getCachedTexture(t,e,s){const{textureCache:i}=this;if(i[t])return i[t];{const n=this.createTexture(this.gl,e.width,e.height,e,s);return n&&(i[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,i=e.targetCanvas,n=i.getContext("2d");if(!n)return;n.translate(0,i.height),n.scale(1,-1);const r=s.height-i.height;n.drawImage(s,0,r,i.width,i.height,0,0,i.width,i.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),i=e.destinationWidth,n=e.destinationHeight,r=i*n*4;if(!s)return;const o=new Uint8Array(this.imageBuffer,0,r),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,o);const l=new ImageData(h,i,n);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let Vr;function vd(){const{WebGLProbe:a}=xe();return a.queryWebGL(Se()),et.enableGLFiltering&&a.isSupported(et.textureSize)?new Fh({tileSize:et.textureSize}):new bd}function Wr(){return!Vr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(Vr=vd()),Vr}const yd=["filters","resizeFilter","src","crossOrigin","type"],Ih=["cropX","cropY"];class Lt extends Dt{static getDefaults(){return w(w({},super.getDefaults()),Lt.ownDefaults)}constructor(t,e){super(),x(this,"_lastScaleX",1),x(this,"_lastScaleY",1),x(this,"_filterScalingX",1),x(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Lt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Ue()),this.setElement(typeof t=="string"?(this.canvas&&ue(this.canvas.getElement())||xs()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Lt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=Wr(!1);e instanceof Fh&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach((t=>{const e=this[t];e&&xe().dispose(e),this[t]=void 0}))}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach((s=>{s&&e.push(s.toObject())})),w(w({},super.toObject([...Ih,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],o="",h="";if(!e)return[];if(this.hasCrop()){const l=Ue();n.push('<clipPath id="imageCrop_'+l+`">
63
63
  `,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
64
64
  `,`</clipPath>
65
65
  `),o=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(h=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",'xlink:href="'.concat(this.getSvgSrc(!0),'" x="').concat(s-this.cropX,'" y="').concat(i-this.cropY,'" width="').concat(e.width||e.naturalWidth,'" height="').concat(e.height||e.naturalHeight,'"').concat(h).concat(o,`></image>
66
66
  `)),this.stroke||this.strokeDashArray){const l=this.fill;this.fill=null,r=[' <rect x="'.concat(s,'" y="').concat(i,'" width="').concat(this.width,'" height="').concat(this.height,'" style="').concat(this.getSvgStyles(),`" />
67
- `)],this.fill=l}return n=this.paintFirst!==wt?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Zs(t,{crossOrigin:e,signal:s}).then((i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)}))}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const o=te(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,Wr().applyFilters([t],r,h,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter((n=>n&&!n.isNeutralState())),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=te({width:s,height:i});this._element=n,this._filteredEl=n}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,i),this._lastScaleX=1,this._lastScaleY=1);Wr().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=o*s,d=h*i,f=Math.min(n*s,l-u),g=Math.min(r*i,c-d),p=-n/2,b=-r/2,m=Math.min(n,l/s-o),v=Math.min(r,c/i-h);e&&t.drawImage(e,u,d,f,g,p,b,m,v)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=pr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,h=1,l=1,c=0,u=0,d=0,f=0;return!t||t.alignX===jt&&t.alignY===jt?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=ah(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-o*l)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(h=l=hh(this._element,i),n=r-e/h,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=o-s/l,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/h,o=s/l)),{width:r,height:o,scaleX:h,scaleY:l,offsetLeft:c,offsetTop:u,cropX:d,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=lt(t,yd);return Promise.all([Zs(n,w(w({},e),{},{crossOrigin:r})),s&&Es(s,e),i&&Es([i],e),Qs(h,e)]).then((l=>{let[c,u=[],[d]=[],f={}]=l;return new this(c,w(w({},h),{},{src:n,filters:u,resizeFilter:d},f))}))}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return Zs(t,{crossOrigin:e,signal:s}).then((n=>new this(n,i)))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const i=Ne(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch((n=>(De("log","Unable to parse Image",n),null)))}}function Xr(a){if(!Tc.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const h=a.getAttribute("width"),l=a.getAttribute("height"),c=a.getAttribute("x")||0,u=a.getAttribute("y")||0,d=!(t&&Aa.test(t)),f=!h||!l||h==="100%"||l==="100%";let g="",p=0,b=0;if(d&&(c||u)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(g=" translate("+zt(c||"0")+" "+zt(u||"0")+") ",e=(a.getAttribute("transform")||"")+g,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),d&&f)return{width:0,height:0};const m={width:0,height:0};if(d)return m.width=zt(h),m.height=zt(l),m;const v=t.match(Aa);r=-parseFloat(v[1]),o=-parseFloat(v[2]);const y=parseFloat(v[3]),_=parseFloat(v[4]);m.minX=r,m.minY=o,m.viewBoxWidth=y,m.viewBoxHeight=_,f?(m.width=y,m.height=_):(m.width=zt(h),m.height=zt(l),i=m.width/y,n=m.height/_);const S=pr(a.getAttribute("preserveAspectRatio")||"");if(S.alignX!==jt&&(S.meetOrSlice==="meet"&&(n=i=i>n?n:i),S.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-y*i,b=m.height-_*i,S.alignX==="Mid"&&(p/=2),S.alignY==="Mid"&&(b/=2),S.alignX==="Min"&&(p=0),S.alignY==="Min"&&(b=0)),i===1&&n===1&&r===0&&o===0&&c===0&&u===0)return m;if((c||u)&&a.parentNode.nodeName!=="#document"&&(g=" translate("+zt(c||"0")+" "+zt(u||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(o*n+b)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(br,"g");a.firstChild;)s.appendChild(a.firstChild);a.appendChild(s)}else s=a,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),m}x(Dt,"type","Image"),x(Dt,"cacheProperties",[...Fe,...Ih]),x(Dt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),x(Dt,"CSS_CANVAS","canvas-img"),x(Dt,"ATTRIBUTE_NAMES",[...Ye,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),L.setClass(Dt),L.setSVGClass(Dt);const un=a=>a.tagName.replace("svg:",""),_d=Bi(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function Nh(a,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=a.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const wd=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Ur="xlink:href";function jh(a,t){var e;const s=((e=t.getAttribute(Ur))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(Ur)&&jh(a,i),i&&(wd.forEach((n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)})),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(Ur)}const xd=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function Sd(a){const t=a.getElementsByTagName("style"),e={};for(let s=0;s<t.length;s++){const i=(t[s].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");i.trim()!==""&&i.split("}").filter(((n,r,o)=>o.length>1&&n.trim())).forEach((n=>{if((n.match(/{/g)||[]).length>1&&n.trim().startsWith("@"))return;const r=n.split("{"),o={},h=r[1].trim().split(";").filter((function(l){return l.trim()}));for(let l=0;l<h.length;l++){const c=h[l].split(":"),u=c[0].trim(),d=c[1].trim();o[u]=d}(n=r[0].trim()).split(",").forEach((l=>{(l=l.replace(/^svg/i,"").trim())!==""&&(e[l]=w(w({},e[l]||{}),o))}))}))}return e}const Bh=a=>L.getSVGClass(un(a).toLowerCase());class Cd{constructor(t,e,s,i,n){this.elements=t,this.options=e,this.reviver=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=i,this.clipPaths=n,this.gradientDefs=(function(r){const o=Nh(r,xd),h={};let l=o.length;for(;l--;){const c=o[l];c.getAttribute("xlink:href")&&jh(r,c);const u=c.getAttribute("id");u&&(h[u]=c)}return h})(i),this.cssRules=Sd(i)}parse(){return Promise.all(this.elements.map((t=>this.createObject(t))))}async createObject(t){const e=Bh(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,wt),this.resolveGradient(s,t,Ht),s instanceof Dt&&s._originalElement?sn(s,s.parsePreserveAspectRatioAttribute()):sn(s),await this.resolveClipPath(s,t),this.reviver&&this.reviver(t,s),s}return null}extractPropertyDefinition(t,e,s){const i=t[e],n=this.regexUrl;if(!n.test(i))return;n.lastIndex=0;const r=n.exec(i)[1];return n.lastIndex=0,s[r]}resolveGradient(t,e,s){const i=this.extractPropertyDefinition(t,s,this.gradientDefs);if(i){const n=e.getAttribute(s+"-opacity"),r=ci.fromElement(i,t,w(w({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=$t(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=Ki("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map((v=>Bh(v).fromElement(v,this.options,this.cssRules).then((y=>(sn(y),y.fillRule=y.clipRule,delete y.clipRule,y)))))),c=l.length===1?l[0]:new ee(l),u=vt(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:d,scaleY:f,angle:g,skewX:p,translateX:b,translateY:m}=is(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new C(b,m),$,$),t.clipPath=c}else delete t.clipPath}}const Hh=a=>Ac.test(un(a)),Yr=()=>({objects:[],elements:[],options:{},allElements:[]});async function Ad(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return De("log",new Kn("parseSVGDocument")),Yr();const i=a.documentElement;(function(c){const u=Nh(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const P of g)P.value&&(p[P.name]=P.value);const b=(p["xlink:href"]||p.href||"").slice(1);if(b==="")return;const m=c.getElementById(b);if(m===null)return;let v=m.cloneNode(!0);const y=v.attributes,_={};for(const P of y)P.value&&(_[P.name]=P.value);const{x:S=0,y:A=0,transform:T=""}=p,k="".concat(T," ").concat(_.transform||""," translate(").concat(S,", ").concat(A,")");if(Xr(v),/^svg$/i.test(v.nodeName)){const P=v.ownerDocument.createElementNS(br,"g");Object.entries(_).forEach((B=>{let[F,I]=B;return P.setAttributeNS(br,F,I)})),P.append(...v.childNodes),v=P}for(const P of g){if(!P)continue;const{name:B,value:F}=P;if(!d.includes(B))if(B==="style"){const I={};Dr(F,I),Object.entries(_).forEach((D=>{let[z,M]=D;I[z]=M})),Dr(_.style||"",I);const O=Object.entries(I).map((D=>D.join(":"))).join(";");v.setAttribute(B,O)}else!_[B]&&v.setAttribute(B,F)}v.setAttribute("transform",k),v.setAttribute("instantiated_by_use","1"),v.removeAttribute("id"),f.parentNode.replaceChild(v,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=w(w({},Xr(i)),{},{crossOrigin:e,signal:s}),o=n.filter((c=>(Xr(c),Hh(c)&&!(function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&_d.test(un(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1})(c))));if(!o||o&&!o.length)return w(w({},Yr()),{},{options:r,allElements:n});const h={};return n.filter((c=>un(c)==="clipPath")).forEach((c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");h[u]=Array.from(c.getElementsByTagName("*")).filter((d=>Hh(d)))})),{objects:await new Cd(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Td(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise(((s,i)=>{_h(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})})).then((s=>Ad(s,t,e))).catch((()=>Yr()))}const dn=a=>a.webgl!==void 0,$r="precision highp float",Ed=`
67
+ `)],this.fill=l}return n=this.paintFirst!==wt?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Zs(t,{crossOrigin:e,signal:s}).then((i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)}))}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const o=te(r),{width:h,height:l}=r;this._element=o,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,Wr().applyFilters([t],r,h,l,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter((n=>n&&!n.isNeutralState())),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=te({width:s,height:i});this._element=n,this._filteredEl=n}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,i),this._lastScaleX=1,this._lastScaleY=1);Wr().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=o*s,d=h*i,f=Math.min(n*s,l-u),g=Math.min(r*i,c-d),p=-n/2,b=-r/2,m=Math.min(n,l/s-o),v=Math.min(r,c/i-h);e&&t.drawImage(e,u,d,f,g,p,b,m,v)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=pr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,o=this._element.height,h=1,l=1,c=0,u=0,d=0,f=0;return!t||t.alignX===Bt&&t.alignY===Bt?(h=e/r,l=s/o):(t.meetOrSlice==="meet"&&(h=l=ah(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-o*l)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(h=l=hh(this._element,i),n=r-e/h,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=o-s/l,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/h,o=s/l)),{width:r,height:o,scaleX:h,scaleY:l,offsetLeft:c,offsetTop:u,cropX:d,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:o}=t,h=ct(t,yd);return Promise.all([Zs(n,w(w({},e),{},{crossOrigin:r})),s&&Es(s,e),i&&Es([i],e),Qs(h,e)]).then((l=>{let[c,u=[],[d]=[],f={}]=l;return new this(c,w(w({},h),{},{src:n,filters:u,resizeFilter:d},f))}))}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return Zs(t,{crossOrigin:e,signal:s}).then((n=>new this(n,i)))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const i=Ne(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch((n=>(De("log","Unable to parse Image",n),null)))}}function Xr(a){if(!Tc.test(a.nodeName))return{};const t=a.getAttribute("viewBox");let e,s,i=1,n=1,r=0,o=0;const h=a.getAttribute("width"),l=a.getAttribute("height"),c=a.getAttribute("x")||0,u=a.getAttribute("y")||0,d=!(t&&Aa.test(t)),f=!h||!l||h==="100%"||l==="100%";let g="",p=0,b=0;if(d&&(c||u)&&a.parentNode&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Gt(c||"0")+" "+Gt(u||"0")+") ",e=(a.getAttribute("transform")||"")+g,a.setAttribute("transform",e),a.removeAttribute("x"),a.removeAttribute("y")),d&&f)return{width:0,height:0};const m={width:0,height:0};if(d)return m.width=Gt(h),m.height=Gt(l),m;const v=t.match(Aa);r=-parseFloat(v[1]),o=-parseFloat(v[2]);const y=parseFloat(v[3]),_=parseFloat(v[4]);m.minX=r,m.minY=o,m.viewBoxWidth=y,m.viewBoxHeight=_,f?(m.width=y,m.height=_):(m.width=Gt(h),m.height=Gt(l),i=m.width/y,n=m.height/_);const S=pr(a.getAttribute("preserveAspectRatio")||"");if(S.alignX!==Bt&&(S.meetOrSlice==="meet"&&(n=i=i>n?n:i),S.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-y*i,b=m.height-_*i,S.alignX==="Mid"&&(p/=2),S.alignY==="Mid"&&(b/=2),S.alignX==="Min"&&(p=0),S.alignY==="Min"&&(b=0)),i===1&&n===1&&r===0&&o===0&&c===0&&u===0)return m;if((c||u)&&a.parentNode.nodeName!=="#document"&&(g=" translate("+Gt(c||"0")+" "+Gt(u||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(o*n+b)+") ",a.nodeName==="svg"){for(s=a.ownerDocument.createElementNS(br,"g");a.firstChild;)s.appendChild(a.firstChild);a.appendChild(s)}else s=a,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),m}x(Lt,"type","Image"),x(Lt,"cacheProperties",[...Fe,...Ih]),x(Lt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),x(Lt,"CSS_CANVAS","canvas-img"),x(Lt,"ATTRIBUTE_NAMES",[...Ye,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),L.setClass(Lt),L.setSVGClass(Lt);const un=a=>a.tagName.replace("svg:",""),_d=Bi(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function Nh(a,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=a.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const wd=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Ur="xlink:href";function jh(a,t){var e;const s=((e=t.getAttribute(Ur))===null||e===void 0?void 0:e.slice(1))||"",i=a.getElementById(s);if(i&&i.getAttribute(Ur)&&jh(a,i),i&&(wd.forEach((n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)})),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(Ur)}const xd=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function Sd(a){const t=a.getElementsByTagName("style"),e={};for(let s=0;s<t.length;s++){const i=(t[s].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");i.trim()!==""&&i.split("}").filter(((n,r,o)=>o.length>1&&n.trim())).forEach((n=>{if((n.match(/{/g)||[]).length>1&&n.trim().startsWith("@"))return;const r=n.split("{"),o={},h=r[1].trim().split(";").filter((function(l){return l.trim()}));for(let l=0;l<h.length;l++){const c=h[l].split(":"),u=c[0].trim(),d=c[1].trim();o[u]=d}(n=r[0].trim()).split(",").forEach((l=>{(l=l.replace(/^svg/i,"").trim())!==""&&(e[l]=w(w({},e[l]||{}),o))}))}))}return e}const Bh=a=>L.getSVGClass(un(a).toLowerCase());class Cd{constructor(t,e,s,i,n){this.elements=t,this.options=e,this.reviver=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=i,this.clipPaths=n,this.gradientDefs=(function(r){const o=Nh(r,xd),h={};let l=o.length;for(;l--;){const c=o[l];c.getAttribute("xlink:href")&&jh(r,c);const u=c.getAttribute("id");u&&(h[u]=c)}return h})(i),this.cssRules=Sd(i)}parse(){return Promise.all(this.elements.map((t=>this.createObject(t))))}async createObject(t){const e=Bh(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,wt),this.resolveGradient(s,t,zt),s instanceof Lt&&s._originalElement?sn(s,s.parsePreserveAspectRatioAttribute()):sn(s),await this.resolveClipPath(s,t),this.reviver&&this.reviver(t,s),s}return null}extractPropertyDefinition(t,e,s){const i=t[e],n=this.regexUrl;if(!n.test(i))return;n.lastIndex=0;const r=n.exec(i)[1];return n.lastIndex=0,s[r]}resolveGradient(t,e,s){const i=this.extractPropertyDefinition(t,s,this.gradientDefs);if(i){const n=e.getAttribute(s+"-opacity"),r=ci.fromElement(i,t,w(w({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=qt(t.calcTransformMatrix()),r=i[0].parentElement;let o=e;for(;!s&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const h=Ki("".concat(o.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const l=await Promise.all(i.map((v=>Bh(v).fromElement(v,this.options,this.cssRules).then((y=>(sn(y),y.fillRule=y.clipRule,delete y.clipRule,y)))))),c=l.length===1?l[0]:new ee(l),u=vt(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:d,scaleY:f,angle:g,skewX:p,translateX:b,translateY:m}=is(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new C(b,m),$,$),t.clipPath=c}else delete t.clipPath}}const Hh=a=>Ac.test(un(a)),Yr=()=>({objects:[],elements:[],options:{},allElements:[]});async function Ad(a,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return De("log",new Kn("parseSVGDocument")),Yr();const i=a.documentElement;(function(c){const u=Nh(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const P of g)P.value&&(p[P.name]=P.value);const b=(p["xlink:href"]||p.href||"").slice(1);if(b==="")return;const m=c.getElementById(b);if(m===null)return;let v=m.cloneNode(!0);const y=v.attributes,_={};for(const P of y)P.value&&(_[P.name]=P.value);const{x:S=0,y:A=0,transform:T=""}=p,k="".concat(T," ").concat(_.transform||""," translate(").concat(S,", ").concat(A,")");if(Xr(v),/^svg$/i.test(v.nodeName)){const P=v.ownerDocument.createElementNS(br,"g");Object.entries(_).forEach((B=>{let[F,I]=B;return P.setAttributeNS(br,F,I)})),P.append(...v.childNodes),v=P}for(const P of g){if(!P)continue;const{name:B,value:F}=P;if(!d.includes(B))if(B==="style"){const I={};Dr(F,I),Object.entries(_).forEach((D=>{let[z,M]=D;I[z]=M})),Dr(_.style||"",I);const O=Object.entries(I).map((D=>D.join(":"))).join(";");v.setAttribute(B,O)}else!_[B]&&v.setAttribute(B,F)}v.setAttribute("transform",k),v.setAttribute("instantiated_by_use","1"),v.removeAttribute("id"),f.parentNode.replaceChild(v,f)}})(a);const n=Array.from(i.getElementsByTagName("*")),r=w(w({},Xr(i)),{},{crossOrigin:e,signal:s}),o=n.filter((c=>(Xr(c),Hh(c)&&!(function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&_d.test(un(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1})(c))));if(!o||o&&!o.length)return w(w({},Yr()),{},{options:r,allElements:n});const h={};return n.filter((c=>un(c)==="clipPath")).forEach((c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");h[u]=Array.from(c.getElementsByTagName("*")).filter((d=>Hh(d)))})),{objects:await new Cd(o,r,t,a,h).parse(),elements:o,options:r,allElements:n}}function Td(a,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise(((s,i)=>{_h(a.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})})).then((s=>Ad(s,t,e))).catch((()=>Yr()))}const dn=a=>a.webgl!==void 0,$r="precision highp float",Ed=`
68
68
  `.concat($r,`;
69
69
  varying vec2 vTexCoord;
70
70
  uniform sampler2D uTexture;
71
71
  void main() {
72
72
  gl_FragColor = texture2D(uTexture, vTexCoord);
73
- }`),kd=["type"],Md=["type"],Pd=new RegExp($r,"g");class At{get type(){return this.constructor.type}constructor(){let t=lt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},kd);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Ed}getVertexSource(){return`
73
+ }`),kd=["type"],Md=["type"],Pd=new RegExp($r,"g");class At{get type(){return this.constructor.type}constructor(){let t=ct(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},kd);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Ed}getVertexSource(){return`
74
74
  attribute vec2 aPosition;
75
75
  varying vec2 vTexCoord;
76
76
  void main() {
77
77
  vTexCoord = aPosition;
78
78
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
79
- }`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=xe();i!=="highp"&&(e=e.replace(Pd,$r.replace("highp",i)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!n||!r||!o)throw new we("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new we("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new we("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new we('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(o)));const h=this.getUniformLocations(t,o)||{};return h.uStepW=t.getUniformLocation(o,"uStepW"),h.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,i={};for(let n=0;n<s.length;n++)i[s[n]]=t.getUniformLocation(e,s[n]);return i}sendAttributeData(t,e,s){const i=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,i=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===i||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,i)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){dn(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:s}=t,i=te({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return w({type:this.type},t.reduce(((e,s)=>(e[s]=this[s],e)),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(lt(t,Md))}}x(At,"type","BaseFilter"),x(At,"uniformLocations",[]);const Od={multiply:`gl_FragColor.rgb *= uColor.rgb;
79
+ }`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=xe();i!=="highp"&&(e=e.replace(Pd,$r.replace("highp",i)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!n||!r||!o)throw new we("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new we("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new we("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new we('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(o)));const h=this.getUniformLocations(t,o)||{};return h.uStepW=t.getUniformLocation(o,"uStepW"),h.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,i={};for(let n=0;n<s.length;n++)i[s[n]]=t.getUniformLocation(e,s[n]);return i}sendAttributeData(t,e,s){const i=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,i=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===i||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,i)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){dn(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:s}=t,i=te({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return w({type:this.type},t.reduce(((e,s)=>(e[s]=this[s],e)),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(ct(t,Md))}}x(At,"type","BaseFilter"),x(At,"uniformLocations",[]);const Od={multiply:`gl_FragColor.rgb *= uColor.rgb;
80
80
  `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
81
81
  `,add:`gl_FragColor.rgb += uColor.rgb;
82
82
  `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
@@ -151,7 +151,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
151
151
  vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
152
152
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
153
153
  }
154
- `}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=Se());const o=n.blendImage,h=o.getContext("2d");o.width!==s||o.height!==i?(o.width=s,o.height=i):h.clearRect(0,0,s,i),h.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),h.drawImage(r.getElement(),0,0,s,i);const l=h.getImageData(0,0,s,i).data;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2],g=e[c+3],p=l[c],b=l[c+1],m=l[c+2],v=l[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=d*b/255,e[c+2]=f*m/255,e[c+3]=g*v/255;break;case"mask":e[c+3]=v}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return w(w({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=lt(t,Rd);return Dt.fromObject(i,e).then((r=>new this(w(w({},n),{},{image:r}))))}}x(gn,"type","BlendImage"),x(gn,"defaults",{mode:"multiply",alpha:1}),x(gn,"uniformLocations",["uTransformMatrix","uImage"]),L.setClass(gn);class pn extends At{getFragmentSource(){return`
154
+ `}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=Se());const o=n.blendImage,h=o.getContext("2d");o.width!==s||o.height!==i?(o.width=s,o.height=i):h.clearRect(0,0,s,i),h.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),h.drawImage(r.getElement(),0,0,s,i);const l=h.getImageData(0,0,s,i).data;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2],g=e[c+3],p=l[c],b=l[c+1],m=l[c+2],v=l[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=d*b/255,e[c+2]=f*m/255,e[c+3]=g*v/255;break;case"mask":e[c+3]=v}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return w(w({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=ct(t,Rd);return Lt.fromObject(i,e).then((r=>new this(w(w({},n),{},{image:r}))))}}x(gn,"type","BlendImage"),x(gn,"defaults",{mode:"multiply",alpha:1}),x(gn,"uniformLocations",["uTransformMatrix","uImage"]),L.setClass(gn);class pn extends At{getFragmentSource(){return`
155
155
  precision highp float;
156
156
  uniform sampler2D uTexture;
157
157
  uniform vec2 uDelta;
@@ -506,10 +506,10 @@ void main() {
506
506
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
507
507
  gl_FragColor = color;
508
508
  }
509
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),l=(n+r+o)/3,c=2*Math.abs(h-l)/255*s;e[i]+=h!==n?(h-n)*c:0,e[i+1]+=h!==r?(h-r)*c:0,e[i+2]+=h!==o?(h-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}x(En,"type","Vibrance"),x(En,"defaults",{vibrance:0}),x(En,"uniformLocations",["uVibrance"]),L.setClass(En);var ui={};ui.d=(a,t)=>{for(var e in t)ui.o(t,e)&&!ui.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},ui.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var Y=globalThis.pdfjsLib={};ui.d(Y,{AbortException:()=>Je,AnnotationEditorLayer:()=>Ve,AnnotationEditorParamsType:()=>tt,AnnotationEditorType:()=>q,AnnotationEditorUIManager:()=>Ze,AnnotationLayer:()=>Dg,AnnotationMode:()=>qe,ColorPicker:()=>he,DOMSVGFactory:()=>_o,DrawLayer:()=>Xt,FeatureTest:()=>Vt,GlobalWorkerOptions:()=>_i,ImageKind:()=>kn,InvalidPDFException:()=>Qr,MissingPDFException:()=>fi,OPS:()=>be,OutputScale:()=>ao,PDFDataRangeTransport:()=>Al,PDFDateString:()=>qh,PDFWorker:()=>zs,PasswordResponses:()=>Hd,PermissionFlag:()=>Bd,PixelsPerInch:()=>js,RenderingCancelledException:()=>no,TextLayer:()=>Wt,TouchManager:()=>Nn,UnexpectedResponseException:()=>Dn,Util:()=>G,VerbosityLevel:()=>Mn,XfaLayer:()=>Ml,build:()=>dg,createValidAbsoluteUrl:()=>Wd,fetchData:()=>Ln,getDocument:()=>ig,getFilenameFromUrl:()=>Qd,getPdfFilenameFromUrl:()=>tf,getXfaPageViewport:()=>ef,isDataScheme:()=>Fn,isPdfFile:()=>ro,noContextMenu:()=>ve,normalizeUnicode:()=>Kd,setLayerDimensions:()=>ms,shadow:()=>Z,stopEvent:()=>ne,version:()=>ug});const Rt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Wh=[1,0,0,1,0,0],Kr=[.001,0,0,.001,0,0],Nd=1e7,Jr=1.35,ie={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},qe={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},jd="pdfjs_internal_editor_",q={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},tt={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Bd={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Lt={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},kn={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},di={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Mn={ERRORS:0,WARNINGS:1,INFOS:5},be={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},Hd={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Pn=Mn.WARNINGS;function zd(a){Number.isInteger(a)&&(Pn=a)}function Gd(){return Pn}function On(a){Pn>=Mn.INFOS&&console.log(`Info: ${a}`)}function K(a){Pn>=Mn.WARNINGS&&console.log(`Warning: ${a}`)}function at(a){throw new Error(a)}function St(a,t){a||at(t)}function Vd(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Wd(a,t=null,e=null){if(!a)return null;try{if(e&&typeof a=="string"&&(e.addDefaultProtocol&&a.startsWith("www.")&&a.match(/\./g)?.length>=2&&(a=`http://${a}`),e.tryConvertEncoding))try{a=qd(a)}catch{}const s=t?new URL(a,t):new URL(a);if(Vd(s))return s}catch{}return null}function Z(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Ke=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Xh extends Ke{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Zr extends Ke{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Qr extends Ke{constructor(t){super(t,"InvalidPDFException")}}class fi extends Ke{constructor(t){super(t,"MissingPDFException")}}class Dn extends Ke{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Xd extends Ke{constructor(t){super(t,"FormatError")}}class Je extends Ke{constructor(t){super(t,"AbortException")}}function Uh(a){(typeof a!="object"||a?.length===void 0)&&at("Invalid argument for bytesToString");const t=a.length,e=8192;if(t<e)return String.fromCharCode.apply(null,a);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=a.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function Rn(a){typeof a!="string"&&at("Invalid argument for stringToBytes");const t=a.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=a.charCodeAt(s)&255;return e}function Ud(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function to(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Yd(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function $d(){try{return new Function(""),!0}catch{return!1}}class Vt{static get isLittleEndian(){return Z(this,"isLittleEndian",Yd())}static get isEvalSupported(){return Z(this,"isEvalSupported",$d())}static get isOffscreenCanvasSupported(){return Z(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Z(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?Z(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):Z(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Z(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const eo=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class G{static makeHexColor(t,e,s){return`#${eo[t]}${eo[e]}${eo[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],o=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,l=o+h||1,c=o-h||1;return[Math.sqrt(l),Math.sqrt(c)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static#t(t,e,s,i,n,r,o,h,l,c){if(l<=0||l>=1)return;const u=1-l,d=l*l,f=d*l,g=u*(u*(u*t+3*l*e)+3*d*s)+f*i,p=u*(u*(u*n+3*l*r)+3*d*o)+f*h;c[0]=Math.min(c[0],g),c[1]=Math.min(c[1],p),c[2]=Math.max(c[2],g),c[3]=Math.max(c[3],p)}static#e(t,e,s,i,n,r,o,h,l,c,u,d){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,h,-u/c,d);return}const f=c**2-4*u*l;if(f<0)return;const g=Math.sqrt(f),p=2*l;this.#t(t,e,s,i,n,r,o,h,(-c+g)/p,d),this.#t(t,e,s,i,n,r,o,h,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){return l?(l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h)):l=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],this.#e(t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l),l}}function qd(a){return decodeURIComponent(escape(a))}let so=null,Yh=null;function Kd(a){return so||(so=/([\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,Yh=new Map([["ſt","ſt"]])),a.replaceAll(so,(t,e,s)=>e?e.normalize("NFKC"):Yh.get(s))}function Jd(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),Uh(a)}const io="pdfjs_internal_id_";function Zd(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(Uh(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const Ge="http://www.w3.org/2000/svg";class js{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ln(a,t="text"){if(pi(a,document.baseURI)){const e=await fetch(a);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",a,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class gi{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let c,u,d,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,u=0,d=0,f=1;break;case 90:c=0,u=1,d=1,f=0;break;case 270:c=0,u=-1,d=-1,f=0;break;case 0:c=1,u=0,d=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(d=-d,f=-f);let g,p,b,m;c===0?(g=Math.abs(l-t[1])*s+n,p=Math.abs(h-t[0])*s+r,b=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(h-t[0])*s+n,p=Math.abs(l-t[1])*s+r,b=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,u*s,d*s,f*s,g-c*s*h-d*s*l,p-u*s*h-f*s*l],this.width=b,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return Z(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new gi({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return G.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=G.applyTransform([t[0],t[1]],this.transform),s=G.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return G.applyInverseTransform([t,e],this.transform)}}class no extends Ke{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Fn(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function ro(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Qd(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function tf(a,t="document.pdf"){if(typeof a!="string")return t;if(Fn(a))return K('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class $h{started=Object.create(null);times=[];time(t){t in this.started&&K(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||K(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
510
- `);return t.join("")}}function pi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ve(a){a.preventDefault()}function ne(a){a.preventDefault(),a.stopPropagation()}class qh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,l==="-"?(r+=c,o+=u):l==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}function ef(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new gi({viewBox:n,userUnit:1,scale:t,rotation:e})}function oo(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(K(`Not a valid color format: "${a}"`),[0,0,0])}function sf(a){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,oo(s))}t.remove()}function ct(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function ke(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform().invertSelf();return[t,e,s,i,n,r]}function ms(a,t,e=!1,s=!0){if(t instanceof gi){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Vt.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class ao{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class mi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,mi.#n||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",ve,{signal:e}),t.addEventListener("pointerdown",mi.#h,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#h(t){t.stopPropagation()}#a(t){this.#s._focusEventsAllowed=!1,ne(t)}#c(t){this.#s._focusEventsAllowed=!0,ne(t)}#l(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#a.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ve,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",mi.#n[t]),this.#l(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#l(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#l(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class nf{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ve,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const o=n.x+(e?n.width:0);if(r>s){i=o,s=r;continue}e?o>i&&(i=o):o<i&&(i=o)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",ve,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function In(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class rf{#t=0;get id(){return`${jd}${this.#t++}`}}class ho{#t=Jd();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return Z(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Ln(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=ho._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){K(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class of{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),this.#e)return;const h={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class bi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Vt.platform;for(const[s,i,n={}]of t)for(const r of s){const o=r.startsWith("mac+");e&&o?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!o&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||ne(e))}}class lo{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return sf(t),Z(this,"_colors",t)}convert(t){const e=oo(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return lo._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?G.makeHexColor(...e):t}}class Ze{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#h=null;#a=new of;#c=null;#l=null;#d=0;#u=new Set;#f=null;#o=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#b=!1;#_=null;#v=null;#w=null;#S=null;#A=!1;#E=null;#M=new rf;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=q.NONE;#y=new Set;#R=null;#z=null;#G=null;#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#N=[0,0];#F=null;#j=null;#W=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Ze.prototype,e=r=>r.#j.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return Z(this,"_keyboardManager",new bi([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,o,h,l,c,u,d,f){const g=this._signal=this.#t.signal;this.#j=t,this.#W=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=o||null,this.#m=h,this.#p=l,this.#b=c,this.#I=u||null,this.viewParameters={realScale:js.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#a.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#v&&(clearTimeout(this.#v),this.#v=null),this.#F&&(clearTimeout(this.#F),this.#F=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return Z(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return Z(this,"direction",getComputedStyle(this.#j).direction)}get highlightColors(){return Z(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return Z(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=t}setMainHighlightColorPicker(t){this.#L=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":this.#b=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#j.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)return s}return null}disableUserSelect(t=!1){this.#W.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*js.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#Y(l),d=this.#C===q.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(q.HIGHLIGHT,f);return}f()}#Q(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new nf(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#P({hasSelectedText:!0}),!(this.#C!==q.HIGHLIGHT&&this.#C!==q.NONE)&&(this.#C===q.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===q.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}}#U(t=""){this.#C===q.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Q()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of this.#o)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){K(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#J(h);this.#Z(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){K(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==q.NONE&&!this.isEditorHandlingKeyboard&&Ze._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#P(t){Object.entries(t).some(([s,i])=>this.#V[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)}),this.#C===q.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[tt.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==q.NONE,isEmpty:this.#X(),hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:this.#a.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#o){this.#o=t;for(const e of this.#o)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#M.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===q.NONE){this.setEditingState(!1),this.#at(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#ot(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#o){switch(t){case tt.CREATE:this.currentLayer.addNewEditor();return;case tt.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case tt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#o)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#G?.get(tt.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[tt.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ot(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#at(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.focusMainContainer(),this.#v=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#ht(){let t=null;for(t of this.#y);return t}updateUI(t){this.#ht===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){this.#l?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#a.undo(),this.#P({hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#X()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#X()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#X()})}cleanUndoStack(t){this.#a.cleanType(t)}#X(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Z(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Z(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==q.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#P({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#N[0]+=t,this.#N[1]+=e;const[i,n]=this.#N,r=[...this.#y],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=null,this.#N[0]=this.#N[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex;if(!e)return!1;const s=(i,n,r,o)=>{if(this.#s.has(i.id)){const h=this.#i.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return Z(this,"imageManager",new ho)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,u,d)=>({x:(c-i)/r,y:1-(l+u-s)/n,width:d/r,height:u/n});break;case"180":o=(l,c,u,d)=>({x:1-(l+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":o=(l,c,u,d)=>({x:1-(c+d-i)/r,y:(l-s)/n,width:d/r,height:u/n});break;default:o=(l,c,u,d)=>({x:(l-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||h.push(o(d,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===q.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Me{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#h=!1;#a=null;#c=null;#l=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Me.#f||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){Me._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Me.#f.missing),e.setAttribute("data-l10n-id",Me.#f["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",ve,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#o}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#h=!0,i(n))},{signal:s}),await this.#g(),t}get#o(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#h}),this.#h=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#d=await Me._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#a.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#o}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#a?.remove(),this.#a=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Me.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Me.#f[`${this.#o}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class Nn{#t;#e=!1;#s=null;#i;#r;#n;#h;#a;#c=null;#l;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#h=r,this.#l=new AbortController,this.#a=AbortSignal.any([o,this.#l.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Z(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#a,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#o.bind(this),r),n.addEventListener("touchcancel",this.#o.bind(this),r),this.#r?.()}if(ne(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=this.#c,{touch0X:l,touch0Y:c,touch1X:u,touch1Y:d}=h,f=u-l,g=d-c,p=r-i,b=o-n,m=Math.hypot(p,b)||1,v=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(v-m)<=Nn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const y=[(i+r)/2,(n+o)/2];this.#n?.(y,v,m)}#o(t){this.#d.abort(),this.#d=null,this.#h?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#l?.abort(),this.#l=null}}class W{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#h=!1;#a=null;#c=null;#l=null;#d=null;#u="";#f=!1;#o=null;#g=!1;#m=!1;#p=!1;#b=null;#_=0;#v=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=W._zIndex++;static _borderLineWidth=-1;static _colorManager=new lo;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=W.prototype._resizeWithKeyboard,e=Ze.TRANSLATE_SMALL,s=Ze.TRANSLATE_BIG;return Z(this,"_resizerKeyboardManager",new bi([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],W.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return Z(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new af({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(W._l10n??=t,W._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"}),W._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);W._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){at("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}#M([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#o||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#o||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,l]=this.getBaseTranslation();r+=h,o+=l;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#o&&(this.#o[0]!==this.x||this.#o[1]!==this.y)}get _hasBeenResized(){return!!this.#o&&(this.#o[2]!==this.width||this.#o[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=W,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return W.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return W.#x(t,e,360-this.parentRotation)}#k(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#h||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#h&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#h&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#a)return;this.#a=document.createElement("div"),this.#a.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#a.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",ve,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=Vt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",ne,{passive:!1,signal:r}),window.addEventListener("contextmenu",ve,{signal:r}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#I()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#L(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#l)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#l=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),undo:this.#L.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=W.MIN_SIZE/s,c=W.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,R)=>[u[0]*M+u[2]*R,u[1]*M+u[3]*R],f=this.#k(360-this.rotation),g=(M,R)=>[f[0]*M+f[2]*R,f[1]*M+f[3]*R];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(M,R)=>[0,0],b=(M,R)=>[M,R];break;case"topMiddle":p=(M,R)=>[M/2,0],b=(M,R)=>[M/2,R];break;case"topRight":m=!0,p=(M,R)=>[M,0],b=(M,R)=>[0,R];break;case"middleRight":v=!0,p=(M,R)=>[M,R/2],b=(M,R)=>[0,R/2];break;case"bottomRight":m=!0,p=(M,R)=>[M,R],b=(M,R)=>[0,0];break;case"bottomMiddle":p=(M,R)=>[M/2,R],b=(M,R)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,R)=>[0,R],b=(M,R)=>[M,0];break;case"middleLeft":v=!0,p=(M,R)=>[0,R/2],b=(M,R)=>[M,R/2];break}const y=p(o,h),_=b(o,h);let S=d(..._);const A=W._round(n+S[0]),T=W._round(r+S[1]);let k=1,P=1,B,F;if(e.fromKeyboard)({deltaX:B,deltaY:F}=e);else{const{screenX:M,screenY:R}=e,[U,ht]=this.#c;[B,F]=this.screenToPageTranslation(M-U,R-ht),this.#c[0]=M,this.#c[1]=R}if([B,F]=g(B/s,F/i),m){const M=Math.hypot(o,h);k=P=Math.max(Math.min(Math.hypot(_[0]-y[0]-B,_[1]-y[1]-F)/M,1/o,1/h),l/o,c/h)}else v?k=Math.max(l,Math.min(1,Math.abs(_[0]-y[0]-B)))/o:P=Math.max(c,Math.min(1,Math.abs(_[1]-y[1]-F)))/h;const I=W._round(o*k),O=W._round(h*P);S=d(...b(I,O));const D=A-S[0],z=T-S[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=I,this.height=O,this.x=D,this.y=z,this.setDims(s*I,i*O),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new mi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Me.initialize(W._l10n),this.#s=new Me(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#N();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),In(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new Nn({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),o=(A,T)=>[r[0]*A+r[2]*T,r[1]*A+r[3]*T],[h,l]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=W.MIN_SIZE/h,p=W.MIN_SIZE/l;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const b=W._round(d*n),m=W._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),y=W._round(c+v[0]),_=W._round(u+v[1]),S=o(b/2,m/2);this.x=y-S[0],this.y=_-S[1],this.width=b,this.height=m,this.setDims(h*b,l*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Vt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#V(t);return}this.#G(t)}get isSelected(){return this._uiManager.isSelected(this)}#G(t){const{isMac:e}=Vt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#V(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=l=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#G(l),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=l;if(d!==this.#r){ne(l);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#v);this.#_=c,this.#v=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",ne,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#n&&(this.#S||l.isPrimary)&&o(l),ne(l)},r));const h=l=>{if(!this.#r||this.#r===l.pointerId){o(l);return}ne(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,l=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+l+o,r-d-c-g+h,u+l+f+o,r-d-c+h];case 90:return[u+c+o,r-d+l+h,u+c+g+o,r-d+l+f+h];case 180:return[u-l-f+o,r-d+c+h,u-l+o,r-d+c+g+h];case 270:return[u-c-g+o,r-d-l-f+h,u-c+o,r-d-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#N(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#N()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){at("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[o,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#a.classList.remove("hidden"),In(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=this.#j.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#W.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",W._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)this.#a.append(this.#a.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#a.firstChild.before(this.#a.lastChild);let r=0;for(const o of e){const l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",W._l10nResizer[l])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){W._resizerKeyboardManager.exec(this,t)}#j(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&this.#B()}#W(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#a?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#h=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},W._telemetryTimeout),this.#w.set(s,i);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class af extends W{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Kh=3285377520,ae=4294901760,Pe=65535;class Jh{constructor(t){this.h1=t?t&4294967295:Kh,this.h2=t?t&4294967295:Kh}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,b=t.length;p<b;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let o=0,h=0,l=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Pe,g=d&Pe;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&ae|o*f&Pe,o=o<<15|o>>>17,o=o*d&ae|o*g&Pe,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*u&ae|h*f&Pe,h=h<<15|h>>>17,h=h*d&ae|h*g&Pe,c^=h,c=c<<13|c>>>19,c=c*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&ae|o*f&Pe,o=o<<15|o>>>17,o=o*d&ae|o*g&Pe,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ae|t*36045&Pe,e=e*4283543511&ae|((e<<16|t>>>16)*2950163797&ae)>>>16,t^=e>>>1,t=t*444984403&ae|t*60499&Pe,e=e*3301882366&ae|((e<<16|t>>>16)*3120437893&ae)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const co=Object.freeze({map:null,hash:"",transfer:void 0});class uo{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof W)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#s.set(t,e);i&&this.#i(),e instanceof W&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?to(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Zh(this)}get serializable(){if(this.#s.size===0)return co;const t=new Map,e=new Jh,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof W?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:co}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof W))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof W)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Zh extends uo{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){at("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return Z(this,"modifiedIds",{ids:new Set,hash:""})}}class hf{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(St(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#t.add(s),e?.(t)}catch{K(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}at("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw K(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return Z(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Rt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),Z(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(St(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Z(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,S){return _.charCodeAt(S)<<24|_.charCodeAt(S+1)<<16|_.charCodeAt(S+2)<<8|_.charCodeAt(S+3)&255}function i(_,S,A,T){const k=_.substring(0,S),P=_.substring(S+A);return k+T+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,S){if(++l>30){K("Load test font never loaded."),S();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(c.bind(null,_,S))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let b=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)b=b-p+s(u,n)|0;n<u.length&&(b=b-p+s(u+"XXX",n)|0),d=i(d,g,4,Ud(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=_,y.append(S)}this._document.body.append(y),c(u,()=>{y.remove(),e.complete()})}}class lf{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Zd(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){K(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const jn={DATA:1,ERROR:2},Ct={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Qh(){}function qt(a){if(a instanceof Je||a instanceof Qr||a instanceof fi||a instanceof Xh||a instanceof Dn||a instanceof Zr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||at('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new Je(a.message);case"InvalidPDFException":return new Qr(a.message);case"MissingPDFException":return new fi(a.message);case"PasswordException":return new Xh(a.message,a.code);case"UnexpectedResponseException":return new Dn(a.message,a.status);case"UnknownErrorException":return new Zr(a.message,a.details)}return new Zr(a.message,a.toString())}class vi{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===jn.DATA)i.resolve(t.data);else if(t.callback===jn.ERROR)i.reject(qt(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:jn.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:jn.ERROR,callbackId:t.callbackId,reason:qt(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:Ct.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{St(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:Ct.CANCEL,streamId:n,reason:qt(l)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(l,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ct.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ct.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){St(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ct.ERROR,streamId:e,reason:qt(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.START_COMPLETE,streamId:e,reason:qt(l)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],o=this.streamSinks[e];switch(t.stream){case Ct.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(qt(t.reason));break;case Ct.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(qt(t.reason));break;case Ct.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||Qh).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,reason:qt(l)})});break;case Ct.ENQUEUE:if(St(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Ct.CLOSE:if(St(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case Ct.ERROR:St(r,"error should have stream controller"),r.controller.error(qt(t.reason)),this.#r(r,e);break;case Ct.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(qt(t.reason)),this.#r(r,e);break;case Ct.CANCEL:if(!o)break;const h=qt(t.reason);Promise.try(o.onCancel||Qh,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.CANCEL_COMPLETE,streamId:e,reason:qt(l)})}),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class tl{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){at("Abstract method `_createCanvas` called.")}}class cf extends tl{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class el{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){at("Abstract method `_fetch` called.")}}class sl extends el{async _fetch(t){const e=await Ln(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):Rn(e)}}class il{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class uf extends il{#t;#e;#s;#i;#r;#n;#h=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#l(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(Ge,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Ge,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const h=t[0],l=new Array(256);for(let u=0;u<256;u++)l[u]=h[u]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/255;return[n.join(","),r.join(","),o.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Fn(e)?K('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#a.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#a.get(r),e)return this.#a.set(t,e),e;const o=`g_${this.#i}_transfer_map_${this.#h++}`,h=this.#u(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#p(s,i,n,l),h}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=G.makeHexColor(...r);const o=this.#_(e);if(e=G.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(l,l,l,u),this.#o(u);const d=(f,g)=>{const p=r[f]/255,b=o[f]/255,m=new Array(g+1);for(let v=0;v<=g;v++)m[v]=p+v/g*(b-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#a.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#b(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#b(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#c.get(t);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(t,o)),!e||!s))return o.url;const[h,l]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#l.style.color="";const g=(m,v,y)=>{const _=new Array(256),S=(u-c)/y,A=m/255,T=(v-m)/(255*y);let k=0;for(let P=0;P<=y;P++){const B=Math.round(c+P*S),F=A+P*T;for(let I=k;I<=B;I++)_[I]=F;k=B+1}for(let P=k;P<256;P++)_[P]=_[k-1];return _.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,b=o.filter=this.#g(p);return this.#o(b),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),b),o.url=this.#u(p),o.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#h=0)}#f(t){const e=this.#r.createElementNS(Ge,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#o(t){const e=this.#r.createElementNS(Ge,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#r.createElementNS(Ge,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(Ge,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(Ge,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#b(t,e){const s=this.#r.createElementNS(Ge,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#l.style.color=t,oo(getComputedStyle(this.#l).getPropertyValue("color"))}}class nl{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){at("Abstract method `_fetch` called.")}}class rl extends nl{async _fetch(t){const e=await Ln(t,"arraybuffer");return new Uint8Array(e)}}Rt&&K("Please use the `legacy` build in Node.js environments.");async function ol(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class df extends il{}class ff extends tl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:mt&&mt.tagName.toUpperCase()==="SCRIPT"&&mt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class gf extends el{async _fetch(t){return ol(t)}}class pf extends nl{async _fetch(t){return ol(t)}}const Ft={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function fo(a,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),a.clip(i)}class go{getPattern(){at("Abstract method `getPattern` called.")}}class mf extends go{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Ft.STROKE||i===Ft.FILL){const r=e.current.getClippedPathBoundingBox(i,ct(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=G.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),fo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else fo(t,this._bbox),n=this._createGradient(t);return n}}function po(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,u=a.width*4;let d;h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),h[s+1]>h[i+1]&&(d=s,s=i,i=d,d=r,r=o,o=d),h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,b=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,v=(h[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const y=l[n],_=l[n+1],S=l[n+2],A=l[r],T=l[r+1],k=l[r+2],P=l[o],B=l[o+1],F=l[o+2],I=Math.round(g),O=Math.round(v);let D,z,M,R,U,ht,dt,E;for(let H=I;H<=O;H++){if(H<b){const N=H<g?0:(g-H)/(g-b);D=f-(f-p)*N,z=y-(y-A)*N,M=_-(_-T)*N,R=S-(S-k)*N}else{let N;H>v?N=1:b===v?N=0:N=(b-H)/(b-v),D=p-(p-m)*N,z=A-(A-P)*N,M=T-(T-B)*N,R=k-(k-F)*N}let V;H<g?V=0:H>v?V=1:V=(g-H)/(g-v),U=f-(f-m)*V,ht=y-(y-P)*V,dt=_-(_-B)*V,E=S-(S-F)*V;const Q=Math.round(Math.min(D,U)),kt=Math.round(Math.max(D,U));let rt=u*H+Q*4;for(let N=Q;N<=kt;N++)V=(D-N)/(D-U),V<0?V=0:V>1&&(V=1),c[rt++]=z-(z-ht)*V|0,c[rt++]=M-(M-dt)*V|0,c[rt++]=R-(R-E)*V|0,c[rt++]=255}}function bf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let u=0;u<l;u++,c++)po(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),po(a,e,s[c+o+1],s[c+1],s[c+o],i[c+o+1],i[c+1],i[c+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)po(a,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class vf extends go{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),y=v.context,_=y.createImageData(u,d);if(e){const A=_.data;for(let T=0,k=A.length;T<k;T+=4)A[T]=e[0],A[T+1]=e[1],A[T+2]=e[2],A[T+3]=255}for(const A of this._figures)bf(_,A,p);return y.putImageData(_,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){fo(t,this._bbox);let n;if(i===Ft.SHADING)n=G.singularValueDecompose2dScale(ct(t));else if(n=G.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=G.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Ft.SHADING?null:this._background,e.cachedCanvases);return i!==Ft.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class yf extends go{getPattern(){return"hotpink"}}function _f(a){switch(a[0]){case"RadialAxial":return new mf(a);case"Mesh":return new vf(a);case"Dummy":return new yf}throw new Error(`Unknown IR type: ${a[0]}`)}const al={COLORED:1,UNCOLORED:2};class mo{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),On("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=G.singularValueDecompose2dScale(this.matrix),m=G.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],y=b[1]*m[1];let _=g,S=p,A=!1,T=!1;const k=Math.ceil(h*v),P=Math.ceil(l*y),B=Math.ceil(g*v),F=Math.ceil(p*y);k>=B?_=h:A=!0,P>=F?S=l:T=!0;const I=this.getSizeAndScale(_,this.ctx.canvas.width,v),O=this.getSizeAndScale(S,this.ctx.canvas.height,y),D=t.cachedCanvases.getCanvas("pattern",I.size,O.size),z=D.context,M=o.createCanvasGraphics(z);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),z.translate(-I.scale*c,-O.scale*u),M.transform(I.scale,0,0,O.scale,0,0),z.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=ct(M.ctx),M.executeOperatorList(s),M.endDrawing(),z.restore(),A||T){const R=D.canvas;A&&(_=h),T&&(S=l);const U=this.getSizeAndScale(_,this.ctx.canvas.width,v),ht=this.getSizeAndScale(S,this.ctx.canvas.height,y),dt=U.size,E=ht.size,H=t.cachedCanvases.getCanvas("pattern-workaround",dt,E),V=H.context,Q=A?Math.floor(g/h):0,kt=T?Math.floor(p/l):0;for(let rt=0;rt<=Q;rt++)for(let N=0;N<=kt;N++)V.drawImage(R,dt*rt,E*N,dt,E,0,0,dt,E);return{canvas:H.canvas,scaleX:U.scale,scaleY:ht.scale,offsetX:c,offsetY:u}}return{canvas:D.canvas,scaleX:I.scale,scaleY:O.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(mo.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(ct(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case al.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case al.UNCOLORED:const o=G.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new Xd(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Ft.SHADING&&(n=G.transform(n,e.baseTransform),this.matrix&&(n=G.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function wf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Vt.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],c=s>>3,u=s&7,d=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const b=t+c;t<b;t++){const m=t<d?a[t]:255;e[f++]=m&128?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(u===0)continue;const p=t<d?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?l:h}return{srcPos:t,destPos:f}}const hl=16,ll=100,xf=15,cl=10,ul=1e3,Kt=16;function Sf(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class Cf{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Bn(a,t,e,s,i,n,r,o,h,l){const[c,u,d,f,g,p]=ct(a);if(u===0&&d===0){const v=r*c+g,y=Math.round(v),_=o*f+p,S=Math.round(_),A=(r+h)*c+g,T=Math.abs(Math.round(A)-y)||1,k=(o+l)*f+p,P=Math.abs(Math.round(k)-S)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),y,S),a.drawImage(t,e,s,i,n,0,0,T,P),a.setTransform(c,u,d,f,g,p),[T,P]}if(c===0&&f===0){const v=o*d+g,y=Math.round(v),_=r*u+p,S=Math.round(_),A=(o+l)*d+g,T=Math.abs(Math.round(A)-y)||1,k=(r+h)*u+p,P=Math.abs(Math.round(k)-S)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,y,S),a.drawImage(t,e,s,i,n,0,0,P,T),a.setTransform(c,u,d,f,g,p),[P,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*h,m*l]}function Af(a){const{width:t,height:e}=a;if(t>ul||e>ul)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of a.data){let v=128;for(;v>0;)u[d++]=m&v?0:255,v>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[h]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[h]=2,++f),o=1;o<e;o++){d=o*c,l=o*n,u[d-c]!==u[d]&&(r[l]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(h=1;h<t;h++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[l+h]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[l+h]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),l=o*n,u[d]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[l+h]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[l+h]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(o=0;f&&o<=e;o++){let m=o*n;const v=m+t;for(;m<v&&!r[m];)m++;if(m===v)continue;p.moveTo(m%n,o);const y=m;let _=r[m];do{const S=g[_];do m+=S;while(!r[m]);const A=r[m];A!==5&&A!==10?(_=A,r[m]=0):(_=A&51*_>>4,r[m]&=_>>2|_<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(y!==m);--o}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class dl{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Wh,this.textMatrixScale=1,this.fontMatrix=Kr,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Lt.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=G.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=G.applyTransform(e,t),i=G.applyTransform(e.slice(2),t),n=G.applyTransform([e[0],e[3]],t),r=G.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){G.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,c){const u=G.bezierBoundingBox(e,s,i,n,r,o,h,l,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Ft.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Ft.STROKE){e||at("Stroke bounding box must include transform.");const i=G.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=G.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Ft.FILL,e=null){return G.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function fl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Kt,n=(e-i)/Kt,r=i===0?n:n+1,o=a.createImageData(s,Kt);let h=0,l;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===kn.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,y=s+7>>3,_=4294967295,S=Vt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?Kt:i,l=0,f=0;f<g;f++){const A=b-h;let T=0;const k=A>y?s:A*8-7,P=k&-8;let B=0,F=0;for(;T<P;T+=8)F=c[h++],m[l++]=F&128?_:S,m[l++]=F&64?_:S,m[l++]=F&32?_:S,m[l++]=F&16?_:S,m[l++]=F&8?_:S,m[l++]=F&4?_:S,m[l++]=F&2?_:S,m[l++]=F&1?_:S;for(;T<k;T++)B===0&&(F=c[h++],B=128),m[l++]=F&B?_:S,B>>=1}for(;l<v;)m[l++]=0;a.putImageData(o,0,d*Kt)}}else if(t.kind===kn.RGBA_32BPP){for(f=0,p=s*Kt*4,d=0;d<n;d++)u.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Kt;d<r&&(p=s*i*4,u.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===kn.RGB_24BPP)for(g=Kt,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),l=0,f=p;f--;)u[l++]=c[h++],u[l++]=c[h++],u[l++]=c[h++],u[l++]=255;a.putImageData(o,0,d*Kt)}else throw new Error(`bad image kind: ${t.kind}`)}function gl(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Kt,n=(e-i)/Kt,r=i===0?n:n+1,o=a.createImageData(s,Kt);let h=0;const l=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?Kt:i;({srcPos:h}=wf({src:l,srcPos:h,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*Kt)}}function yi(a,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)a[s]!==void 0&&(t[s]=a[s]);a.setLineDash!==void 0&&(t.setLineDash(a.getLineDash()),t.lineDashOffset=a.lineDashOffset)}function Hn(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!Rt){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function pl(a,t){if(t)return!0;const e=G.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*js.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Tf=["butt","round","square"],Ef=["miter","round","bevel"],kf={},ml={};class Bs{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){this.ctx=t,this.current=new dl(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedCanvases=new Cf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...ct(this.compositeCtx))}this.ctx.save(),Hn(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=ct(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>cl&&typeof s=="function",c=l?Date.now()+xf:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(g=r[o],g!==be.dependency)this[g].apply(this,n[o]);else for(const p of n[o]){const b=p.startsWith("g_")?d:f;if(!b.has(p))return b.get(p,s),o}if(o++,o===h)return o;if(l&&++u>cl){if(Date.now()>c)return s(),o;u=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",c,u;for(;n>2&&o>1||r>2&&h>1;){let d=o,f=h;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/d),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,o,h,0,0,d,f),t=c.canvas,o=d,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=ct(e);let h,l,c,u;if((t.bitmap||t.data)&&t.count>1){const k=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(k),h||(h=new Map,this._cachedBitmapsMap.set(k,h));const P=h.get(l);if(P&&!r){const B=Math.round(Math.min(o[0],o[2])+o[4]),F=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:B,offsetY:F}}c=P}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),gl(u.context,t));let d=G.transform(o,[1/s,0,0,-1/i,0,0]);d=G.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=G.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,v),_=y.context,S=f,A=g;_.translate(-S,-A),_.transform(...d),c||(c=this._scaleImage(u.canvas,ke(_)),c=c.img,h&&r&&h.set(l,c)),_.imageSmoothingEnabled=pl(ct(_),t.interpolate),Bn(_,c,0,0,c.width,c.height,0,0,s,i),_.globalCompositeOperation="source-in";const T=G.transform(ke(_),[1,0,0,1,-S,-A]);return _.fillStyle=r?n.getPattern(e,this,T,Ft.FILL):n,_.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Tf[t]}setLineJoin(t){this.ctx.lineJoin=Ef[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...ct(this.suspendedCtx)),yi(this.suspendedCtx,n),Sf(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),yi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,u){let d=t.canvas,f=h-c,g=l-u;if(r){const b=G.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),v=m.context;v.drawImage(d,-f,-g),v.globalCompositeOperation="destination-atop",v.fillStyle=b,v.fillRect(0,0,s,i),v.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=b,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&o?e.filter=this.filterFactory.addAlphaFilter(o):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(o));const p=new Path2D;p.rect(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(yi(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),yi(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const c=ct(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case be.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,y=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,y):(i.lineTo(v,o),i.lineTo(v,y),i.lineTo(r,y)),u||n.updateRectMinMax(c,[r,o,v,y]),i.closePath();break;case be.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case be.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case be.curveTo:h=r,l=o,r=e[g+4],o=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case be.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,h,l,r,o,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],o=e[g+3],g+=4;break;case be.curveTo3:h=r,l=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],r,o,r,o,d),g+=4;break;case be.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,o)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,ke(e),Ft.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,ke(e),Ft.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=kf}eoClip(){this.pendingClip=ml}beginText(){this.current.textMatrix=Wh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:l}of t)s.addPath(l,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Kr,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&K("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<hl?l=hl:e>ll&&(l=ll),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=l&Lt.FILL_STROKE_MASK,d=!!(l&Lt.ADD_TO_PATH_FLAG),f=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let p;if((h.disableFontFace||d||f||g)&&(p=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Lt.FILL||u===Lt.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===Lt.STROKE||u===Lt.FILL_STROKE)if(n){const b=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,b,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Lt.FILL||u===Lt.FILL_STROKE)&&r.fillText(t,e,s),(u===Lt.STROKE||u===Lt.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:ct(r),x:e,y:s,fontSize:c,path:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return Z(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,c=e.textHScale*l,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],b=e.textRenderingMode===Lt.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(c,-1):n.scale(c,1);let m,v;if(e.patternFill){n.save();const T=e.fillColor.getPattern(n,this,ke(n),Ft.FILL);m=ct(n),n.restore(),n.fillStyle=T}if(e.patternStroke){n.save();const T=e.strokeColor.getPattern(n,this,ke(n),Ft.STROKE);v=ct(n),n.restore(),n.strokeStyle=T}let y=e.lineWidth;const _=e.textMatrixScale;if(_===0||y===0){const T=e.textRenderingMode&Lt.FILL_STROKE_MASK;(T===Lt.STROKE||T===Lt.FILL_STROKE)&&(y=this.getSinglePixelWidth())}else y/=_;if(r!==1&&(n.scale(r,r),y/=r),n.lineWidth=y,s.isInvalidPDFjsFont){const T=[];let k=0;for(const P of t)T.push(P.unicode),k+=P.width;n.fillText(T.join(""),0,0),e.x+=k*p*c,n.restore(),this.compose();return}let S=0,A;for(A=0;A<u;++A){const T=t[A];if(typeof T=="number"){S+=f*T*i/1e3;continue}let k=!1;const P=(T.isSpace?h:0)+o,B=T.fontChar,F=T.accent;let I,O,D=T.width;if(d){const M=T.vmetric||g,R=-(T.vmetric?M[1]:D*.5)*p,U=M[2]*p;D=M?-M[0]:D,I=R/r,O=(S+U)/r}else I=S/r,O=0;if(s.remeasure&&D>0){const M=n.measureText(B).width*1e3/i*r;if(D<M&&this.isFontSubpixelAAEnabled){const R=D/M;k=!0,n.save(),n.scale(R,1),I/=R}else D!==M&&(I+=(D-M)/2e3*i/r)}if(this.contentVisible&&(T.isInFont||s.missingFile)){if(b&&!F)n.fillText(B,I,O);else if(this.paintChar(B,I,O,m,v),F){const M=I+i*F.offset.x/r,R=O-i*F.offset.y/r;this.paintChar(F.fontChar,M,R,m,v)}}const z=d?D*p-P*l:D*p+P*l;S+=z,k&&n.restore()}d?e.y-=S:e.x+=S*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||Kr,d=t.length,f=s.textRenderingMode===Lt.INVISIBLE;let g,p,b,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=o*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const v=(p.isSpace?l:0)+h,y=i.charProcOperatorList[p.operatorListId];if(!y){K(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(y),this.restore()),b=G.applyTransform([p.width,0],u)[0]*n+v,e.translate(b,0),s.x+=b*c}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||ct(this.ctx),n={createCanvasGraphics:r=>new Bs(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new mo(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=G.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=G.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=_f(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,ke(e),Ft.SHADING);const i=ke(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,c]=G.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,c-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){at("Should not call beginInlineImage")}beginImageData(){at("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=ct(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(ct(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||On("TODO: Support non-isolated groups."),t.knockout&&K("Knockout groups not supported.");const s=ct(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=G.getAxialAlignedBoundingBox(t.bbox,ct(e));const n=[0,0,e.canvas.width,e.canvas.height];i=G.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,l),d=u.context;d.translate(-r,-o),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,o),e.save()),yi(e,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=ct(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=G.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),Hn(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=G.singularValueDecompose2dScale(ct(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(o*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),Hn(this.ctx)}else Hn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new dl(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=Af(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=ct(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let c=0,u=r.length;c<u;c+=2){const d=G.transform(h,[e,s,i,n,r[c],r[c+1]]),[f,g]=G.applyTransform([0,0],d);o.drawImage(l.canvas,f,g)}o.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:o,height:h,transform:l}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=c.context;u.save();const d=this.getObject(r,n);gl(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,ke(e),Ft.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),Bn(e,c.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){K("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){K("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,c=i.length;l<c;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Rt){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;fl(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,ke(i));i.imageSmoothingEnabled=pl(ct(i),t.interpolate),Bn(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;fl(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),Bn(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===ml?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=ct(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,u=l*t;r=c<1?1/c:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const u=t*h;r=c>u?c/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const a in be)Bs.prototype[a]!==void 0&&(Bs.prototype[be[a]]=Bs.prototype[a]);class _i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class Mf{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return to(this.#t)}has(t){return this.#t.has(t)}}const Hs=Symbol("INTERNAL");class Pf{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&ie.DISPLAY),this.#e=!!(t&ie.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==Hs&&at("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class Of{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=ie.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new Pf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(Hs,!1);for(const s of t.on)this.#e.get(s)._setVisible(Hs,!0);for(const s of t.off)this.#e.get(s)._setVisible(Hs,!1);this.#s=this.getHash()}}#r(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return K(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return On("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(K(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return K(`Unknown optional content policy ${t.policy}.`),!0}return K(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){K(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(Hs,!1,!0);i._setVisible(Hs,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?to(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Jh;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class Df{constructor(t,{disableRange:e=!1,disableStream:s=!1}){St(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:o}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=o,n?.length>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});St(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){St(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Rf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Lf(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Rf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=ro(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Lf{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Ff(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=Rn(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,b,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[b,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[b,m]=u[p];m=o(m),b&&(m=unescape(m),p===0&&(m=h(m))),g.push(m)}return g.join("")}function o(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function h(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,b){return String.fromCharCode(parseInt(b,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function bl(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function zn(a){try{return new URL(a).origin}catch{}return null}function vl({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function yl(a){const t=a.get("Content-Disposition");if(t){let e=Ff(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(ro(e))return e}return null}function Gn(a,t){return a===404||a===0&&t.startsWith("file:")?new fi('Missing PDF "'+t+'".'):new Dn(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function _l(a){return a===200||a===206}function wl(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function xl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(K(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class Sl{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=bl(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return St(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new If(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Nf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class If{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,wl(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=zn(n.url),!_l(n.status))throw Gn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=vl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=yl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Je("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:xl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Nf{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,wl(n,this._withCredentials,this._abortController)).then(o=>{const h=zn(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!_l(o.status))throw Gn(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:xl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const bo=200,vo=206;function jf(a){const t=a.response;return typeof t!="string"?t:Rn(t).buffer}class Bf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=bl(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=vo):i.expectedStatus=bo,e.responseType="arraybuffer",St(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||bo;if(!(n===bo&&s.expectedStatus===vo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=jf(i);if(n===vo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(K('Missing or invalid "Content-Range" header.'),s.onError(0))}else o?s.onDone({begin:0,chunk:o}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Hf{constructor(t){this._source=t,this._manager=new Bf(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return St(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new zf(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Gf(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class zf{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=zn(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=vl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=yl(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Gn(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Gf{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=zn(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=Gn(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Vf=/^[a-z][a-z0-9\-+.]+:/i;function Wf(a){if(Vf.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class Xf{constructor(t){this.source=t,this.url=Wf(t.url),St(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return St(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Uf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Yf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Uf{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new fi(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new Je("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Yf{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const $f=1e5,Jt=30,qf=.8;class Wt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#h=0;#a=0;#c=null;#l=null;#d=0;#u=0;#f=Object.create(null);#o=[];#g=null;#m=[];#p=new WeakMap;#b=null;static#_=new Map;static#v=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;this.#b=[1,0,0,-1,-r,o+n],this.#a=i,this.#h=n,Wt.#O(),ms(e,s),this.#t.promise.finally(()=>{Wt.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Vt.platform;return Z(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Wt.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,ms(this.#l,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Wt.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new Je("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#o}#E(t){if(this.#s)return;this.#n.ctx??=Wt.#k(this.#r);const e=this.#m,s=this.#o;for(const i of t){if(e.length>$f){K("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#M(i)}}#M(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=G.transform(this.#b,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Wt.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*Wt.#L(o,this.#r);let c,u;n===0?(c=i[4],u=i[5]-l):(c=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*u/this.#h).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Wt.#S*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);p!==b&&Math.max(p,b)/Math.min(p,b)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Wt.#S>1&&(r=`scale(${1/Wt.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:h,fontSize:l}=s;Wt.#T(i,l*this.#u,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#v.values())t.remove();this.#v.clear()}}static#k(t=null){let e=this.#v.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#v.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#S=t.getBoundingClientRect().height,t.remove()}static#L(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=Jt,this.#T(i,Jt,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+o);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,Jt,Jt),i.strokeText("g",0,0);let h=i.getImageData(0,0,Jt,Jt).data;o=0;for(let c=h.length-1-3;c>=0;c-=4)if(h[c]>0){o=Math.ceil(c/4/Jt);break}i.clearRect(0,0,Jt,Jt),i.strokeText("A",0,Jt),h=i.getImageData(0,0,Jt,Jt).data,r=0;for(let c=0,u=h.length;c<u;c+=4)if(h[c]>0){r=Jt-Math.floor(c/4/Jt);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):qf;return this.#_.set(t,l),l}}class wi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(wi.shouldBuildText(o))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Kf=65536,Jf=100,Zf=5e3,Qf=Rt?ff:cf,tg=Rt?gf:sl,eg=Rt?df:uf,sg=Rt?pf:rl;function ig(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new yo,{docId:e}=t,s=a.url?ng(a.url):null,i=a.data?rg(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof Al?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Kf;let c=a.worker instanceof zs?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Fn(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||tg,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||sg,v=a.stopAtErrors!==!0,y=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,_=a.isEvalSupported!==!1,S=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Rt,A=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Rt&&(Vt.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,k=typeof a.disableFontFace=="boolean"?a.disableFontFace:Rt,P=a.fontExtraProperties===!0,B=a.enableXfa===!0,F=a.ownerDocument||globalThis.document,I=a.disableRange===!0,O=a.disableStream===!0,D=a.disableAutoFetch===!0,z=a.pdfBug===!0,M=a.CanvasFactory||Qf,R=a.FilterFactory||eg,U=a.enableHWA===!0,ht=h?h.length:a.length??NaN,dt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Rt&&!k,E=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===sl&&m===rl&&f&&b&&pi(f,document.baseURI)&&pi(b,document.baseURI),H=null;zd(u);const V={canvasFactory:new M({ownerDocument:F,enableHWA:U}),filterFactory:new R({docId:e,ownerDocument:F}),cMapReaderFactory:E?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:E?null:new m({baseUrl:b})};if(!c){const rt={verbosity:u,port:_i.workerPort};c=rt.port?zs.fromPort(rt):new zs(rt),t._worker=c}const Q={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:D,rangeChunkSize:l,length:ht,docBaseUrl:d,enableXfa:B,evaluatorOptions:{maxImageSize:y,disableFontFace:k,ignoreErrors:v,isEvalSupported:_,isOffscreenCanvasSupported:S,isImageDecoderSupported:A,canvasMaxAreaInBytes:T,fontExtraProperties:P,useSystemFonts:dt,cMapUrl:E?f:null,standardFontDataUrl:E?b:null}},kt={disableFontFace:k,fontExtraProperties:P,ownerDocument:F,pdfBug:z,styleElement:H,loadingParams:{disableAutoFetch:D,enableXfa:B}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const rt=c.messageHandler.sendWithPromise("GetDocRequest",Q,i?[i.buffer]:null);let N;if(h)N=new Df(h,{disableRange:I,disableStream:O});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let ft;if(Rt)if(pi(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");ft=Sl}else ft=Xf;else ft=pi(s)?Sl:Hf;N=new ft({url:s,length:ht,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:I,disableStream:O})}return rt.then(ft=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const It=new vi(e,ft,c.port),Zt=new lg(It,t,N,kt,V);t._transport=Zt,It.send("Ready",null)})}).catch(t._capability.reject),t}function ng(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Rt&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function rg(a){if(Rt&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return Rn(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(a?.length))return new Uint8Array(a);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function Cl(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class yo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${yo.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class Al{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){at("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class og{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 Z(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class ag{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new $h:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new Tl,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new gi({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Z(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=qe.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),o||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const b=!!(f&ie.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=_=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(v.capability.reject(_),this._abortOperatorList({intentState:p,reason:_ instanceof Error?_:new Error(_)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Gs({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(p.renderTasks||=new Set).add(v);const y=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([_,S])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(S.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:_,optionalContentConfig:S}),v.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=qe.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>wi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new $h),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},Zf),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:u,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),c())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.opListReadCapability.reject(u);else throw u}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof no){let i=Jf;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new Je(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class hg{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){K("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const ut=class ut{constructor({name:t=null,port:e=null,verbosity:s=Gd()}={}){Xs(this,Vs);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(ye(ut,ws)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(ye(ut,ws)||Ai(ut,ws,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new vi("main","worker",t),this._messageHandler.on("ready",function(){}),Un(this,Vs,$n).call(this)}_initialize(){if(ye(ut,_s)||ye(ut,Ws,qn)){this._setupFakeWorker();return}let{workerSrc:t}=ut;try{ut._isSameOrigin(window.location.href,t)||(t=ut._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vi("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,Un(this,Vs,$n).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{On("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(ut,_s)||(K("Setting up fake worker."),Ai(ut,_s,!0)),ut._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new hg;this._port=e;const s=`fake${Zl(ut,Xn)._++}`,i=new vi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vi(s,s+"_worker",e),Un(this,Vs,$n).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,ye(ut,ws)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=ye(this,ws)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new ut(t)}static get workerSrc(){if(_i.workerSrc)return _i.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Z(this,"_setupFakeWorkerGlobal",(async()=>ye(this,Ws,qn)?ye(this,Ws,qn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Xn=new WeakMap,_s=new WeakMap,ws=new WeakMap,Vs=new WeakSet,$n=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Ws=new WeakSet,qn=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Xs(ut,Ws),Xs(ut,Xn,0),Xs(ut,_s,!1),Xs(ut,ws),Rt&&(Ai(ut,_s,!0),_i.workerSrc||="./pdf.worker.mjs"),ut._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},ut._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let zs=ut;class lg{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new Tl,this.fontLoader=new hf({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return Z(this,"annotationStorage",new uo)}getRenderingIntent(t,e=qe.ENABLE,s=null,i=!1,n=!1){let r=ie.DISPLAY,o=co;switch(t){case"any":r=ie.ANY;break;case"display":break;case"print":r=ie.PRINT;break;default:K(`getRenderingIntent - invalid intent: ${t}`)}const h=r&ie.PRINT&&s instanceof Zh?s:this.annotationStorage;switch(e){case qe.DISABLE:r+=ie.ANNOTATIONS_DISABLE;break;case qe.ENABLE:break;case qe.ENABLE_FORMS:r+=ie.ANNOTATIONS_FORMS;break;case qe.ENABLE_STORAGE:r+=ie.ANNOTATIONS_STORAGE,o=h.serializable;break;default:K(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=ie.IS_EDITING),n&&(r+=ie.OPLIST);const{ids:l,hash:c}=h.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Wt.cleanup(),this._networkStream?.cancelAllRequests(new Je("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{St(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}St(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=o=>{e.onProgress?.({loaded:o.loaded,total:o.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{St(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:o}){if(o){i.close();return}St(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new og(s,this))}),t.on("DocException",s=>{e._capability.reject(qt(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw qt(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:o,pdfBug:h}=this._params;if("error"in n){const d=n.error;K(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const l=h&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new lf(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:l});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;St(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const o=this.#e.get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":o.objs.resolve(s,r),r?.dataLen>Nd&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&K("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#i.set(n.refStr,t);const r=new ag(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return Cl(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#n("GetFieldObjects")}hasJSActions(){return this.#n("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#n("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#n("GetOptionalContentConfig").then(e=>new Of(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new Mf(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Wt.cleanup()}}cachedPageNumber(t){if(!Cl(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const xi=Symbol("INITIAL_DATA");class Tl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:xi}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===xi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==xi}delete(t){const e=this.#t[t];return!e||e.data===xi?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==xi&&(yield[t,e])}}}class cg{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class Gs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new cg(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Gs.#e.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Gs.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new Bs(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),Gs.#e.delete(this._canvas),this.callback(t||new no(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Gs.#e.delete(this._canvas),this.callback())))}}const ug="4.10.38",dg="f9bea397f";function El(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function Si(a){return Math.max(0,Math.min(255,255*a))}class kl{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=Si(t),[t,t,t]}static G_HTML([t]){const e=El(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Si)}static RGB_HTML(t){return`#${t.map(El).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Si(1-Math.min(1,t+i)),Si(1-Math.min(1,s+i)),Si(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,o=Math.min(i,n,r);return["CMYK",i,n,r,o]}}class fg{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){at("Abstract method `_createSVG` called.")}}class _o extends fg{_createSVG(t){return document.createElementNS(Ge,t)}}class Ml{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=u}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&wi.shouldBuildText(i.name)&&l.push(u)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);l.push(m),f.append(m);continue}const b=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,b]);else if(g.value){const m=document.createTextNode(g.value);o&&wi.shouldBuildText(p)&&l.push(m),b.append(m)}}for(const u of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Ci=1e3,gg=9,bs=new WeakSet;function Qe(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class pg{static create(t){switch(t.data.annotationType){case Tt.LINK:return new Pl(t);case Tt.TEXT:return new mg(t);case Tt.WIDGET:switch(t.data.fieldType){case"Tx":return new bg(t);case"Btn":return t.data.radioButton?new Ol(t):t.data.checkBox?new yg(t):new _g(t);case"Ch":return new wg(t);case"Sig":return new vg(t)}return new vs(t);case Tt.POPUP:return new wo(t);case Tt.FREETEXT:return new Dl(t);case Tt.LINE:return new Sg(t);case Tt.SQUARE:return new Cg(t);case Tt.CIRCLE:return new Ag(t);case Tt.POLYLINE:return new Rl(t);case Tt.CARET:return new Eg(t);case Tt.INK:return new xo(t);case Tt.POLYGON:return new Tg(t);case Tt.HIGHLIGHT:return new Ll(t);case Tt.UNDERLINE:return new kg(t);case Tt.SQUIGGLY:return new Mg(t);case Tt.STRIKEOUT:return new Pg(t);case Tt.STAMP:return new Fl(t);case Tt.FILEATTACHMENT:return new Og(t);default:return new yt(t)}}}class yt{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return yt._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s?.splice(0,4,...t);const{width:l,height:c}=Qe(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof vs||(n.tabIndex=Ci);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof wo){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=Qe(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(p>0||b>0){const v=`calc(${p}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;r.borderRadius=v}else if(this instanceof Ol){const v=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case di.SOLID:r.borderStyle="solid";break;case di.DASHED:r.borderStyle="dashed";break;case di.BEVELED:K("Unimplemented border style: beveled");break;case di.INSET:K("Unimplemented border style: inset");break;case di.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=G.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=G.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(l[0]-d)/c}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/u}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Qe(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=kl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:kl[`${r}_rgb`](o)})};return Z(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const o={detail:{[i]:n},target:t};r(o),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(p=>Math.fround(p));if(t.length===8){const[p,b,m,v]=t.subarray(2,6);if(i===p&&n===b&&e===m&&s===v)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:b}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${p}" stroke-width="${b}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,b=t.length;p<b;p+=8){const m=t[p],v=t[p+1],y=t[p+2],_=t[p+3],S=c.createElement("rect"),A=(y-e)/h,T=(n-v)/l,k=(m-y)/h,P=(v-_)/l;S.setAttribute("x",A),S.setAttribute("y",T),S.setAttribute("width",k),S.setAttribute("height",P),f.append(S),o?.push(`<rect vector-effect="non-scaling-stroke" x="${A}" y="${T}" width="${k}" height="${P}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new wo({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){at("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!bs.has(l)){K(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&bs.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class Pl extends yt{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){K('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,o=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&o.push(d)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const h=this.annotationStorage,l=[];for(const c of o){const{id:u}=c;switch(l.push(u),c.type){case"text":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!bs.has(d)){K(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class mg extends yt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class vs extends yt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Vt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":G.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||gg,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(Jr*i))||1,u=l/c;r=Math.min(i,h(u/Jr))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/Jr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=G.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class bg extends vs{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let o=i.formattedValue||this.data.textContent?.join(`
509
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],o=e[i+2],h=Math.max(n,r,o),l=(n+r+o)/3,c=2*Math.abs(h-l)/255*s;e[i]+=h!==n?(h-n)*c:0,e[i+1]+=h!==r?(h-r)*c:0,e[i+2]+=h!==o?(h-o)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}x(En,"type","Vibrance"),x(En,"defaults",{vibrance:0}),x(En,"uniformLocations",["uVibrance"]),L.setClass(En);var ui={};ui.d=(a,t)=>{for(var e in t)ui.o(t,e)&&!ui.o(a,e)&&Object.defineProperty(a,e,{enumerable:!0,get:t[e]})},ui.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t);var Y=globalThis.pdfjsLib={};ui.d(Y,{AbortException:()=>Je,AnnotationEditorLayer:()=>Ve,AnnotationEditorParamsType:()=>tt,AnnotationEditorType:()=>q,AnnotationEditorUIManager:()=>Ze,AnnotationLayer:()=>Dg,AnnotationMode:()=>qe,ColorPicker:()=>he,DOMSVGFactory:()=>_o,DrawLayer:()=>Ut,FeatureTest:()=>Wt,GlobalWorkerOptions:()=>_i,ImageKind:()=>kn,InvalidPDFException:()=>Qr,MissingPDFException:()=>fi,OPS:()=>be,OutputScale:()=>ao,PDFDataRangeTransport:()=>Al,PDFDateString:()=>qh,PDFWorker:()=>zs,PasswordResponses:()=>Hd,PermissionFlag:()=>Bd,PixelsPerInch:()=>js,RenderingCancelledException:()=>no,TextLayer:()=>Xt,TouchManager:()=>Nn,UnexpectedResponseException:()=>Dn,Util:()=>G,VerbosityLevel:()=>Mn,XfaLayer:()=>Ml,build:()=>dg,createValidAbsoluteUrl:()=>Wd,fetchData:()=>Ln,getDocument:()=>ig,getFilenameFromUrl:()=>Qd,getPdfFilenameFromUrl:()=>tf,getXfaPageViewport:()=>ef,isDataScheme:()=>Fn,isPdfFile:()=>ro,noContextMenu:()=>ve,normalizeUnicode:()=>Kd,setLayerDimensions:()=>ms,shadow:()=>Z,stopEvent:()=>ne,version:()=>ug});const Ft=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Wh=[1,0,0,1,0,0],Kr=[.001,0,0,.001,0,0],Nd=1e7,Jr=1.35,ie={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},qe={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},jd="pdfjs_internal_editor_",q={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},tt={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Bd={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},It={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},kn={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Tt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},di={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Mn={ERRORS:0,WARNINGS:1,INFOS:5},be={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},Hd={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Pn=Mn.WARNINGS;function zd(a){Number.isInteger(a)&&(Pn=a)}function Gd(){return Pn}function On(a){Pn>=Mn.INFOS&&console.log(`Info: ${a}`)}function K(a){Pn>=Mn.WARNINGS&&console.log(`Warning: ${a}`)}function at(a){throw new Error(a)}function St(a,t){a||at(t)}function Vd(a){switch(a?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Wd(a,t=null,e=null){if(!a)return null;try{if(e&&typeof a=="string"&&(e.addDefaultProtocol&&a.startsWith("www.")&&a.match(/\./g)?.length>=2&&(a=`http://${a}`),e.tryConvertEncoding))try{a=qd(a)}catch{}const s=t?new URL(a,t):new URL(a);if(Vd(s))return s}catch{}return null}function Z(a,t,e,s=!1){return Object.defineProperty(a,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const Ke=(function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t})();class Xh extends Ke{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Zr extends Ke{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Qr extends Ke{constructor(t){super(t,"InvalidPDFException")}}class fi extends Ke{constructor(t){super(t,"MissingPDFException")}}class Dn extends Ke{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Xd extends Ke{constructor(t){super(t,"FormatError")}}class Je extends Ke{constructor(t){super(t,"AbortException")}}function Uh(a){(typeof a!="object"||a?.length===void 0)&&at("Invalid argument for bytesToString");const t=a.length,e=8192;if(t<e)return String.fromCharCode.apply(null,a);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=a.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function Rn(a){typeof a!="string"&&at("Invalid argument for stringToBytes");const t=a.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=a.charCodeAt(s)&255;return e}function Ud(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)}function to(a){const t=Object.create(null);for(const[e,s]of a)t[e]=s;return t}function Yd(){const a=new Uint8Array(4);return a[0]=1,new Uint32Array(a.buffer,0,1)[0]===1}function $d(){try{return new Function(""),!0}catch{return!1}}class Wt{static get isLittleEndian(){return Z(this,"isLittleEndian",Yd())}static get isEvalSupported(){return Z(this,"isEvalSupported",$d())}static get isOffscreenCanvasSupported(){return Z(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Z(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?Z(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):Z(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Z(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const eo=Array.from(Array(256).keys(),a=>a.toString(16).padStart(2,"0"));class G{static makeHexColor(t,e,s){return`#${eo[t]}${eo[e]}${eo[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],o=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,l=o+h||1,c=o-h||1;return[Math.sqrt(l),Math.sqrt(c)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static#t(t,e,s,i,n,r,o,h,l,c){if(l<=0||l>=1)return;const u=1-l,d=l*l,f=d*l,g=u*(u*(u*t+3*l*e)+3*d*s)+f*i,p=u*(u*(u*n+3*l*r)+3*d*o)+f*h;c[0]=Math.min(c[0],g),c[1]=Math.min(c[1],p),c[2]=Math.max(c[2],g),c[3]=Math.max(c[3],p)}static#e(t,e,s,i,n,r,o,h,l,c,u,d){if(Math.abs(l)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,o,h,-u/c,d);return}const f=c**2-4*u*l;if(f<0)return;const g=Math.sqrt(f),p=2*l;this.#t(t,e,s,i,n,r,o,h,(-c+g)/p,d),this.#t(t,e,s,i,n,r,o,h,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,o,h,l){return l?(l[0]=Math.min(l[0],t,o),l[1]=Math.min(l[1],e,h),l[2]=Math.max(l[2],t,o),l[3]=Math.max(l[3],e,h)):l=[Math.min(t,o),Math.min(e,h),Math.max(t,o),Math.max(e,h)],this.#e(t,s,n,o,e,i,r,h,3*(-t+3*(s-n)+o),6*(t-2*s+n),3*(s-t),l),this.#e(t,s,n,o,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),l),l}}function qd(a){return decodeURIComponent(escape(a))}let so=null,Yh=null;function Kd(a){return so||(so=/([\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,Yh=new Map([["ſt","ſt"]])),a.replaceAll(so,(t,e,s)=>e?e.normalize("NFKC"):Yh.get(s))}function Jd(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const a=new Uint8Array(32);return crypto.getRandomValues(a),Uh(a)}const io="pdfjs_internal_id_";function Zd(a){return Uint8Array.prototype.toBase64?a.toBase64():btoa(Uh(a))}typeof Promise.try!="function"&&(Promise.try=function(a,...t){return new Promise(e=>{e(a(...t))})});const Ge="http://www.w3.org/2000/svg";class js{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Ln(a,t="text"){if(pi(a,document.baseURI)){const e=await fetch(a);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",a,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class gi{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let c,u,d,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,u=0,d=0,f=1;break;case 90:c=0,u=1,d=1,f=0;break;case 270:c=0,u=-1,d=-1,f=0;break;case 0:c=1,u=0,d=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}o&&(d=-d,f=-f);let g,p,b,m;c===0?(g=Math.abs(l-t[1])*s+n,p=Math.abs(h-t[0])*s+r,b=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(h-t[0])*s+n,p=Math.abs(l-t[1])*s+r,b=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,u*s,d*s,f*s,g-c*s*h-d*s*l,p-u*s*h-f*s*l],this.width=b,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return Z(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new gi({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return G.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=G.applyTransform([t[0],t[1]],this.transform),s=G.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return G.applyInverseTransform([t,e],this.transform)}}class no extends Ke{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Fn(a){const t=a.length;let e=0;for(;e<t&&a[e].trim()==="";)e++;return a.substring(e,e+5).toLowerCase()==="data:"}function ro(a){return typeof a=="string"&&/\.pdf$/i.test(a)}function Qd(a){return[a]=a.split(/[#?]/,1),a.substring(a.lastIndexOf("/")+1)}function tf(a,t="document.pdf"){if(typeof a!="string")return t;if(Fn(a))return K('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(a);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class $h{started=Object.create(null);times=[];time(t){t in this.started&&K(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||K(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
510
+ `);return t.join("")}}function pi(a,t){try{const{protocol:e}=t?new URL(a,t):new URL(a);return e==="http:"||e==="https:"}catch{return!1}}function ve(a){a.preventDefault()}function ne(a){a.preventDefault(),a.stopPropagation()}class qh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const l=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,l==="-"?(r+=c,o+=u):l==="+"&&(r-=c,o-=u),new Date(Date.UTC(s,i,n,r,o,h))}}function ef(a,{scale:t=1,rotation:e=0}){const{width:s,height:i}=a.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new gi({viewBox:n,userUnit:1,scale:t,rotation:e})}function oo(a){if(a.startsWith("#")){const t=parseInt(a.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return a.startsWith("rgb(")?a.slice(4,-1).split(",").map(t=>parseInt(t)):a.startsWith("rgba(")?a.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(K(`Not a valid color format: "${a}"`),[0,0,0])}function sf(a){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of a.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;a.set(e,oo(s))}t.remove()}function ut(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform();return[t,e,s,i,n,r]}function ke(a){const{a:t,b:e,c:s,d:i,e:n,f:r}=a.getTransform().invertSelf();return[t,e,s,i,n,r]}function ms(a,t,e=!1,s=!0){if(t instanceof gi){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=a,o=Wt.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,l=`var(--scale-factor) * ${n}px`,c=o?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,u=o?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&a.setAttribute("data-main-rotation",t.rotation)}class ao{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class mi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,mi.#n||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",ve,{signal:e}),t.addEventListener("pointerdown",mi.#h,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#h(t){t.stopPropagation()}#a(t){this.#s._focusEventsAllowed=!1,ne(t)}#c(t){this.#s._focusEventsAllowed=!0,ne(t)}#l(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#a.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ve,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",mi.#n[t]),this.#l(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#l(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#l(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class nf{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ve,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const o=n.x+(e?n.width:0);if(r>s){i=o,s=r;continue}e?o>i&&(i=o):o<i&&(i=o)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",ve,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function In(a,t,e){for(const s of e)t.addEventListener(s,a[s].bind(a))}class rf{#t=0;get id(){return`${jd}${this.#t++}`}}class ho{#t=Jd();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return Z(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Ln(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=ho._isSVGFittingCanvas,r=new FileReader,o=new Image,h=new Promise((l,c)=>{o.onload=()=>{s.bitmap=o,s.isSvg=!0,l()},r.onload=async()=>{const u=s.svgUrl=r.result;o.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},o.onerror=r.onerror=c});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){K(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class of{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(i&&t(),this.#e)return;const h={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(h);return}if(r&&this.#t[this.#i].type===n){o&&(h.undo=this.#t[this.#i].undo),this.#t[this.#i]=h;return}const l=this.#i+1;l===this.#s?this.#t.splice(0,1):(this.#i=l,l<this.#t.length&&this.#t.splice(l)),this.#t.push(h)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class bi{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Wt.platform;for(const[s,i,n={}]of t)for(const r of s){const o=r.startsWith("mac+");e&&o?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!o&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:o=null}}=s;o&&!o(t,e)||(i.bind(t,...r,e)(),n||ne(e))}}class lo{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return sf(t),Z(this,"_colors",t)}convert(t){const e=oo(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return lo._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?G.makeHexColor(...e):t}}class Ze{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#h=null;#a=new of;#c=null;#l=null;#d=0;#u=new Set;#f=null;#o=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#b=!1;#_=null;#v=null;#w=null;#S=null;#A=!1;#E=null;#M=new rf;#x=!1;#k=!1;#T=null;#O=null;#L=null;#I=null;#C=q.NONE;#y=new Set;#R=null;#z=null;#G=null;#V={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#N=[0,0];#F=null;#j=null;#W=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=Ze.prototype,e=r=>r.#j.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:o})=>{if(o instanceof HTMLInputElement){const{type:h}=o;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return Z(this,"_keyboardManager",new bi([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(o)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#j.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,o,h,l,c,u,d,f){const g=this._signal=this.#t.signal;this.#j=t,this.#W=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=o||null,this.#m=h,this.#p=l,this.#b=c,this.#I=u||null,this.viewParameters={realScale:js.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#a.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#v&&(clearTimeout(this.#v),this.#v=null),this.#F&&(clearTimeout(this.#F),this.#F=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return Z(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return Z(this,"direction",getComputedStyle(this.#j).direction)}get highlightColors(){return Z(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return Z(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=t}setMainHighlightColorPicker(t){this.#L=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":this.#b=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#j.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:o}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+o)return s}return null}disableUserSelect(t=!1){this.#W.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*js.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,o=e.toString(),l=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(l);if(!c)return;e.empty();const u=this.#Y(l),d=this.#C===q.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:o}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(q.HIGHLIGHT,f);return}f()}#Q(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new nf(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#P({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#P({hasSelectedText:!0}),!(this.#C!==q.HIGHLIGHT&&this.#C!==q.NONE)&&(this.#C===q.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===q.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,o=this.combinedSignal(r),h=l=>{l.type==="pointerup"&&l.button!==0||(r.abort(),n?.toggleDrawing(!0),l.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",h,{signal:o}),window.addEventListener("blur",h,{signal:o})}}#U(t=""){this.#C===q.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Q()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#o)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of this.#o)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){K(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const l=await i.deserialize(h);if(!l)return;n.push(l)}const r=()=>{for(const h of n)this.#J(h);this.#Z(n)},o=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(n){K(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==q.NONE&&!this.isEditorHandlingKeyboard&&Ze._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#P(t){Object.entries(t).some(([s,i])=>this.#V[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#V,t)}),this.#C===q.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[tt.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#P({isEditing:this.#C!==q.NONE,isEmpty:this.#X(),hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:this.#a.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#P({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#o){this.#o=t;for(const e of this.#o)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#M.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===q.NONE){this.setEditingState(!1),this.#at(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#ot(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#o){switch(t){case tt.CREATE:this.currentLayer.addNewEditor();return;case tt.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(e);break;case tt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#G||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#o)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#G?.get(tt.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[tt.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#ot(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#at(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.focusMainContainer(),this.#v=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#ht(){let t=null;for(t of this.#y);return t}updateUI(t){this.#ht===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#P({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}setSelected(t){this.#l?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#P({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#P({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#a.undo(),this.#P({hasSomethingToUndo:this.#a.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#X()}),this._editorUndoBar?.hide()}redo(){this.#a.redo(),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:this.#a.hasSomethingToRedo(),isEmpty:this.#X()})}addCommands(t){this.#a.add(t),this.#P({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#X()})}cleanUndoStack(t){this.#a.cleanType(t)}#X(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Z(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#P({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Z(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==q.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#P({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#N[0]+=t,this.#N[1]+=e;const[i,n]=this.#N,r=[...this.#y],o=1e3;this.#F&&clearTimeout(this.#F),this.#F=setTimeout(()=>{this.#F=null,this.#N[0]=this.#N[1]=0,this.addCommands({cmd:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)this.#s.has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},o);for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},o]of t)o.newX=i,o.newY=n,o.newPageIndex=r,e||=i!==o.savedX||n!==o.savedY||r!==o.savedPageIndex;if(!e)return!1;const s=(i,n,r,o)=>{if(this.#s.has(i.id)){const h=this.#i.get(o);h?i._setParentAndPosition(h,n,r):(i.pageIndex=o,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:o}]of t)s(i,n,r,o)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:o}]of t)s(i,n,r,o)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return Z(this,"imageManager",new ho)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let l=0,c=e.rangeCount;l<c;l++)if(!t.contains(e.getRangeAt(l).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let o;switch(t.getAttribute("data-main-rotation")){case"90":o=(l,c,u,d)=>({x:(c-i)/r,y:1-(l+u-s)/n,width:d/r,height:u/n});break;case"180":o=(l,c,u,d)=>({x:1-(l+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":o=(l,c,u,d)=>({x:1-(c+d-i)/r,y:(l-s)/n,width:d/r,height:u/n});break;default:o=(l,c,u,d)=>({x:(l-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const h=[];for(let l=0,c=e.rangeCount;l<c;l++){const u=e.getRangeAt(l);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||h.push(o(d,f,g,p))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#h||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#h?.delete(t)}renderAnnotationElement(t){const e=this.#h?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===q.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Me{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#h=!1;#a=null;#c=null;#l=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Me.#f||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){Me._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Me.#f.missing),e.setAttribute("data-l10n-id",Me.#f["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",ve,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#o}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#h=!0,i(n))},{signal:s}),await this.#g(),t}get#o(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#h}),this.#h=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#t===null&&(this.#l=t,this.#d=await Me._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#a?.remove(),this.#a=null;return}if(!this.#a){const e=this.#a=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#a.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#l===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#l,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#l=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#o}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#a?.remove(),this.#a=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Me.#f[this.#o]),this.#i?.setAttribute("data-l10n-id",Me.#f[`${this.#o}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class Nn{#t;#e=!1;#s=null;#i;#r;#n;#h;#a;#c=null;#l;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:o}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#h=r,this.#l=new AbortController,this.#a=AbortSignal.any([o,this.#l.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#a})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Z(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#a,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#o.bind(this),r),n.addEventListener("touchcancel",this.#o.bind(this),r),this.#r?.()}if(ne(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:o}=s,h=this.#c,{touch0X:l,touch0Y:c,touch1X:u,touch1Y:d}=h,f=u-l,g=d-c,p=r-i,b=o-n,m=Math.hypot(p,b)||1,v=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(v-m)<=Nn.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=o,t.preventDefault(),!this.#e){this.#e=!0;return}const y=[(i+r)/2,(n+o)/2];this.#n?.(y,v,m)}#o(t){this.#d.abort(),this.#d=null,this.#h?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#l?.abort(),this.#l=null}}class W{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#h=!1;#a=null;#c=null;#l=null;#d=null;#u="";#f=!1;#o=null;#g=!1;#m=!1;#p=!1;#b=null;#_=0;#v=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=W._zIndex++;static _borderLineWidth=-1;static _colorManager=new lo;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=W.prototype._resizeWithKeyboard,e=Ze.TRANSLATE_SMALL,s=Ze.TRANSLATE_BIG;return Z(this,"_resizerKeyboardManager",new bi([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],W.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[o,h]=this.parentDimensions;this.x=t.x/o,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return Z(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new af({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(W._l10n??=t,W._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"}),W._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);W._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){at("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}#M([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#M(this.parentDimensions,t,e)}translateInPage(t,e){this.#o||=[this.x,this.y,this.width,this.height],this.#M(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#o||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:o}=this;const[h,l]=this.getBaseTranslation();r+=h,o+=l;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#o&&(this.#o[0]!==this.x||this.#o[1]!==this.y)}get _hasBeenResized(){return!!this.#o&&(this.#o[2]!==this.width||this.#o[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=W,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:o,height:h}=this;if(o*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-o,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(o,r));break;case 180:n=Math.min(s,Math.max(o,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-o,r));break}this.x=n/=s,this.y=r/=i;const[l,c]=this.getBaseTranslation();n+=l,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return W.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return W.#x(t,e,360-this.parentRotation)}#k(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#h||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#h&&e.endsWith("%");if(i&&n)return;const[r,o]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#h&&!n&&(t.height=`${(100*parseFloat(e)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#a)return;this.#a=document.createElement("div"),this.#a.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#a.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",ve,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#a)}#O(t,e){e.preventDefault();const{isMac:s}=Wt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",ne,{passive:!1,signal:r}),window.addEventListener("contextmenu",ve,{signal:r}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const o=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const l=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=o,this.div.style.cursor=h,this.#I()};window.addEventListener("pointerup",l,{signal:r}),window.addEventListener("blur",l,{signal:r})}#L(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#l)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#l;this.#l=null;const n=this.x,r=this.y,o=this.width,h=this.height;n===t&&r===e&&o===s&&h===i||this.addCommands({cmd:this.#L.bind(this,n,r,o,h),undo:this.#L.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,o=this.width,h=this.height,l=W.MIN_SIZE/s,c=W.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,R)=>[u[0]*M+u[2]*R,u[1]*M+u[3]*R],f=this.#k(360-this.rotation),g=(M,R)=>[f[0]*M+f[2]*R,f[1]*M+f[3]*R];let p,b,m=!1,v=!1;switch(t){case"topLeft":m=!0,p=(M,R)=>[0,0],b=(M,R)=>[M,R];break;case"topMiddle":p=(M,R)=>[M/2,0],b=(M,R)=>[M/2,R];break;case"topRight":m=!0,p=(M,R)=>[M,0],b=(M,R)=>[0,R];break;case"middleRight":v=!0,p=(M,R)=>[M,R/2],b=(M,R)=>[0,R/2];break;case"bottomRight":m=!0,p=(M,R)=>[M,R],b=(M,R)=>[0,0];break;case"bottomMiddle":p=(M,R)=>[M/2,R],b=(M,R)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,R)=>[0,R],b=(M,R)=>[M,0];break;case"middleLeft":v=!0,p=(M,R)=>[0,R/2],b=(M,R)=>[M,R/2];break}const y=p(o,h),_=b(o,h);let S=d(..._);const A=W._round(n+S[0]),T=W._round(r+S[1]);let k=1,P=1,B,F;if(e.fromKeyboard)({deltaX:B,deltaY:F}=e);else{const{screenX:M,screenY:R}=e,[U,lt]=this.#c;[B,F]=this.screenToPageTranslation(M-U,R-lt),this.#c[0]=M,this.#c[1]=R}if([B,F]=g(B/s,F/i),m){const M=Math.hypot(o,h);k=P=Math.max(Math.min(Math.hypot(_[0]-y[0]-B,_[1]-y[1]-F)/M,1/o,1/h),l/o,c/h)}else v?k=Math.max(l,Math.min(1,Math.abs(_[0]-y[0]-B)))/o:P=Math.max(c,Math.min(1,Math.abs(_[1]-y[1]-F)))/h;const I=W._round(o*k),O=W._round(h*P);S=d(...b(I,O));const D=A-S[0],z=T-S[1];this.#o||=[this.x,this.y,this.width,this.height],this.width=I,this.height=O,this.x=D,this.y=z,this.setDims(s*I,i*O),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new mi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Me.initialize(W._l10n),this.#s=new Me(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#N();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),In(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new Nn({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),o=(A,T)=>[r[0]*A+r[2]*T,r[1]*A+r[3]*T],[h,l]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=W.MIN_SIZE/h,p=W.MIN_SIZE/l;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const b=W._round(d*n),m=W._round(f*n);if(b===d&&m===f)return;this.#o||=[c,u,d,f];const v=o(d/2,f/2),y=W._round(c+v[0]),_=W._round(u+v[1]),S=o(b/2,m/2);this.x=y-S[0],this.y=_-S[1],this.width=b,this.height=m,this.setDims(h*b,l*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Wt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#V(t);return}this.#G(t)}get isSelected(){return this._uiManager.isSelected(this)}#G(t){const{isMac:e}=Wt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#V(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},o=l=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#G(l),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#v=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",l=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=l;if(d!==this.#r){ne(l);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#v);this.#_=c,this.#v=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",ne,r),window.addEventListener("pointerdown",l=>{l.pointerType===this.#n&&(this.#S||l.isPrimary)&&o(l),ne(l)},r));const h=l=>{if(!this.#r||this.#r===l.pointerId){o(l);return}ne(l)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[o,h]=this.pageTranslation,l=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+l+o,r-d-c-g+h,u+l+f+o,r-d-c+h];case 90:return[u+c+o,r-d+l+h,u+c+g+o,r-d+l+f+h];case 180:return[u-l-f+o,r-d+c+h,u-l+o,r-d+c+g+h];case 270:return[u-c-g+o,r-d-l-f+h,u-c+o,r-d-l+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,o=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,o,h];case 90:return[s,e-i,h,o];case 180:return[n,e-i,o,h];case 270:return[n,e-r,h,o];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#N(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#N()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){at("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[o,h,l,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=o/n,i.y=h/r,i.width=l/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#b&&(clearTimeout(this.#b),this.#b=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#a.classList.remove("hidden"),In(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#a.children;if(!this.#e){this.#e=Array.from(e);const r=this.#F.bind(this),o=this.#j.bind(this),h=this._uiManager._signal;for(const l of this.#e){const c=l.getAttribute("data-resizer-name");l.setAttribute("role","spinbutton"),l.addEventListener("keydown",r,{signal:h}),l.addEventListener("blur",o,{signal:h}),l.addEventListener("focus",this.#W.bind(this,c),{signal:h}),l.setAttribute("data-l10n-id",W._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let o=0;o<i-n;o++)this.#a.append(this.#a.firstChild);else if(n>i)for(let o=0;o<n-i;o++)this.#a.firstChild.before(this.#a.lastChild);let r=0;for(const o of e){const l=this.#e[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",W._l10nResizer[l])}}this.#D(0),this.#p=!0,this.#a.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#F(t){W._resizerKeyboardManager.exec(this,t)}#j(t){this.#p&&t.relatedTarget?.parentNode!==this.#a&&this.#B()}#W(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#a?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#h=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},W._telemetryTimeout),this.#w.set(s,i);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class af extends W{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Kh=3285377520,ae=4294901760,Pe=65535;class Jh{constructor(t){this.h1=t?t&4294967295:Kh,this.h2=t?t&4294967295:Kh}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,b=t.length;p<b;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let o=0,h=0,l=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Pe,g=d&Pe;for(let p=0;p<i;p++)p&1?(o=r[p],o=o*u&ae|o*f&Pe,o=o<<15|o>>>17,o=o*d&ae|o*g&Pe,l^=o,l=l<<13|l>>>19,l=l*5+3864292196):(h=r[p],h=h*u&ae|h*f&Pe,h=h<<15|h>>>17,h=h*d&ae|h*g&Pe,c^=h,c=c<<13|c>>>19,c=c*5+3864292196);switch(o=0,n){case 3:o^=e[i*4+2]<<16;case 2:o^=e[i*4+1]<<8;case 1:o^=e[i*4],o=o*u&ae|o*f&Pe,o=o<<15|o>>>17,o=o*d&ae|o*g&Pe,i&1?l^=o:c^=o}this.h1=l,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&ae|t*36045&Pe,e=e*4283543511&ae|((e<<16|t>>>16)*2950163797&ae)>>>16,t^=e>>>1,t=t*444984403&ae|t*60499&Pe,e=e*3301882366&ae|((e<<16|t>>>16)*3120437893&ae)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const co=Object.freeze({map:null,hash:"",transfer:void 0});class uo{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof W)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#s.set(t,e);i&&this.#i(),e instanceof W&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?to(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Zh(this)}get serializable(){if(this.#s.size===0)return co;const t=new Map,e=new Jh,s=[],i=Object.create(null);let n=!1;for(const[r,o]of this.#s){const h=o instanceof W?o.serialize(!1,i):o;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||=!!h.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:co}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof W))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[o,h]of Object.entries(i)){if(o==="type")continue;let l=r.get(o);l||(l=new Map,r.set(o,l));const c=l.get(h)??0;l.set(h,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof W)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Zh extends uo{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){at("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return Z(this,"modifiedIds",{ids:new Set,hash:""})}}class hf{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(St(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#t.add(s),e?.(t)}catch{K(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}at("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw K(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return Z(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Ft||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),Z(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(St(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Z(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(_,S){return _.charCodeAt(S)<<24|_.charCodeAt(S+1)<<16|_.charCodeAt(S+2)<<8|_.charCodeAt(S+3)&255}function i(_,S,A,T){const k=_.substring(0,S),P=_.substring(S+A);return k+T+P}let n,r;const o=this._document.createElement("canvas");o.width=1,o.height=1;const h=o.getContext("2d");let l=0;function c(_,S){if(++l>30){K("Load test font never loaded."),S();return}if(h.font="30px "+_,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){S();return}setTimeout(c.bind(null,_,S))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let b=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)b=b-p+s(u,n)|0;n<u.length&&(b=b-p+s(u+"XXX",n)|0),d=i(d,g,4,Ud(b));const m=`url(data:font/opentype;base64,${btoa(d)});`,v=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(v);const y=this._document.createElement("div");y.style.visibility="hidden",y.style.width=y.style.height="10px",y.style.position="absolute",y.style.top=y.style.left="0px";for(const _ of[t.loadedName,u]){const S=this._document.createElement("span");S.textContent="Hi",S.style.fontFamily=_,y.append(S)}this._document.body.append(y),c(u,()=>{y.remove(),e.complete()})}}class lf{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Zd(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){K(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const jn={DATA:1,ERROR:2},Ct={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Qh(){}function Kt(a){if(a instanceof Je||a instanceof Qr||a instanceof fi||a instanceof Xh||a instanceof Dn||a instanceof Zr)return a;switch(a instanceof Error||typeof a=="object"&&a!==null||at('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),a.name){case"AbortException":return new Je(a.message);case"InvalidPDFException":return new Qr(a.message);case"MissingPDFException":return new fi(a.message);case"PasswordException":return new Xh(a.message,a.code);case"UnexpectedResponseException":return new Dn(a.message,a.status);case"UnknownErrorException":return new Zr(a.message,a.details)}return new Zr(a.message,a.toString())}class vi{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===jn.DATA)i.resolve(t.data);else if(t.callback===jn.ERROR)i.reject(Kt(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:jn.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:jn.ERROR,callbackId:t.callbackId,reason:Kt(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,o=this.targetName,h=this.comObj;return new ReadableStream({start:l=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:l,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:o,action:t,streamId:n,data:e,desiredSize:l.desiredSize},i),c.promise},pull:l=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,h.postMessage({sourceName:r,targetName:o,stream:Ct.PULL,streamId:n,desiredSize:l.desiredSize}),c.promise},cancel:l=>{St(l instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:o,stream:Ct.CANCEL,streamId:n,reason:Kt(l)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,o=this.actionHandler[t.action],h={enqueue(l,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ct.ENQUEUE,streamId:e,chunk:l},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ct.CLOSE,streamId:e}),delete r.streamSinks[e])},error(l){St(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ct.ERROR,streamId:e,reason:Kt(l)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(o,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.START_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.START_COMPLETE,streamId:e,reason:Kt(l)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],o=this.streamSinks[e];switch(t.stream){case Ct.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(Kt(t.reason));break;case Ct.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(Kt(t.reason));break;case Ct.PULL:if(!o){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,Promise.try(o.onPull||Qh).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.PULL_COMPLETE,streamId:e,reason:Kt(l)})});break;case Ct.ENQUEUE:if(St(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Ct.CLOSE:if(St(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case Ct.ERROR:St(r,"error should have stream controller"),r.controller.error(Kt(t.reason)),this.#r(r,e);break;case Ct.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(Kt(t.reason)),this.#r(r,e);break;case Ct.CANCEL:if(!o)break;const h=Kt(t.reason);Promise.try(o.onCancel||Qh,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ct.CANCEL_COMPLETE,streamId:e,success:!0})},function(l){n.postMessage({sourceName:s,targetName:i,stream:Ct.CANCEL_COMPLETE,streamId:e,reason:Kt(l)})}),o.sinkCapability.reject(h),o.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class tl{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){at("Abstract method `_createCanvas` called.")}}class cf extends tl{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class el{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){at("Abstract method `_fetch` called.")}}class sl extends el{async _fetch(t){const e=await Ln(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):Rn(e)}}class il{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class uf extends il{#t;#e;#s;#i;#r;#n;#h=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#a(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#l(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(Ge,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(Ge,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const h=t[0],l=new Array(256);for(let u=0;u<256;u++)l[u]=h[u]/255;const c=l.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),o=new Array(256);for(let h=0;h<256;h++)n[h]=e[h]/255,r[h]=s[h]/255,o[h]=i[h]/255;return[n.join(","),r.join(","),o.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Fn(e)?K('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#a.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#a.get(r),e)return this.#a.set(t,e),e;const o=`g_${this.#i}_transfer_map_${this.#h++}`,h=this.#u(o);this.#a.set(t,h),this.#a.set(r,h);const l=this.#g(o);return this.#p(s,i,n,l),h}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=G.makeHexColor(...r);const o=this.#_(e);if(e=G.makeHexColor(...o),this.#l.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const h=new Array(256);for(let f=0;f<=255;f++){const g=f/255;h[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const l=h.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(l,l,l,u),this.#o(u);const d=(f,g)=>{const p=r[f]/255,b=o[f]/255,m=new Array(g+1);for(let v=0;v<=g;v++)m[v]=p+v/g*(b-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#a.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#b(s,o),r}addLuminosityFilter(t){let e=this.#a.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#a.get(i),e)return this.#a.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#h++}`,r=this.#u(n);this.#a.set(t,r),this.#a.set(i,r);const o=this.#g(n);return this.#f(o),t&&this.#b(s,o),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let o=this.#c.get(t);if(o?.key===r||(o?(o.filter?.remove(),o.key=r,o.url="none",o.filter=null):(o={key:r,url:"none",filter:null},this.#c.set(t,o)),!e||!s))return o.url;const[h,l]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),u=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#l.style.color="";const g=(m,v,y)=>{const _=new Array(256),S=(u-c)/y,A=m/255,T=(v-m)/(255*y);let k=0;for(let P=0;P<=y;P++){const B=Math.round(c+P*S),F=A+P*T;for(let I=k;I<=B;I++)_[I]=F;k=B+1}for(let P=k;P<256;P++)_[P]=_[k-1];return _.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,b=o.filter=this.#g(p);return this.#o(b),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),b),o.url=this.#u(p),o.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#h=0)}#f(t){const e=this.#r.createElementNS(Ge,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#o(t){const e=this.#r.createElementNS(Ge,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#r.createElementNS(Ge,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#l.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(Ge,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(Ge,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#b(t,e){const s=this.#r.createElementNS(Ge,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#l.style.color=t,oo(getComputedStyle(this.#l).getPropertyValue("color"))}}class nl{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){at("Abstract method `_fetch` called.")}}class rl extends nl{async _fetch(t){const e=await Ln(t,"arraybuffer");return new Uint8Array(e)}}Ft&&K("Please use the `legacy` build in Node.js environments.");async function ol(a){const e=await process.getBuiltinModule("fs").promises.readFile(a);return new Uint8Array(e)}class df extends il{}class ff extends tl{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:mt&&mt.tagName.toUpperCase()==="SCRIPT"&&mt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class gf extends el{async _fetch(t){return ol(t)}}class pf extends nl{async _fetch(t){return ol(t)}}const Nt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function fo(a,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),a.clip(i)}class go{getPattern(){at("Abstract method `getPattern` called.")}}class mf extends go{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Nt.STROKE||i===Nt.FILL){const r=e.current.getClippedPathBoundingBox(i,ut(t))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",o,h),c=l.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=G.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),fo(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(l.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else fo(t,this._bbox),n=this._createGradient(t);return n}}function po(a,t,e,s,i,n,r,o){const h=t.coords,l=t.colors,c=a.data,u=a.width*4;let d;h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),h[s+1]>h[i+1]&&(d=s,s=i,i=d,d=r,r=o,o=d),h[e+1]>h[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(h[e]+t.offsetX)*t.scaleX,g=(h[e+1]+t.offsetY)*t.scaleY,p=(h[s]+t.offsetX)*t.scaleX,b=(h[s+1]+t.offsetY)*t.scaleY,m=(h[i]+t.offsetX)*t.scaleX,v=(h[i+1]+t.offsetY)*t.scaleY;if(g>=v)return;const y=l[n],_=l[n+1],S=l[n+2],A=l[r],T=l[r+1],k=l[r+2],P=l[o],B=l[o+1],F=l[o+2],I=Math.round(g),O=Math.round(v);let D,z,M,R,U,lt,ft,E;for(let H=I;H<=O;H++){if(H<b){const N=H<g?0:(g-H)/(g-b);D=f-(f-p)*N,z=y-(y-A)*N,M=_-(_-T)*N,R=S-(S-k)*N}else{let N;H>v?N=1:b===v?N=0:N=(b-H)/(b-v),D=p-(p-m)*N,z=A-(A-P)*N,M=T-(T-B)*N,R=k-(k-F)*N}let V;H<g?V=0:H>v?V=1:V=(g-H)/(g-v),U=f-(f-m)*V,lt=y-(y-P)*V,ft=_-(_-B)*V,E=S-(S-F)*V;const Q=Math.round(Math.min(D,U)),kt=Math.round(Math.max(D,U));let rt=u*H+Q*4;for(let N=Q;N<=kt;N++)V=(D-N)/(D-U),V<0?V=0:V>1&&(V=1),c[rt++]=z-(z-lt)*V|0,c[rt++]=M-(M-ft)*V|0,c[rt++]=R-(R-E)*V|0,c[rt++]=255}}function bf(a,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const o=t.verticesPerRow,h=Math.floor(s.length/o)-1,l=o-1;for(n=0;n<h;n++){let c=n*o;for(let u=0;u<l;u++,c++)po(a,e,s[c],s[c+1],s[c+o],i[c],i[c+1],i[c+o]),po(a,e,s[c+o+1],s[c+1],s[c+o],i[c+o+1],i[c+1],i[c+o])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)po(a,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class vf extends go{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const o=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),l=Math.ceil(this._bounds[2])-o,c=Math.ceil(this._bounds[3])-h,u=Math.min(Math.ceil(Math.abs(l*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=l/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-o,offsetY:-h,scaleX:1/f,scaleY:1/g},b=u+4,m=d+4,v=s.getCanvas("mesh",b,m),y=v.context,_=y.createImageData(u,d);if(e){const A=_.data;for(let T=0,k=A.length;T<k;T+=4)A[T]=e[0],A[T+1]=e[1],A[T+2]=e[2],A[T+3]=255}for(const A of this._figures)bf(_,A,p);return y.putImageData(_,2,2),{canvas:v.canvas,offsetX:o-2*f,offsetY:h-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){fo(t,this._bbox);let n;if(i===Nt.SHADING)n=G.singularValueDecompose2dScale(ut(t));else if(n=G.singularValueDecompose2dScale(e.baseTransform),this.matrix){const o=G.singularValueDecompose2dScale(this.matrix);n=[n[0]*o[0],n[1]*o[1]]}const r=this._createMeshCanvas(n,i===Nt.SHADING?null:this._background,e.cachedCanvases);return i!==Nt.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class yf extends go{getPattern(){return"hotpink"}}function _f(a){switch(a[0]){case"RadialAxial":return new mf(a);case"Mesh":return new vf(a);case"Dummy":return new yf}throw new Error(`Unknown IR type: ${a[0]}`)}const al={COLORED:1,UNCOLORED:2};class mo{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:o}=this;let{xstep:h,ystep:l}=this;h=Math.abs(h),l=Math.abs(l),On("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,b=G.singularValueDecompose2dScale(this.matrix),m=G.singularValueDecompose2dScale(this.baseTransform),v=b[0]*m[0],y=b[1]*m[1];let _=g,S=p,A=!1,T=!1;const k=Math.ceil(h*v),P=Math.ceil(l*y),B=Math.ceil(g*v),F=Math.ceil(p*y);k>=B?_=h:A=!0,P>=F?S=l:T=!0;const I=this.getSizeAndScale(_,this.ctx.canvas.width,v),O=this.getSizeAndScale(S,this.ctx.canvas.height,y),D=t.cachedCanvases.getCanvas("pattern",I.size,O.size),z=D.context,M=o.createCanvasGraphics(z);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),z.translate(-I.scale*c,-O.scale*u),M.transform(I.scale,0,0,O.scale,0,0),z.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=ut(M.ctx),M.executeOperatorList(s),M.endDrawing(),z.restore(),A||T){const R=D.canvas;A&&(_=h),T&&(S=l);const U=this.getSizeAndScale(_,this.ctx.canvas.width,v),lt=this.getSizeAndScale(S,this.ctx.canvas.height,y),ft=U.size,E=lt.size,H=t.cachedCanvases.getCanvas("pattern-workaround",ft,E),V=H.context,Q=A?Math.floor(g/h):0,kt=T?Math.floor(p/l):0;for(let rt=0;rt<=Q;rt++)for(let N=0;N<=kt;N++)V.drawImage(R,ft*rt,E*N,ft,E,0,0,ft,E);return{canvas:H.canvas,scaleX:U.scale,scaleY:lt.scale,offsetX:c,offsetY:u}}return{canvas:D.canvas,scaleX:I.scale,scaleY:O.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(mo.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,o=n-s;t.ctx.rect(e,s,r,o),t.current.updateRectMinMax(ut(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case al.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case al.UNCOLORED:const o=G.makeHexColor(s[0],s[1],s[2]);i.fillStyle=o,i.strokeStyle=o,n.fillColor=o,n.strokeColor=o;break;default:throw new Xd(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Nt.SHADING&&(n=G.transform(n,e.baseTransform),this.matrix&&(n=G.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let o=new DOMMatrix(n);o=o.translate(r.offsetX,r.offsetY),o=o.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(o),h}}function wf({src:a,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const o=Wt.isLittleEndian?4278190080:255,[h,l]=r?[n,o]:[o,n],c=s>>3,u=s&7,d=a.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const b=t+c;t<b;t++){const m=t<d?a[t]:255;e[f++]=m&128?l:h,e[f++]=m&64?l:h,e[f++]=m&32?l:h,e[f++]=m&16?l:h,e[f++]=m&8?l:h,e[f++]=m&4?l:h,e[f++]=m&2?l:h,e[f++]=m&1?l:h}if(u===0)continue;const p=t<d?a[t++]:255;for(let b=0;b<u;b++)e[f++]=p&1<<7-b?l:h}return{srcPos:t,destPos:f}}const hl=16,ll=100,xf=15,cl=10,ul=1e3,Jt=16;function Sf(a,t){if(a._removeMirroring)throw new Error("Context is already forwarding operations.");a.__originalSave=a.save,a.__originalRestore=a.restore,a.__originalRotate=a.rotate,a.__originalScale=a.scale,a.__originalTranslate=a.translate,a.__originalTransform=a.transform,a.__originalSetTransform=a.setTransform,a.__originalResetTransform=a.resetTransform,a.__originalClip=a.clip,a.__originalMoveTo=a.moveTo,a.__originalLineTo=a.lineTo,a.__originalBezierCurveTo=a.bezierCurveTo,a.__originalRect=a.rect,a.__originalClosePath=a.closePath,a.__originalBeginPath=a.beginPath,a._removeMirroring=()=>{a.save=a.__originalSave,a.restore=a.__originalRestore,a.rotate=a.__originalRotate,a.scale=a.__originalScale,a.translate=a.__originalTranslate,a.transform=a.__originalTransform,a.setTransform=a.__originalSetTransform,a.resetTransform=a.__originalResetTransform,a.clip=a.__originalClip,a.moveTo=a.__originalMoveTo,a.lineTo=a.__originalLineTo,a.bezierCurveTo=a.__originalBezierCurveTo,a.rect=a.__originalRect,a.closePath=a.__originalClosePath,a.beginPath=a.__originalBeginPath,delete a._removeMirroring},a.save=function(){t.save(),this.__originalSave()},a.restore=function(){t.restore(),this.__originalRestore()},a.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},a.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},a.transform=function(s,i,n,r,o,h){t.transform(s,i,n,r,o,h),this.__originalTransform(s,i,n,r,o,h)},a.setTransform=function(s,i,n,r,o,h){t.setTransform(s,i,n,r,o,h),this.__originalSetTransform(s,i,n,r,o,h)},a.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},a.rotate=function(s){t.rotate(s),this.__originalRotate(s)},a.clip=function(s){t.clip(s),this.__originalClip(s)},a.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},a.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},a.bezierCurveTo=function(e,s,i,n,r,o){t.bezierCurveTo(e,s,i,n,r,o),this.__originalBezierCurveTo(e,s,i,n,r,o)},a.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},a.closePath=function(){t.closePath(),this.__originalClosePath()},a.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class Cf{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function Bn(a,t,e,s,i,n,r,o,h,l){const[c,u,d,f,g,p]=ut(a);if(u===0&&d===0){const v=r*c+g,y=Math.round(v),_=o*f+p,S=Math.round(_),A=(r+h)*c+g,T=Math.abs(Math.round(A)-y)||1,k=(o+l)*f+p,P=Math.abs(Math.round(k)-S)||1;return a.setTransform(Math.sign(c),0,0,Math.sign(f),y,S),a.drawImage(t,e,s,i,n,0,0,T,P),a.setTransform(c,u,d,f,g,p),[T,P]}if(c===0&&f===0){const v=o*d+g,y=Math.round(v),_=r*u+p,S=Math.round(_),A=(o+l)*d+g,T=Math.abs(Math.round(A)-y)||1,k=(r+h)*u+p,P=Math.abs(Math.round(k)-S)||1;return a.setTransform(0,Math.sign(u),Math.sign(d),0,y,S),a.drawImage(t,e,s,i,n,0,0,P,T),a.setTransform(c,u,d,f,g,p),[P,T]}a.drawImage(t,e,s,i,n,r,o,h,l);const b=Math.hypot(c,u),m=Math.hypot(d,f);return[b*h,m*l]}function Af(a){const{width:t,height:e}=a;if(t>ul||e>ul)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),o,h,l;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of a.data){let v=128;for(;v>0;)u[d++]=m&v?0:255,v>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[h]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[h]=2,++f),o=1;o<e;o++){d=o*c,l=o*n,u[d-c]!==u[d]&&(r[l]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(h=1;h<t;h++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[l+h]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[l+h]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),l=o*n,u[d]!==0&&(r[l]=8,++f),h=1;h<t;h++)u[d]!==u[d+1]&&(r[l+h]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[l+h]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(o=0;f&&o<=e;o++){let m=o*n;const v=m+t;for(;m<v&&!r[m];)m++;if(m===v)continue;p.moveTo(m%n,o);const y=m;let _=r[m];do{const S=g[_];do m+=S;while(!r[m]);const A=r[m];A!==5&&A!==10?(_=A,r[m]=0):(_=A&51*_>>4,r[m]&=_>>2|_<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(y!==m);--o}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class dl{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Wh,this.textMatrixScale=1,this.fontMatrix=Kr,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=It.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=G.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=G.applyTransform(e,t),i=G.applyTransform(e.slice(2),t),n=G.applyTransform([e[0],e[3]],t),r=G.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){G.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,o,h,l,c){const u=G.bezierBoundingBox(e,s,i,n,r,o,h,l,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Nt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Nt.STROKE){e||at("Stroke bounding box must include transform.");const i=G.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=G.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Nt.FILL,e=null){return G.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function fl(a,t){if(t instanceof ImageData){a.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%Jt,n=(e-i)/Jt,r=i===0?n:n+1,o=a.createImageData(s,Jt);let h=0,l;const c=t.data,u=o.data;let d,f,g,p;if(t.kind===kn.GRAYSCALE_1BPP){const b=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),v=m.length,y=s+7>>3,_=4294967295,S=Wt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?Jt:i,l=0,f=0;f<g;f++){const A=b-h;let T=0;const k=A>y?s:A*8-7,P=k&-8;let B=0,F=0;for(;T<P;T+=8)F=c[h++],m[l++]=F&128?_:S,m[l++]=F&64?_:S,m[l++]=F&32?_:S,m[l++]=F&16?_:S,m[l++]=F&8?_:S,m[l++]=F&4?_:S,m[l++]=F&2?_:S,m[l++]=F&1?_:S;for(;T<k;T++)B===0&&(F=c[h++],B=128),m[l++]=F&B?_:S,B>>=1}for(;l<v;)m[l++]=0;a.putImageData(o,0,d*Jt)}}else if(t.kind===kn.RGBA_32BPP){for(f=0,p=s*Jt*4,d=0;d<n;d++)u.set(c.subarray(h,h+p)),h+=p,a.putImageData(o,0,f),f+=Jt;d<r&&(p=s*i*4,u.set(c.subarray(h,h+p)),a.putImageData(o,0,f))}else if(t.kind===kn.RGB_24BPP)for(g=Jt,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),l=0,f=p;f--;)u[l++]=c[h++],u[l++]=c[h++],u[l++]=c[h++],u[l++]=255;a.putImageData(o,0,d*Jt)}else throw new Error(`bad image kind: ${t.kind}`)}function gl(a,t){if(t.bitmap){a.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%Jt,n=(e-i)/Jt,r=i===0?n:n+1,o=a.createImageData(s,Jt);let h=0;const l=t.data,c=o.data;for(let u=0;u<r;u++){const d=u<n?Jt:i;({srcPos:h}=wf({src:l,srcPos:h,dest:c,width:s,height:d,nonBlackColor:0})),a.putImageData(o,0,u*Jt)}}function yi(a,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)a[s]!==void 0&&(t[s]=a[s]);a.setLineDash!==void 0&&(t.setLineDash(a.getLineDash()),t.lineDashOffset=a.lineDashOffset)}function Hn(a){if(a.strokeStyle=a.fillStyle="#000000",a.fillRule="nonzero",a.globalAlpha=1,a.lineWidth=1,a.lineCap="butt",a.lineJoin="miter",a.miterLimit=10,a.globalCompositeOperation="source-over",a.font="10px sans-serif",a.setLineDash!==void 0&&(a.setLineDash([]),a.lineDashOffset=0),!Ft){const{filter:t}=a;t!=="none"&&t!==""&&(a.filter="none")}}function pl(a,t){if(t)return!0;const e=G.singularValueDecompose2dScale(a);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*js.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const Tf=["butt","round","square"],Ef=["miter","round","bevel"],kf={},ml={};class Bs{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:o=null},h,l){this.ctx=t,this.current=new dl(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedCanvases=new Cf(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=l,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=o,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...ut(this.compositeCtx))}this.ctx.save(),Hn(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=ut(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let o=e||0;const h=n.length;if(h===o)return o;const l=h-o>cl&&typeof s=="function",c=l?Date.now()+xf:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&o===i.nextBreakPoint)return i.breakIt(o,s),o;if(g=r[o],g!==be.dependency)this[g].apply(this,n[o]);else for(const p of n[o]){const b=p.startsWith("g_")?d:f;if(!b.has(p))return b.get(p,s),o}if(o++,o===h)return o;if(l&&++u>cl){if(Date.now()>c)return s(),o;u=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=s,h=i,l="prescale1",c,u;for(;n>2&&o>1||r>2&&h>1;){let d=o,f=h;n>2&&o>1&&(d=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),n/=o/d),r>2&&h>1&&(f=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/f),c=this.cachedCanvases.getCanvas(l,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,o,h,0,0,d,f),t=c.canvas,o=d,h=f,l=l==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,o=ut(e);let h,l,c,u;if((t.bitmap||t.data)&&t.count>1){const k=t.bitmap||t.data.buffer;l=JSON.stringify(r?o:[o.slice(0,4),n]),h=this._cachedBitmapsMap.get(k),h||(h=new Map,this._cachedBitmapsMap.set(k,h));const P=h.get(l);if(P&&!r){const B=Math.round(Math.min(o[0],o[2])+o[4]),F=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:P,offsetX:B,offsetY:F}}c=P}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),gl(u.context,t));let d=G.transform(o,[1/s,0,0,-1/i,0,0]);d=G.transform(d,[1,0,0,1,0,-i]);const[f,g,p,b]=G.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,v=Math.round(b-g)||1,y=this.cachedCanvases.getCanvas("fillCanvas",m,v),_=y.context,S=f,A=g;_.translate(-S,-A),_.transform(...d),c||(c=this._scaleImage(u.canvas,ke(_)),c=c.img,h&&r&&h.set(l,c)),_.imageSmoothingEnabled=pl(ut(_),t.interpolate),Bn(_,c,0,0,c.width,c.height,0,0,s,i),_.globalCompositeOperation="source-in";const T=G.transform(ke(_),[1,0,0,1,-S,-A]);return _.fillStyle=r?n.getPattern(e,this,T,Nt.FILL):n,_.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(l,y.canvas)),{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=Tf[t]}setLineJoin(t){this.ctx.lineJoin=Ef[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...ut(this.suspendedCtx)),yi(this.suspendedCtx,n),Sf(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),yi(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],o=i[2]-n,h=i[3]-r;o===0||h===0||(this.genericComposeSMask(e.context,s,o,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,o,h,l,c,u){let d=t.canvas,f=h-c,g=l-u;if(r){const b=G.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),v=m.context;v.drawImage(d,-f,-g),v.globalCompositeOperation="destination-atop",v.fillStyle=b,v.fillRect(0,0,s,i),v.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=b,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&o?e.filter=this.filterFactory.addAlphaFilter(o):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(o));const p=new Path2D;p.rect(h,l,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,h,l,s,i),e.restore()}save(){this.inSMaskMode?(yi(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),yi(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,o=n.y,h,l;const c=ut(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case be.rectangle:r=e[g++],o=e[g++];const b=e[g++],m=e[g++],v=r+b,y=o+m;i.moveTo(r,o),b===0||m===0?i.lineTo(v,y):(i.lineTo(v,o),i.lineTo(v,y),i.lineTo(r,y)),u||n.updateRectMinMax(c,[r,o,v,y]),i.closePath();break;case be.moveTo:r=e[g++],o=e[g++],i.moveTo(r,o),u||n.updatePathMinMax(c,r,o);break;case be.lineTo:r=e[g++],o=e[g++],i.lineTo(r,o),u||n.updatePathMinMax(c,r,o);break;case be.curveTo:h=r,l=o,r=e[g+4],o=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],e[g+2],e[g+3],r,o,d),g+=6;break;case be.curveTo2:h=r,l=o,i.bezierCurveTo(r,o,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,h,l,r,o,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],o=e[g+3],g+=4;break;case be.curveTo3:h=r,l=o,r=e[g+2],o=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,o,r,o),n.updateCurvePathMinMax(c,h,l,e[g],e[g+1],r,o,r,o,d),g+=4;break;case be.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,o)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,ke(e),Nt.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,ke(e),Nt.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=kf}eoClip(){this.pendingClip=ml}beginText(){this.current.textMatrix=Wh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:o,fontSize:h,path:l}of t)s.addPath(l,new DOMMatrix(n).preMultiplySelf(i).translate(r,o).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Kr,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&K("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let o="normal";s.black?o="900":s.bold&&(o="bold");const h=s.italic?"italic":"normal";let l=e;e<hl?l=hl:e>ll&&(l=ll),this.current.fontSizeScale=e/l,this.ctx.font=`${h} ${o} ${l}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,o=this.current,h=o.font,l=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,u=l&It.FILL_STROKE_MASK,d=!!(l&It.ADD_TO_PATH_FLAG),f=o.patternFill&&!h.missingFile,g=o.patternStroke&&!h.missingFile;let p;if((h.disableFontFace||d||f||g)&&(p=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===It.FILL||u===It.FILL_STROKE)if(i){const b=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,b,i))}else r.fill(p);if(u===It.STROKE||u===It.FILL_STROKE)if(n){const b=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,b,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===It.FILL||u===It.FILL_STROKE)&&r.fillText(t,e,s),(u===It.STROKE||u===It.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:ut(r),x:e,y:s,fontSize:c,path:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return Z(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,o=e.charSpacing,h=e.wordSpacing,l=e.fontDirection,c=e.textHScale*l,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],b=e.textRenderingMode===It.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),l>0?n.scale(c,-1):n.scale(c,1);let m,v;if(e.patternFill){n.save();const T=e.fillColor.getPattern(n,this,ke(n),Nt.FILL);m=ut(n),n.restore(),n.fillStyle=T}if(e.patternStroke){n.save();const T=e.strokeColor.getPattern(n,this,ke(n),Nt.STROKE);v=ut(n),n.restore(),n.strokeStyle=T}let y=e.lineWidth;const _=e.textMatrixScale;if(_===0||y===0){const T=e.textRenderingMode&It.FILL_STROKE_MASK;(T===It.STROKE||T===It.FILL_STROKE)&&(y=this.getSinglePixelWidth())}else y/=_;if(r!==1&&(n.scale(r,r),y/=r),n.lineWidth=y,s.isInvalidPDFjsFont){const T=[];let k=0;for(const P of t)T.push(P.unicode),k+=P.width;n.fillText(T.join(""),0,0),e.x+=k*p*c,n.restore(),this.compose();return}let S=0,A;for(A=0;A<u;++A){const T=t[A];if(typeof T=="number"){S+=f*T*i/1e3;continue}let k=!1;const P=(T.isSpace?h:0)+o,B=T.fontChar,F=T.accent;let I,O,D=T.width;if(d){const M=T.vmetric||g,R=-(T.vmetric?M[1]:D*.5)*p,U=M[2]*p;D=M?-M[0]:D,I=R/r,O=(S+U)/r}else I=S/r,O=0;if(s.remeasure&&D>0){const M=n.measureText(B).width*1e3/i*r;if(D<M&&this.isFontSubpixelAAEnabled){const R=D/M;k=!0,n.save(),n.scale(R,1),I/=R}else D!==M&&(I+=(D-M)/2e3*i/r)}if(this.contentVisible&&(T.isInFont||s.missingFile)){if(b&&!F)n.fillText(B,I,O);else if(this.paintChar(B,I,O,m,v),F){const M=I+i*F.offset.x/r,R=O-i*F.offset.y/r;this.paintChar(F.fontChar,M,R,m,v)}}const z=d?D*p-P*l:D*p+P*l;S+=z,k&&n.restore()}d?e.y-=S:e.x+=S*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,o=i.vertical?1:-1,h=s.charSpacing,l=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||Kr,d=t.length,f=s.textRenderingMode===It.INVISIBLE;let g,p,b,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=o*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const v=(p.isSpace?l:0)+h,y=i.charProcOperatorList[p.operatorListId];if(!y){K(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(y),this.restore()),b=G.applyTransform([p.width,0],u)[0]*n+v,e.translate(b,0),s.x+=b*c}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||ut(this.ctx),n={createCanvasGraphics:r=>new Bs(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new mo(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=G.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=G.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=_f(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,ke(e),Nt.SHADING);const i=ke(e);if(i){const{width:n,height:r}=e.canvas,[o,h,l,c]=G.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(o,h,l-o,c-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){at("Should not call beginInlineImage")}beginImageData(){at("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=ut(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(ut(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||On("TODO: Support non-isolated groups."),t.knockout&&K("Knockout groups not supported.");const s=ut(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=G.getAxialAlignedBoundingBox(t.bbox,ut(e));const n=[0,0,e.canvas.width,e.canvas.height];i=G.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),o=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),l=Math.max(Math.ceil(i[3])-o,1);this.current.startNewPathAndClipBox([0,0,h,l]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,h,l),d=u.context;d.translate(-r,-o),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,o),e.save()),yi(e,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=ut(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=G.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),Hn(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],o=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=o;const[h,l]=G.singularValueDecompose2dScale(ut(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(o*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(h,0,0,-l,0,o*l),Hn(this.ctx)}else Hn(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new dl(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=Af(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const h=ut(o);o.transform(e,s,i,n,0,0);const l=this._createMaskCanvas(t);o.setTransform(1,0,0,1,l.offsetX-h[4],l.offsetY-h[5]);for(let c=0,u=r.length;c<u;c+=2){const d=G.transform(h,[e,s,i,n,r[c],r[c+1]]),[f,g]=G.applyTransform([0,0],d);o.drawImage(l.canvas,f,g)}o.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:o,height:h,transform:l}=n,c=this.cachedCanvases.getCanvas("maskCanvas",o,h),u=c.context;u.save();const d=this.getObject(r,n);gl(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,ke(e),Nt.FILL):s,u.fillRect(0,0,o,h),u.restore(),e.save(),e.transform(...l),e.scale(1,-1),Bn(e,c.canvas,0,0,o,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){K("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){K("Dependent image isn't ready yet");return}const r=n.width,o=n.height,h=[];for(let l=0,c=i.length;l<c;l+=2)h.push({transform:[e,0,0,s,i[l],i[l+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Ft){const{filter:o}=i;o!=="none"&&o!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;fl(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,ke(i));i.imageSmoothingEnabled=pl(ut(i),t.interpolate),Bn(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;fl(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),Bn(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===ml?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=ut(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,o;if(s===0&&i===0){const h=Math.abs(e),l=Math.abs(n);if(h===l)if(t===0)r=o=1/h;else{const c=h*t;r=o=c<1?1/c:1}else if(t===0)r=1/h,o=1/l;else{const c=h*t,u=l*t;r=c<1?1/c:1,o=u<1?1/u:1}}else{const h=Math.abs(e*n-s*i),l=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/h,o=l/h;else{const u=t*h;r=c>u?c/u:1,o=l>u?l/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const o=Math.max(i,n);e.setLineDash(r.map(h=>h/o)),e.lineDashOffset/=o}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const a in be)Bs.prototype[a]!==void 0&&(Bs.prototype[be[a]]=Bs.prototype[a]);class _i{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class Mf{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return to(this.#t)}has(t){return this.#t.has(t)}}const Hs=Symbol("INTERNAL");class Pf{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&ie.DISPLAY),this.#e=!!(t&ie.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==Hs&&at("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class Of{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=ie.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new Pf(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(Hs,!1);for(const s of t.on)this.#e.get(s)._setVisible(Hs,!0);for(const s of t.off)this.#e.get(s)._setVisible(Hs,!1);this.#s=this.getHash()}}#r(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return K(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return On("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(K(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return K(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return K(`Unknown optional content policy ${t.policy}.`),!0}return K(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){K(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(Hs,!1,!0);i._setVisible(Hs,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?to(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Jh;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class Df{constructor(t,{disableRange:e=!1,disableStream:s=!1}){St(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:o}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=o,n?.length>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,l)=>{this._onReceiveData({begin:h,chunk:l})}),t.addProgressListener((h,l)=>{this._onProgress({loaded:h,total:l})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});St(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){St(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new Rf(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Lf(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class Rf{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=ro(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class Lf{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function Ff(a){let t=!0,e=s("filename\\*","i").exec(a);if(e){e=e[1];let c=o(e);return c=unescape(c),c=h(c),c=l(c),n(c)}if(e=r(a),e){const c=l(e);return n(c)}if(e=s("filename","i").exec(a),e){e=e[1];let c=o(e);return c=l(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=Rn(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,b,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[b,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[b,m]=u[p];m=o(m),b&&(m=unescape(m),p===0&&(m=h(m))),g.push(m)}return g.join("")}function o(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function h(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function l(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,b){return String.fromCharCode(parseInt(b,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function bl(a,t){const e=new Headers;if(!a||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function zn(a){try{return new URL(a).origin}catch{}return null}function vl({responseHeaders:a,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(a.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||a.get("Accept-Ranges")!=="bytes"||(a.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function yl(a){const t=a.get("Content-Disposition");if(t){let e=Ff(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(ro(e))return e}return null}function Gn(a,t){return a===404||a===0&&t.startsWith("file:")?new fi('Missing PDF "'+t+'".'):new Dn(`Unexpected server response (${a}) while retrieving PDF "${t}".`,a)}function _l(a){return a===200||a===206}function wl(a,t,e){return{method:"GET",headers:a,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function xl(a){return a instanceof Uint8Array?a.buffer:a instanceof ArrayBuffer?a:(K(`getArrayBuffer - unexpected data format: ${a}`),new Uint8Array(a).buffer)}class Sl{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=bl(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return St(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new If(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Nf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class If{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,wl(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=zn(n.url),!_l(n.status))throw Gn(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:o,suggestedLength:h}=vl({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=h||this._contentLength,this._filename=yl(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Je("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:xl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class Nf{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,wl(n,this._withCredentials,this._abortController)).then(o=>{const h=zn(o.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!_l(o.status))throw Gn(o.status,r);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:xl(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const bo=200,vo=206;function jf(a){const t=a.response;return typeof t!="string"?t:Rn(t).buffer}class Bf{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=bl(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=vo):i.expectedStatus=bo,e.responseType="arraybuffer",St(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||bo;if(!(n===bo&&s.expectedStatus===vo)&&n!==s.expectedStatus){s.onError(i.status);return}const o=jf(i);if(n===vo){const h=i.getResponseHeader("Content-Range"),l=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);l?s.onDone({begin:parseInt(l[1],10),chunk:o}):(K('Missing or invalid "Content-Range" header.'),s.onError(0))}else o?s.onDone({begin:0,chunk:o}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Hf{constructor(t){this._source=t,this._manager=new Bf(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return St(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new zf(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Gf(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class zf{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=zn(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(o=>{const[h,...l]=o.split(": ");return[h,l.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=vl({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=yl(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Gn(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Gf{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=zn(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=Gn(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const Vf=/^[a-z][a-z0-9\-+.]+:/i;function Wf(a){if(Vf.test(a))return new URL(a);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(a))}class Xf{constructor(t){this.source=t,this.url=Wf(t.url),St(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return St(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Uf(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Yf(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Uf{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new fi(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new Je("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Yf{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const $f=1e5,Zt=30,qf=.8;class Xt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#h=0;#a=0;#c=null;#l=null;#d=0;#u=0;#f=Object.create(null);#o=[];#g=null;#m=[];#p=new WeakMap;#b=null;static#_=new Map;static#v=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(h){h.enqueue(t),h.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#l=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:o}=s.rawDims;this.#b=[1,0,0,-1,-r,o+n],this.#a=i,this.#h=n,Xt.#O(),ms(e,s),this.#t.promise.finally(()=>{Xt.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Wt.platform;return Z(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Xt.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,ms(this.#l,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Xt.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new Je("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#o}#E(t){if(this.#s)return;this.#n.ctx??=Xt.#k(this.#r);const e=this.#m,s=this.#o;for(const i of t){if(e.length>$f){K("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#M(i)}}#M(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=G.transform(this.#b,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let o=this.#i&&r.fontSubstitution||r.fontFamily;o=Xt.fontFamilyMap.get(o)||o;const h=Math.hypot(i[2],i[3]),l=h*Xt.#L(o,this.#r);let c,u;n===0?(c=i[4],u=i[5]-l):(c=i[4]+l*Math.sin(n),u=i[5]-l*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#l?(f.left=`${(100*c/this.#a).toFixed(2)}%`,f.top=`${(100*u/this.#h).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Xt.#S*h).toFixed(2)}px)`,f.fontFamily=o,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);p!==b&&Math.max(p,b)/Math.min(p,b)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Xt.#S>1&&(r=`scale(${1/Xt.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:o}=n,{canvasWidth:h,fontSize:l}=s;Xt.#T(i,l*this.#u,o);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${h*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#v.values())t.remove();this.#v.clear()}}static#k(t=null){let e=this.#v.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#v.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#S=t.getBoundingClientRect().height,t.remove()}static#L(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=Zt,this.#T(i,Zt,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,o=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+o);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,Zt,Zt),i.strokeText("g",0,0);let h=i.getImageData(0,0,Zt,Zt).data;o=0;for(let c=h.length-1-3;c>=0;c-=4)if(h[c]>0){o=Math.ceil(c/4/Zt);break}i.clearRect(0,0,Zt,Zt),i.strokeText("A",0,Zt),h=i.getImageData(0,0,Zt,Zt).data,r=0;for(let c=0,u=h.length;c<u;c+=4)if(h[c]>0){r=Zt-Math.floor(c/4/Zt);break}i.canvas.width=i.canvas.height=0;const l=r?r/(r+o):qf;return this.#_.set(t,l),l}}class wi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const o=n.name;if(o==="#text")r=n.value;else if(wi.shouldBuildText(o))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const h of n.children)i(h)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Kf=65536,Jf=100,Zf=5e3,Qf=Ft?ff:cf,tg=Ft?gf:sl,eg=Ft?df:uf,sg=Ft?pf:rl;function ig(a={}){typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a});const t=new yo,{docId:e}=t,s=a.url?ng(a.url):null,i=a.data?rg(a.data):null,n=a.httpHeaders||null,r=a.withCredentials===!0,o=a.password??null,h=a.range instanceof Al?a.range:null,l=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:Kf;let c=a.worker instanceof zs?a.worker:null;const u=a.verbosity,d=typeof a.docBaseUrl=="string"&&!Fn(a.docBaseUrl)?a.docBaseUrl:null,f=typeof a.cMapUrl=="string"?a.cMapUrl:null,g=a.cMapPacked!==!1,p=a.CMapReaderFactory||tg,b=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,m=a.StandardFontDataFactory||sg,v=a.stopAtErrors!==!0,y=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,_=a.isEvalSupported!==!1,S=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!Ft,A=typeof a.isImageDecoderSupported=="boolean"?a.isImageDecoderSupported:!Ft&&(Wt.platform.isFirefox||!globalThis.chrome),T=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,k=typeof a.disableFontFace=="boolean"?a.disableFontFace:Ft,P=a.fontExtraProperties===!0,B=a.enableXfa===!0,F=a.ownerDocument||globalThis.document,I=a.disableRange===!0,O=a.disableStream===!0,D=a.disableAutoFetch===!0,z=a.pdfBug===!0,M=a.CanvasFactory||Qf,R=a.FilterFactory||eg,U=a.enableHWA===!0,lt=h?h.length:a.length??NaN,ft=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!Ft&&!k,E=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:p===sl&&m===rl&&f&&b&&pi(f,document.baseURI)&&pi(b,document.baseURI),H=null;zd(u);const V={canvasFactory:new M({ownerDocument:F,enableHWA:U}),filterFactory:new R({docId:e,ownerDocument:F}),cMapReaderFactory:E?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:E?null:new m({baseUrl:b})};if(!c){const rt={verbosity:u,port:_i.workerPort};c=rt.port?zs.fromPort(rt):new zs(rt),t._worker=c}const Q={docId:e,apiVersion:"4.10.38",data:i,password:o,disableAutoFetch:D,rangeChunkSize:l,length:lt,docBaseUrl:d,enableXfa:B,evaluatorOptions:{maxImageSize:y,disableFontFace:k,ignoreErrors:v,isEvalSupported:_,isOffscreenCanvasSupported:S,isImageDecoderSupported:A,canvasMaxAreaInBytes:T,fontExtraProperties:P,useSystemFonts:ft,cMapUrl:E?f:null,standardFontDataUrl:E?b:null}},kt={disableFontFace:k,fontExtraProperties:P,ownerDocument:F,pdfBug:z,styleElement:H,loadingParams:{disableAutoFetch:D,enableXfa:B}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const rt=c.messageHandler.sendWithPromise("GetDocRequest",Q,i?[i.buffer]:null);let N;if(h)N=new Df(h,{disableRange:I,disableStream:O});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let ht;if(Ft)if(pi(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");ht=Sl}else ht=Xf;else ht=pi(s)?Sl:Hf;N=new ht({url:s,length:lt,httpHeaders:n,withCredentials:r,rangeChunkSize:l,disableRange:I,disableStream:O})}return rt.then(ht=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const Mt=new vi(e,ht,c.port),Pt=new lg(Mt,t,N,kt,V);t._transport=Pt,Mt.send("Ready",null)})}).catch(t._capability.reject),t}function ng(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(Ft&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function rg(a){if(Ft&&typeof Buffer<"u"&&a instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(a instanceof Uint8Array&&a.byteLength===a.buffer.byteLength)return a;if(typeof a=="string")return Rn(a);if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)||typeof a=="object"&&!isNaN(a?.length))return new Uint8Array(a);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function Cl(a){return typeof a=="object"&&Number.isInteger(a?.num)&&a.num>=0&&Number.isInteger(a?.gen)&&a.gen>=0}class yo{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${yo.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class Al{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){at("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class og{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 Z(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class ag{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new $h:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new Tl,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new gi({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Z(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=qe.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:l=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),o||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const b=!!(f&ie.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=_=>{p.renderTasks.delete(v),(this._maybeCleanupAfterRender||b)&&(this.#e=!0),this.#s(!b),_?(v.capability.reject(_),this._abortOperatorList({intentState:p,reason:_ instanceof Error?_:new Error(_)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Gs({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:l});(p.renderTasks||=new Set).add(v);const y=v.task;return Promise.all([p.displayReadyCapability.promise,o]).then(([_,S])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(S.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:_,optionalContentConfig:S}),v.operatorListChanged()}).catch(m),y}getOperatorList({intent:t="display",annotationMode:e=qe.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let o=this._intentStates.get(r.cacheKey);o||(o=Object.create(null),this._intentStates.set(r.cacheKey,o));let h;return o.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(h),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>wi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:l}){if(l){s(o);return}o.lang??=h.lang,Object.assign(o.styles,h.styles),o.items.push(...h.items),n()},i)}const r=e.getReader(),o={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new $h),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},Zf),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),l=this._intentStates.get(e);l.streamReader=h;const c=()=>{h.read().then(({value:u,done:d})=>{if(d){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,l),c())},u=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const d of l.renderTasks)d.operatorListChanged();this.#s(!0)}if(l.displayReadyCapability)l.displayReadyCapability.reject(u);else if(l.opListReadCapability)l.opListReadCapability.reject(u);else throw u}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof no){let i=Jf;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new Je(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class hg{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){K("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const dt=class dt{constructor({name:t=null,port:e=null,verbosity:s=Gd()}={}){Xs(this,Vs);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(ye(dt,ws)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(ye(dt,ws)||Ai(dt,ws,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new vi("main","worker",t),this._messageHandler.on("ready",function(){}),Un(this,Vs,$n).call(this)}_initialize(){if(ye(dt,_s)||ye(dt,Ws,qn)){this._setupFakeWorker();return}let{workerSrc:t}=dt;try{dt._isSameOrigin(window.location.href,t)||(t=dt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new vi("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",o=>{if(n.abort(),this.destroyed||!o){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,Un(this,Vs,$n).call(this)}),s.on("ready",o=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const o=new Uint8Array;s.send("test",o,[o.buffer])};r();return}catch{On("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(dt,_s)||(K("Setting up fake worker."),Ai(dt,_s,!0)),dt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new hg;this._port=e;const s=`fake${Zl(dt,Xn)._++}`,i=new vi(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new vi(s,s+"_worker",e),Un(this,Vs,$n).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,ye(dt,ws)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=ye(this,ws)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new dt(t)}static get workerSrc(){if(_i.workerSrc)return _i.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Z(this,"_setupFakeWorkerGlobal",(async()=>ye(this,Ws,qn)?ye(this,Ws,qn):(await import(this.workerSrc)).WorkerMessageHandler)())}};Xn=new WeakMap,_s=new WeakMap,ws=new WeakMap,Vs=new WeakSet,$n=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Ws=new WeakSet,qn=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},Xs(dt,Ws),Xs(dt,Xn,0),Xs(dt,_s,!1),Xs(dt,ws),Ft&&(Ai(dt,_s,!0),_i.workerSrc||="./pdf.worker.mjs"),dt._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},dt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let zs=dt;class lg{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new Tl,this.fontLoader=new hf({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return Z(this,"annotationStorage",new uo)}getRenderingIntent(t,e=qe.ENABLE,s=null,i=!1,n=!1){let r=ie.DISPLAY,o=co;switch(t){case"any":r=ie.ANY;break;case"display":break;case"print":r=ie.PRINT;break;default:K(`getRenderingIntent - invalid intent: ${t}`)}const h=r&ie.PRINT&&s instanceof Zh?s:this.annotationStorage;switch(e){case qe.DISABLE:r+=ie.ANNOTATIONS_DISABLE;break;case qe.ENABLE:break;case qe.ENABLE_FORMS:r+=ie.ANNOTATIONS_FORMS;break;case qe.ENABLE_STORAGE:r+=ie.ANNOTATIONS_STORAGE,o=h.serializable;break;default:K(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=ie.IS_EDITING),n&&(r+=ie.OPLIST);const{ids:l,hash:c}=h.modifiedIds,u=[r,o.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:o,modifiedIds:l}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Xt.cleanup(),this._networkStream?.cancelAllRequests(new Je("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{St(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}St(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=o=>{e.onProgress?.({loaded:o.loaded,total:o.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{St(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:o}){if(o){i.close();return}St(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new og(s,this))}),t.on("DocException",s=>{e._capability.reject(Kt(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw Kt(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:o,pdfBug:h}=this._params;if("error"in n){const d=n.error;K(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const l=h&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new lf(n,{disableFontFace:r,fontExtraProperties:o,inspectFont:l});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!o&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;St(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const o=this.#e.get(i);if(!o.objs.has(s)){if(o._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":o.objs.resolve(s,r),r?.dataLen>Nd&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&K("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#i.set(n.refStr,t);const r=new ag(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return Cl(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#n("GetFieldObjects")}hasJSActions(){return this.#n("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#n("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#n("GetOptionalContentConfig").then(e=>new Of(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new Mf(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Xt.cleanup()}}cachedPageNumber(t){if(!Cl(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const xi=Symbol("INITIAL_DATA");class Tl{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:xi}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===xi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==xi}delete(t){const e=this.#t[t];return!e||e.data===xi?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==xi&&(yield[t,e])}}}class cg{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class Gs{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:o,canvasFactory:h,filterFactory:l,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=h,this.filterFactory=l,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new cg(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(Gs.#e.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Gs.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new Bs(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),Gs.#e.delete(this._canvas),this.callback(t||new no(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),Gs.#e.delete(this._canvas),this.callback())))}}const ug="4.10.38",dg="f9bea397f";function El(a){return Math.floor(Math.max(0,Math.min(1,a))*255).toString(16).padStart(2,"0")}function Si(a){return Math.max(0,Math.min(255,255*a))}class kl{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=Si(t),[t,t,t]}static G_HTML([t]){const e=El(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(Si)}static RGB_HTML(t){return`#${t.map(El).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[Si(1-Math.min(1,t+i)),Si(1-Math.min(1,s+i)),Si(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,o=Math.min(i,n,r);return["CMYK",i,n,r,o]}}class fg{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){at("Abstract method `_createSVG` called.")}}class _o extends fg{_createSVG(t){return document.createElementNS(Ge,t)}}class Ml{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",o=>{i.setValue(e,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",o=>{i.setValue(e,{value:o.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const o of s.children)o.attributes.value===r.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const h=o.target.options,l=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:l})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,o=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,l]of Object.entries(r))if(l!=null)switch(h){case"class":l.length&&t.setAttribute(h,l.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",l);break;case"style":Object.assign(t.style,l);break;case"textContent":t.textContent=l;break;default:(!o||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,l)}o&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const o=n!=="richText",h=t.div;if(h.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=u}o&&h.setAttribute("class","xfaLayer xfaFont");const l=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),o&&wi.shouldBuildText(i.name)&&l.push(u)}return{textDivs:l}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);l.push(m),f.append(m);continue}const b=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(b),g.attributes&&this.setAttributes({html:b,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,b]);else if(g.value){const m=document.createTextNode(g.value);o&&wi.shouldBuildText(p)&&l.push(m),b.append(m)}}for(const u of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Ci=1e3,gg=9,bs=new WeakSet;function Qe(a){return{width:a[2]-a[0],height:a[3]-a[1]}}class pg{static create(t){switch(t.data.annotationType){case Tt.LINK:return new Pl(t);case Tt.TEXT:return new mg(t);case Tt.WIDGET:switch(t.data.fieldType){case"Tx":return new bg(t);case"Btn":return t.data.radioButton?new Ol(t):t.data.checkBox?new yg(t):new _g(t);case"Ch":return new wg(t);case"Sig":return new vg(t)}return new vs(t);case Tt.POPUP:return new wo(t);case Tt.FREETEXT:return new Dl(t);case Tt.LINE:return new Sg(t);case Tt.SQUARE:return new Cg(t);case Tt.CIRCLE:return new Ag(t);case Tt.POLYLINE:return new Rl(t);case Tt.CARET:return new Eg(t);case Tt.INK:return new xo(t);case Tt.POLYGON:return new Tg(t);case Tt.HIGHLIGHT:return new Ll(t);case Tt.UNDERLINE:return new kg(t);case Tt.SQUIGGLY:return new Mg(t);case Tt.STRIKEOUT:return new Pg(t);case Tt.STAMP:return new Fl(t);case Tt.FILEATTACHMENT:return new Og(t);default:return new yt(t)}}}class yt{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return yt._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:o,pageY:h}}}}=this;s?.splice(0,4,...t);const{width:l,height:c}=Qe(t);e.left=`${100*(t[0]-o)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*l/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof vs||(n.tabIndex=Ci);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof wo){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:o,height:h}=Qe(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,b=e.borderStyle.verticalCornerRadius;if(p>0||b>0){const v=`calc(${p}px * var(--scale-factor)) / calc(${b}px * var(--scale-factor))`;r.borderRadius=v}else if(this instanceof Ol){const v=`calc(${o}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=v}switch(e.borderStyle.style){case di.SOLID:r.borderStyle="solid";break;case di.DASHED:r.borderStyle="dashed";break;case di.BEVELED:K("Unimplemented border style: beveled");break;case di.INSET:K("Unimplemented border style: inset");break;case di.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=G.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const l=G.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(l[0]-d)/c}%`,r.top=`${100*(l[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*o/c}%`,r.height=`${100*h/u}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Qe(this.data.rect);let o,h;t%180===0?(o=100*n/s,h=100*r/i):(o=100*r/s,h=100*n/i),e.style.width=`${o}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],o=n.slice(1);i.target.style[s]=kl[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[s]:kl[`${r}_rgb`](o)})};return Z(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const o={detail:{[i]:n},target:t};r(o),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(p=>Math.fround(p));if(t.length===8){const[p,b,m,v]=t.subarray(2,6);if(i===p&&n===b&&e===m&&s===v)return}const{style:r}=this.container;let o;if(this.#e){const{borderColor:p,borderWidth:b}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${p}" stroke-width="${b}">`],this.container.classList.add("hasBorder")}const h=i-e,l=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,b=t.length;p<b;p+=8){const m=t[p],v=t[p+1],y=t[p+2],_=t[p+3],S=c.createElement("rect"),A=(y-e)/h,T=(n-v)/l,k=(m-y)/h,P=(v-_)/l;S.setAttribute("x",A),S.setAttribute("y",T),S.setAttribute("width",k),S.setAttribute("height",P),f.append(S),o?.push(`<rect vector-effect="non-scaling-stroke" x="${A}" y="${T}" width="${k}" height="${P}"/>`)}this.#e&&(o.push("</g></svg>')"),r.backgroundImage=o.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new wo({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){at("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:o}of i){if(n===-1||r===e)continue;const h=typeof o=="string"?o:null,l=document.querySelector(`[data-element-id="${r}"]`);if(l&&!bs.has(l)){K(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:l})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&bs.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class Pl extends yt{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){K('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,o=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&o.push(d)}else for(const c of Object.values(this._fieldObjects))o.push(...c);const h=this.annotationStorage,l=[];for(const c of o){const{id:u}=c;switch(l.push(u),c.type){case"text":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;h.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";h.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!bs.has(d)){K(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}}),!1}}}class mg extends yt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class vs extends yt{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Wt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":G.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||gg,n=t.style;let r;const o=2,h=l=>Math.round(10*l)/10;if(this.data.multiLine){const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o),c=Math.round(l/(Jr*i))||1,u=l/c;r=Math.min(i,h(u/Jr))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-o);r=Math.min(i,h(l/Jr))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=G.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class bg extends vs{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let o=i.formattedValue||this.data.textContent?.join(`
511
511
  `)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,""));const h={userValue:n,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=o??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",o??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),bs.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=Ci,this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",c=>{t.setValue(e,{value:c.target.value}),this.setPropertyOnSiblings(s,"value",c.target.value,"value"),h.formattedValue=null}),s.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue??"";s.value=h.userValue=u,h.formattedValue=null});let l=c=>{const{formattedValue:u}=h;u!=null&&(c.target.value=u),c.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",u=>{if(h.focused)return;const{target:d}=u;h.userValue&&(d.value=h.userValue),h.lastCommittedValue=d.value,h.commitKey=1,this.data.actions?.Focus||(h.focused=!0)}),s.addEventListener("updatefromsandbox",u=>{this.showElementAndHideCanvas(u.target);const d={value(f){h.userValue=f.detail.value??"",t.setValue(e,{value:h.userValue.toString()}),f.target.value=h.userValue},formattedValue(f){const{formattedValue:g}=f.detail;h.formattedValue=g,g!=null&&f.target!==document.activeElement&&(f.target.value=g),t.setValue(e,{formattedValue:g})},selRange(f){f.target.setSelectionRange(...f.detail.selRange)},charLimit:f=>{const{charLimit:g}=f.detail,{target:p}=f;if(g===0){p.removeAttribute("maxLength");return}p.setAttribute("maxLength",g);let b=h.userValue;!b||b.length<=g||(b=b.slice(0,g),p.value=h.userValue=b,t.setValue(e,{value:b}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:p.selectionStart,selEnd:p.selectionEnd}}))}};this._dispatchEventFromSandbox(d,u)}),s.addEventListener("keydown",u=>{h.commitKey=1;let d=-1;if(u.key==="Escape"?d=0:u.key==="Enter"&&!this.data.multiLine?d=2:u.key==="Tab"&&(h.commitKey=3),d===-1)return;const{value:f}=u.target;h.lastCommittedValue!==f&&(h.lastCommittedValue=f,h.userValue=f,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:f,willCommit:!0,commitKey:d,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}))});const c=l;l=null,s.addEventListener("blur",u=>{if(!h.focused||!u.relatedTarget)return;this.data.actions?.Blur||(h.focused=!1);const{value:d}=u.target;h.userValue=d,h.lastCommittedValue!==d&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:d,willCommit:!0,commitKey:h.commitKey,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}),c(u)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",u=>{h.lastCommittedValue=null;const{data:d,target:f}=u,{value:g,selectionStart:p,selectionEnd:b}=f;let m=p,v=b;switch(u.inputType){case"deleteWordBackward":{const y=g.substring(0,p).match(/\w*[^\w]*$/);y&&(m-=y[0].length);break}case"deleteWordForward":{const y=g.substring(p).match(/^[^\w]*\w*/);y&&(v+=y[0].length);break}case"deleteContentBackward":p===b&&(m-=1);break;case"deleteContentForward":p===b&&(v+=1);break}u.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:g,change:d||"",willCommit:!1,selStart:m,selEnd:v}})}),this._setEventListeners(s,h,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],u=>u.target.value)}if(l&&s.addEventListener("blur",l),this.data.comb){const u=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.letterSpacing=`calc(${u}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class vg extends vs{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class yg extends vs{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return bs.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=Ci,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s)){const c=h&&l.exportValue===e.exportValue;l.domElement&&(l.domElement.checked=c),t.setValue(l.id,{value:c})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue||"Off";r.target.checked=o===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const o={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class Ol extends vs{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(bs.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=Ci,n.addEventListener("change",r=>{const{name:o,checked:h}=r.target;for(const l of this._getElementsByName(o,s))t.setValue(l.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const o=e.defaultFieldValue;r.target.checked=o!=null&&o===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",o=>{const h={value:l=>{const c=r===l.detail.value;for(const u of this._getElementsByName(l.target.name)){const d=c&&u.id===s;u.domElement&&(u.domElement.checked=d),t.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(h,o)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class _g extends Pl{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class wg extends vs{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");bs.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=Ci;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue;for(const d of i.options)d.selected=d.value===u});for(const c of this.data.options){const u=document.createElement("option");u.textContent=c.displayValue,u.value=c.exportValue,s.value.includes(c.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let r=null;if(n){const c=document.createElement("option");c.value=" ",c.setAttribute("hidden",!0),c.setAttribute("selected",!0),i.prepend(c),r=()=>{c.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const o=c=>{const u=c?"value":"textContent",{options:d,multiple:f}=i;return f?Array.prototype.filter.call(d,g=>g.selected).map(g=>g[u]):d.selectedIndex===-1?null:d[d.selectedIndex][u]};let h=o(!1);const l=c=>{const u=c.target.options;return Array.prototype.map.call(u,d=>({displayValue:d.textContent,exportValue:d.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",c=>{const u={value(d){r?.();const f=d.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const p of i.options)p.selected=g.has(p.value);t.setValue(e,{value:o(!0)}),h=o(!1)},multipleSelection(d){i.multiple=!0},remove(d){const f=i.options,g=d.detail.remove;f[g].selected=!1,i.remove(g),f.length>0&&Array.prototype.findIndex.call(f,b=>b.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=o(!1)},insert(d){const{index:f,displayValue:g,exportValue:p}=d.detail.insert,b=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,b?b.before(m):i.append(m),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},items(d){const{items:f}=d.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:b}=g,m=document.createElement("option");m.textContent=p,m.value=b,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:o(!0),items:l(d)}),h=o(!1)},indices(d){const f=new Set(d.detail.indices);for(const g of d.target.options)g.selected=f.has(g.index);t.setValue(e,{value:o(!0)}),h=o(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,c)}),i.addEventListener("input",c=>{const u=o(!0),d=o(!1);t.setValue(e,{value:u}),c.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:d,changeEx:u,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],c=>c.target.value)):i.addEventListener("input",function(c){t.setValue(e,{value:o(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class wo extends yt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:yt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new xg({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${io}${s}`).join(",")),this.container}}class xg{#t=this.#E.bind(this);#e=this.#T.bind(this);#s=this.#k.bind(this);#i=this.#x.bind(this);#r=null;#n=null;#h=null;#a=null;#c=null;#l=null;#d=null;#u=!1;#f=null;#o=null;#g=null;#m=null;#p=null;#b=null;#_=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:o,parent:h,rect:l,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#h=r,this.#m=o,this.#l=h,this.#r=e,this.#g=l,this.#d=c,this.#c=s,this.#a=qh.toDateObject(n),this.trigger=s.flatMap(d=>d.getElementsToTriggerPopup());for(const d of this.trigger)d.addEventListener("click",this.#i),d.addEventListener("mouseenter",this.#s),d.addEventListener("mouseleave",this.#e),d.classList.add("popupTriggerArea");for(const d of s)d.container?.addEventListener("keydown",this.#t);this.#n.hidden=!0,u&&this.#x()}render(){if(this.#f)return;const t=this.#f=document.createElement("div");if(t.className="popup",this.#r){const n=t.style.outlineColor=G.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=G.makeHexColor(...this.#r.map(o=>Math.floor(.7*(255-o)+o)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=this.#p,t.append(e),this.#a){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#a.valueOf()})),e.append(n)}const i=this.#v;if(i)Ml.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#h);t.append(n)}this.#n.append(t)}get#v(){const t=this.#m,e=this.#h;return t?.str&&(!e?.str||e.str===t.str)&&this.#m.html||null}get#w(){return this.#v?.attributes?.style?.fontSize||0}get#S(){return this.#v?.attributes?.style?.color||null}#A(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#S,fontSize:this.#w?`calc(${this.#w}px * var(--scale-factor))`:""}};for(const n of t.split(`
512
- `))e.push({name:"span",value:n,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const o=i[n];s.append(document.createTextNode(o)),n<r-1&&s.append(document.createElement("br"))}return s}#E(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#u)&&this.#x()}updateEdited({rect:t,popupContent:e}){this.#b||={contentsObj:this.#h,richText:this.#m},t&&(this.#o=null),e&&(this.#m=this.#A(e),this.#h=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#b&&({contentsObj:this.#h,richText:this.#m}=this.#b,this.#b=null,this.#f?.remove(),this.#f=null,this.#o=null)}#M(){if(this.#o!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#l;let r=!!this.#d,o=r?this.#d:this.#g;for(const g of this.#c)if(!o||G.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const h=G.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),c=r?o[2]-o[0]+5:0,u=h[0]+c,d=h[1];this.#o=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#o[0]}%`,f.top=`${this.#o[1]}%`}#x(){this.#u=!this.#u,this.#u?(this.#k(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#T(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#k(){this.#f||this.render(),this.isVisible?this.#u&&this.#n.classList.add("focused"):(this.#M(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#T(){this.#n.classList.remove("focused"),!(this.#u||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#n.hidden=!0)}maybeShow(){this.#_&&(this.#f||this.#k(),this.#_=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class Dl extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=q.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Sg extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Cg extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ag extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Rl extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:r}=Qe(t),o=this.svgFactory.create(n,r,!0);let h=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];h.push(`${d},${f}`)}h=h.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",h),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Tg extends Rl{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Eg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class xo extends yt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?q.HIGHLIGHT:q.INK}#s(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:o,height:h}=this.#s(e,t),l=this.svgFactory.create(o,h,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let u=0,d=s.length;u<d;u++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[u].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,o=this.#e.length;r<o;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:o,height:h}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${h}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ll extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=q.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class kg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class Mg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class Pg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class Fl extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=q.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Og extends yt{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=Vt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Dg{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){this.div=t,this.#t=e,this.#e=s,this.#i=o||null,this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#r(t,e){const s=t.firstChild||t,i=s.id=`${io}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,o]of n)s.setAttribute(r,o);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;ms(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new _o,annotationStorage:t.annotationStorage||new uo,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const o=r.annotationType===Tt.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=Qe(r.rect);if(c<=0||u<=0)continue}n.data=r;const h=pg.create(n);if(!h.isRenderable)continue;if(!o&&r.popupRef){const c=i.get(r.popupRef);c?c.push(h):i.set(r.popupRef,[h])}const l=h.render();r.hidden&&(l.style.visibility="hidden"),await this.#r(l,r.id),h._isEditable&&(this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,ms(e,{rotation:t.rotation}),this.#n(),e.hidden=!1}#n(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const Vn=/\r\n?|\n/g;class Et extends W{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Et.prototype,e=n=>n.isEmpty(),s=Ze.TRANSLATE_SMALL,i=Ze.TRANSLATE_BIG;return Z(this,"_keyboardManager",new bi([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=q.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Et._defaultColor||W._defaultLineColor,this.#r=t.fontSize||Et._defaultFontSize}static initialize(t,e){W.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case tt.FREETEXT_SIZE:Et._defaultFontSize=e;break;case tt.FREETEXT_COLOR:Et._defaultColor=e;break}}updateParams(t,e){switch(t){case tt.FREETEXT_SIZE:this.#n(e);break;case tt.FREETEXT_COLOR:this.#h(e);break}}static get defaultPropertiesToUpdate(){return[[tt.FREETEXT_SIZE,Et._defaultFontSize],[tt.FREETEXT_COLOR,Et._defaultColor||W._defaultLineColor]]}get propertiesToUpdate(){return[[tt.FREETEXT_SIZE,this.#r],[tt.FREETEXT_COLOR,this.#t]]}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#c()},s=this.#r;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#h(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Et._internalPadding*t,-(Et._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(q.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;const t=this._uiManager.combinedSignal(this.#i);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#a(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(Et.#l(s)),e=s);return t.join(`
512
+ `))e.push({name:"span",value:n,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const o=i[n];s.append(document.createTextNode(o)),n<r-1&&s.append(document.createElement("br"))}return s}#E(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#u)&&this.#x()}updateEdited({rect:t,popupContent:e}){this.#b||={contentsObj:this.#h,richText:this.#m},t&&(this.#o=null),e&&(this.#m=this.#A(e),this.#h=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#b&&({contentsObj:this.#h,richText:this.#m}=this.#b,this.#b=null,this.#f?.remove(),this.#f=null,this.#o=null)}#M(){if(this.#o!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#l;let r=!!this.#d,o=r?this.#d:this.#g;for(const g of this.#c)if(!o||G.intersect(g.data.rect,o)!==null){o=g.data.rect,r=!0;break}const h=G.normalizeRect([o[0],t[3]-o[1]+t[1],o[2],t[3]-o[3]+t[1]]),c=r?o[2]-o[0]+5:0,u=h[0]+c,d=h[1];this.#o=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#o[0]}%`,f.top=`${this.#o[1]}%`}#x(){this.#u=!this.#u,this.#u?(this.#k(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#T(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#k(){this.#f||this.render(),this.isVisible?this.#u&&this.#n.classList.add("focused"):(this.#M(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#T(){this.#n.classList.remove("focused"),!(this.#u||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#n.hidden=!0)}maybeShow(){this.#_&&(this.#f||this.#k(),this.#_=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class Dl extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=q.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Sg extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Cg extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ag extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=Qe(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Rl extends yt{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:r}=Qe(t),o=this.svgFactory.create(n,r,!0);let h=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];h.push(`${d},${f}`)}h=h.join(" ");const l=this.#t=this.svgFactory.createElement(this.svgElementName);return l.setAttribute("points",h),l.setAttribute("stroke-width",s.width||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class Tg extends Rl{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Eg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class xo extends yt{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?q.HIGHLIGHT:q.INK}#s(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:o,height:h}=this.#s(e,t),l=this.svgFactory.create(o,h,!0),c=this.#t=this.svgFactory.createElement("svg:g");l.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let u=0,d=s.length;u<d;u++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[u].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(l),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,o=this.#e.length;r<o;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:o,height:h}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${o} ${h}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class Ll extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=q.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class kg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class Mg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class Pg extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class Fl extends yt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=q.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class Og extends yt{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=Wt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class Dg{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:o}){this.div=t,this.#t=e,this.#e=s,this.#i=o||null,this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#r(t,e){const s=t.firstChild||t,i=s.id=`${io}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,o]of n)s.setAttribute(r,o);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;ms(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new _o,annotationStorage:t.annotationStorage||new uo,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const o=r.annotationType===Tt.POPUP;if(o){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=Qe(r.rect);if(c<=0||u<=0)continue}n.data=r;const h=pg.create(n);if(!h.isRenderable)continue;if(!o&&r.popupRef){const c=i.get(r.popupRef);c?c.push(h):i.set(r.popupRef,[h])}const l=h.render();r.hidden&&(l.style.visibility="hidden"),await this.#r(l,r.id),h._isEditable&&(this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,ms(e,{rotation:t.rotation}),this.#n(),e.hidden=!1}#n(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const Vn=/\r\n?|\n/g;class Et extends W{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=Et.prototype,e=n=>n.isEmpty(),s=Ze.TRANSLATE_SMALL,i=Ze.TRANSLATE_BIG;return Z(this,"_keyboardManager",new bi([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=q.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||Et._defaultColor||W._defaultLineColor,this.#r=t.fontSize||Et._defaultFontSize}static initialize(t,e){W.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case tt.FREETEXT_SIZE:Et._defaultFontSize=e;break;case tt.FREETEXT_COLOR:Et._defaultColor=e;break}}updateParams(t,e){switch(t){case tt.FREETEXT_SIZE:this.#n(e);break;case tt.FREETEXT_COLOR:this.#h(e);break}}static get defaultPropertiesToUpdate(){return[[tt.FREETEXT_SIZE,Et._defaultFontSize],[tt.FREETEXT_COLOR,Et._defaultColor||W._defaultLineColor]]}get propertiesToUpdate(){return[[tt.FREETEXT_SIZE,this.#r],[tt.FREETEXT_COLOR,this.#t]]}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#c()},s=this.#r;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#h(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-Et._internalPadding*t,-(Et._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(q.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;const t=this._uiManager.combinedSignal(this.#i);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#a(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(Et.#l(s)),e=s);return t.join(`
513
513
  `)}#c(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,r=n.style.display,o=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=r,n.classList.toggle("hidden",o)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#e,e=this.#e=this.#a().trimEnd();if(t===e)return;const s=i=>{if(this.#e=i,!i){this.remove();return}this.#d(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){Et._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#s),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),In(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[o,h]=this.getInitialTranslation();[o,h]=this.pageTranslationToScreen(o,h);const[l,c]=this.pageDimensions,[u,d]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=t+(r[0]-u)/l,g=e+this.height-(r[1]-d)/c;break;case 90:f=t+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[h,-o];break;case 180:f=t-this.width+(r[0]-u)/l,g=e-(r[1]-d)/c,[o,h]=[-o,-h];break;case 270:f=t+(r[0]-u-this.height*c)/l,g=e+(r[1]-d-this.width*l)/c,[o,h]=[-h,o];break}this.setAt(f*i,g*n,o,h)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#d(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Vn,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=Et.#f(e.getData("text")||"").replaceAll(Vn,`
514
514
  `);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
515
515
  `)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:o,startOffset:h}=r,l=[],c=[];if(o.nodeType===Node.TEXT_NODE){const f=o.parentElement;if(c.push(o.nodeValue.slice(h).replaceAll(Vn,"")),f!==this.editorDiv){let g=l;for(const p of this.editorDiv.childNodes){if(p===f){g=c;continue}g.push(Et.#l(p))}}l.push(o.nodeValue.slice(0,h).replaceAll(Vn,""))}else if(o===this.editorDiv){let f=l,g=0;for(const p of this.editorDiv.childNodes)g++===h&&(f=c),f.push(Et.#l(p))}this.#e=`${l.join(`
@@ -517,4 +517,4 @@ void main() {
517
517
  `)}`,this.#d();const u=new Range;let d=l.reduce((f,g)=>f+g.length,0);for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const g=f.nodeValue.length;if(d<=g){u.setStart(f,d),u.setEnd(f,d);break}d-=g}n.removeAllRanges(),n.addRange(u)}#d(){if(this.editorDiv.replaceChildren(),!!this.#e)for(const t of this.#e.split(`
518
518
  `)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#u(){return this.#e.replaceAll(" "," ")}static#f(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof Dl){const{data:{defaultAppearanceData:{fontSize:r,fontColor:o},rect:h,rotation:l,id:c,popupRef:u},textContent:d,textPosition:f,parent:{page:{pageNumber:g}}}=t;if(!d||d.length===0)return null;i=t={annotationType:q.FREETEXT,color:Array.from(o),fontSize:r,value:d.join(`
519
519
  `),position:f,pageIndex:g-1,rect:h.slice(0),rotation:l,id:c,deleted:!1,popupRef:u}}const n=await super.deserialize(t,e,s);return n.#r=t.fontSize,n.#t=G.makeHexColor(...t.color),n.#e=Et.#f(t.value),n.annotationElementId=t.id||null,n._initialData=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=Et._internalPadding*this.parentScale,s=this.getRect(e,e),i=W._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:q.FREETEXT,color:i,fontSize:this.#r,value:this.#u(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#o(n)?null:(n.id=this.annotationElementId,n)}#o(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((r,o)=>r!==i[o])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,e.replaceChildren();for(const n of this.#e.split(`
520
- `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=Et._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class j{static PRECISION=1e-4;toSVGPath(){at("Abstract method `toSVGPath` must be implemented.")}get box(){at("Abstract getter `box` must be implemented.")}serialize(t,e){at("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class ys{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#h;#a;#c;#l;#d;#u;#f=[];static#o=8;static#g=2;static#m=ys.#o+ys.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#l=ys.#o*i,this.#c=ys.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#h+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#h+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#h=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const u=t-l,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#l,p=g/f,b=p*u,m=p*d;let v=o,y=h;o=l,h=c,l+=b,c+=m,this.#f?.push(t,e);const _=-m/g,S=b/g,A=_*this.#u,T=S*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+A,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+A-s)/n,(h+T-i)/r),this.#n.set([o-A,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-A-s)/n,(h-T-i)/r)),this.#n.set([v,y,o,h,l,c],6),!this.isEmpty()):(this.#n.set([v,y,o,h,l,c],6),Math.abs(Math.atan2(y-h,v-o)-Math.atan2(m,b))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,v,y]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((y+h)/2-i)/r),!0):([v,y,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,v,y]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#b();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#v(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#_(s),s.join(" ")}#b(){const[t,e,s,i]=this.#t,[n,r,o,h]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${o} ${h} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#v(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=this.#n.subarray(16,18),[h,l,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Il(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=h.length-2;u<d;u+=2)h[u]=(this.#f[u]-i)/r,h[u+1]=(this.#f[u+1]-n)/o;if(h[h.length-2]=(this.#h-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#w(h);const l=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){l[u]=l[u+1]=NaN;continue}l[u]=t[u],l[u+1]=t[u+1]}c=this.#A(l,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[u+d],l[c+1]=e[u+d+1],c+=2}return this.#S(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,c]=this.#p(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,o,h]=this.#t,[l,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class Il extends j{#t;#e=new Float32Array(4);#s;#i;#r;#n;#h;constructor(t,e,s,i,n,r){super(),this.#h=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#a(r);const[o,h,l,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/l,t[u+1]=(t[u+1]-h)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/l,e[u+1]=(e[u+1]-h)/c}toSVGPath(){const t=[`M${this.#h[4]} ${this.#h[5]}`];for(let e=6,s=this.#h.length;e<s;e+=6){if(isNaN(this.#h[e])){t.push(`L${this.#h[e+4]} ${this.#h[e+5]}`);continue}t.push(`C${this.#h[e]} ${this.#h[e+1]} ${this.#h[e+2]} ${this.#h[e+3]} ${this.#h[e+4]} ${this.#h[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=j._rescale(this.#h,t,i,r,-o),l=j._rescale(this.#r,t,i,r,-o);break;case 90:h=j._rescaleAndSwap(this.#h,t,e,r,o),l=j._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=j._rescale(this.#h,s,e,-r,o),l=j._rescale(this.#r,s,e,-r,o);break;case 270:h=j._rescaleAndSwap(this.#h,s,i,-r,-o),l=j._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#h;let s=e[4],i=e[5],n=s,r=i,o=s,h=i,l=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),o=Math.max(o,e[f+4]),h=Math.max(h,e[f+5]),c<e[f+5]?(l=e[f+4],c=e[f+5]):c===e[f+5]&&(l=u(l,e[f+4]));else{const p=G.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),o=Math.max(o,p[2]),h=Math.max(h,p[3]),c<p[3]?(l=p[2],c=p[3]):c===p[3]&&(l=u(l,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=o-n+2*this.#s,d[3]=h-r+2*this.#s,this.lastPoint=[l,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new ys(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,u=n*l,d=r*c,f=s*l+o,g=i*c+h,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let b=2;b<this.#r.length;b+=2)p.add({x:this.#r[b]*u+f,y:this.#r[b+1]*d+g});return p.getOutlines()}}class So{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,h=-1/0;const l=10**-4;for(const{x:b,y:m,width:v,height:y}of t){const _=Math.floor((b-e)/l)*l,S=Math.ceil((b+v+e)/l)*l,A=Math.floor((m-e)/l)*l,T=Math.ceil((m+y+e)/l)*l,k=[_,A,T,!0],P=[S,A,T,!1];this.#s.push(k,P),n=Math.min(n,_),r=Math.max(r,S),o=Math.min(o,A),h=Math.max(h,T)}const c=r-n+2*s,u=h-o+2*s,d=n-s,f=o-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const b of this.#s){const[m,v,y]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[2]=(y-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#h(e)):(this.#a(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,u]=r;s.delete(r);let d=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,h,l,c,u]=g,d!==o&&(n.push(d,f,o,f===h?h:l),d=o),f=f===h?l:h}n.push(d,f)}return new Rg(i,this.#t,this.#e)}#n(t){const e=this.#i;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#h([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#a([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let o=0;o<r;o++){const[h,l]=this.#i[o];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(l<=d||f<=h)){if(d>=h){if(f>l)n[c][1]=l;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class Rg extends j{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],o=e[n+1];r===s?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],o=s-t,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let u=0;u<l.length;u+=2)c[u]=t+l[u]*o,c[u+1]=i-l[u+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Co extends ys{newFreeDrawOutline(t,e,s,i,n,r){return new Lg(t,e,s,i,n,r)}}class Lg extends Il{newOutliner(t,e,s,i,n,r=0){return new Co(t,e,s,i,n,r)}}class he{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#h=null;#a;#c=null;#l=null;#d;static#u=null;static get _keyboardManager(){return Z(this,"_keyboardManager",new bi([[["Escape","mac+Escape"],he.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],he.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],he.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],he.prototype._moveToPrevious],[["Home","mac+Home"],he.prototype._moveToBeginning],[["End","mac+End"],he.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=tt.HIGHLIGHT_COLOR,this.#h=t):(this.#n=!0,this.#d=tt.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color||this.#l?.highlightColors.values().next().value||"#FFFF98",he.#u||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#l._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",ve,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#l.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",he.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#o.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#o(t,e){e.stopPropagation(),this.#a.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#o(e,t)}_moveToNext(t){if(!this.#b){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#b){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#b){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){he._keyboardManager.exec(this,t)}#m(t){if(this.#b){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#b){this.#h?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#l.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class _t extends W{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#h=null;#a=0;#c=null;#l=null;#d=null;#u=!1;#f=null;#o;#g=null;#m="";#p;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=q.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=_t.prototype;return Z(this,"_keyboardManager",new bi([[["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||_t._defaultColor,this.#p=t.thickness||_t._defaultThickness,this.#o=t.opacity||_t._defaultOpacity,this.#s=t.boxes||null,this.#b=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#v(t),this.#M()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#h=t.focusNode,this.#a=t.focusOffset,this.#_(),this.#M(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new So(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new So(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#v({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:_t.#x(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:_t.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=h*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=h*c/u;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){W.initialize(t,e),_t._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case tt.HIGHLIGHT_DEFAULT_COLOR:_t._defaultColor=e;break;case tt.HIGHLIGHT_THICKNESS:_t._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case tt.HIGHLIGHT_COLOR:this.#w(e);break;case tt.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[tt.HIGHLIGHT_DEFAULT_COLOR,_t._defaultColor],[tt.HIGHLIGHT_THICKNESS,_t._defaultThickness]]}get propertiesToUpdate(){return[[tt.HIGHLIGHT_COLOR,this.color||_t._defaultColor],[tt.HIGHLIGHT_THICKNESS,this.#p||_t._defaultThickness],[tt.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#o=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#o;this.addCommands({cmd:e.bind(this,t,_t._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new he({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#M(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#M(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#v({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#M(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#o},rootClass:{highlight:!0,free:this.#u},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=_t.#x(this.#l.box,t)):s=_t.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:_t.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),In(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){_t._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#h,this.#a)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#L(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let o=0;for(const{x:h,y:l,width:c,height:u}of n){const d=h*t+s,f=(1-l)*e+i;r[o]=r[o+4]=d,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=d+c*t,r[o+5]=r[o+7]=f-u*e,o+=8}return r}#I(t){return this.#l.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",ne,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ve,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new Co({x:i,y:n},[r,o,h,l],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof Ll){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:y,popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:q.HIGHLIGHT,color:Array.from(v),opacity:y,quadPoints:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof xo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:q.HIGHLIGHT,color:Array.from(v),thickness:y,inkLists:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=G.makeHexColor(...n),l.#o=h||1,o&&(l.#p=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[c,u]=l.pageDimensions,[d,f]=l.pageTranslation;if(r){const g=l.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});l.#_(),l.#M(),l.rotate(l.rotation)}else if(o){l.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new Co(p,[0,0,c,u],1,l.#p/2,!0,.001);for(let y=0,_=g.length;y<_;y+=2)p.x=g[y]-d,p.y=u-(g[y+1]-f),b.add(p);const{id:m,clipPathId:v}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:b.toSVGPath()}},!0,!0);l.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),l.#M()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=W._colorManager.convert(this.color),i={annotationType:q.HIGHLIGHT,color:s,opacity:this.#o,thickness:this.#p,quadPoints:this.#L(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class Fg{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){at("Not implemented")}}class X extends W{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#h=null;static#a=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#l(t),this.#f())}#l({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(X._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){at("Not implemented")}static get typesMap(){at("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(X.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=o=>{i.updateProperty(e,o);const h=this.#t.updateProperty(e,o);h&&this.#m(h),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#o([t,e,s,i]){const{parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#o(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[o,h]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(o/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/o)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){at("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(X.#h&&X.#h!==l)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=X.#i=new AbortController,g=t.combinedSignal(f);if(X.#n||=h,X.#h??=l,window.addEventListener("pointerup",p=>{X.#n===p.pointerId?this._endDraw(p):X.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{X.#n===p.pointerId?this._currentParent.endDrawingSession():X.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{X.#h===p.pointerType&&((X.#a||=new Set).add(p.pointerId),X.#s.isCancellable()&&(X.#s.removeLastElement(),X.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ve,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===X.#c&&ne(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),X.#s){t.drawLayer.updateProperties(this._currentDrawId,X.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),X.#s=this.createDrawerInstance(r,o,u,d,c),X.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(X.#r.toSVGProperties(),X.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(X.#c=-1,!X.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(X.#n===i){if(X.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,X.#s.add(e,s)),X.#c=t.timeStamp,ne(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,X.#s=null,X.#r=null,X.#h=null,X.#c=NaN),X.#i&&(X.#i.abort(),X.#i=null,X.#n=NaN,X.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,X.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=X.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:tt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(tt.DRAW_STEP),!X.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:X.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:X.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){at("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class Ig{#t=new Float64Array(6);#e;#s;#i;#r;#n;#h="";#a=0;#c=new Wn;#l;#d;constructor(t,e,s,i,n,r){this.#l=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const o=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:o,points:this.#n}],this.#t.set(o,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return j._normalizePoint(t,e,this.#l,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),o=t-n,h=e-r;return Math.hypot(this.#l*o,this.#d*h)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...j.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#l=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const o=this.#s.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#a=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#a=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#h="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#a=0,this.toSVGPath()}return{path:{d:this.#h}}}toSVGPath(){const t=j.svgRound(this.#e[4]),e=j.svgRound(this.#e[5]);if(this.#n.length===2)return this.#h=`${this.#h} M ${t} ${e} Z`,this.#h;if(this.#n.length<=6){const i=this.#h.lastIndexOf("M");this.#h=`${this.#h.slice(0,i)} M ${t} ${e}`,this.#a=6}if(this.#n.length===4){const i=j.svgRound(this.#e[10]),n=j.svgRound(this.#e[11]);return this.#h=`${this.#h} L ${i} ${n}`,this.#a=12,this.#h}const s=[];this.#a===0&&(s.push(`M ${t} ${e}`),this.#a=6);for(let i=this.#a,n=this.#e.length;i<n;i+=6){const[r,o,h,l,c,u]=this.#e.slice(i,i+6).map(j.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${u}`)}return this.#h+=s.join(" "),this.#a=this.#e.length,this.#h}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#h=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Wn extends j{#t;#e=0;#s;#i;#r;#n;#h;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#h=i,this.#a=n,this.#c=r,this.#s=o??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${j.svgRound(e[4])} ${j.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${j.svgRound(e[10])} ${j.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,h,l,c]=e.subarray(s,s+6).map(j.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,u]=this.#d();let d,f,g,p,b,m,v,y,_;switch(this.#a){case 0:_=j._rescale,d=t,f=e+i,g=s,p=-i,b=t+h*s,m=e+(1-l-u)*i,v=t+(h+c)*s,y=e+(1-l)*i;break;case 90:_=j._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+l*s,m=e+h*i,v=t+(l+u)*s,y=e+(h+c)*i;break;case 180:_=j._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-h-c)*s,m=e+l*i,v=t+(1-h)*s,y=e+(l+u)*i;break;case 270:_=j._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-l-u)*s,m=e+(1-h-c)*i,v=t+(1-l)*s,y=e+(1-h)*i;break}for(const{line:S,points:A}of this.#i)r.push(_(S,d,f,g,p,n?new Array(S.length):null)),o.push(_(A,d,f,g,p,n?new Array(A.length):null));return{lines:r,points:o,rect:[b,m,v,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let u,d,f,g,p;switch(h){case 0:p=j._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=j._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=j._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=j._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const v=m.length;if(v===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(v===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const y=new Float32Array(3*(v-2));r.push(y);let[_,S,A,T]=m.subarray(0,4);y.set([NaN,NaN,NaN,NaN,_,S],0);for(let k=4;k<v;k+=2){const P=m[k],B=m[k+1];y.set(j.createBezierPoints(_,S,A,T,P,B),(k-2)*3),[_,S,A,T]=[A,T,P,B]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(y=>y??NaN),u,d,f,g),points:p(o[m].map(y=>y??NaN),u,d,f,g)});const b=new Wn;return b.build(c,s,i,1,h,l,n),b}#l(t=this.#c){const e=this.#s+t/2*this.#h;return this.#a%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let o=4,h=i.length;o<h;o+=6){const[l,c]=i.subarray(o,o+2);t[0]=Math.min(t[0],l),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],l),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,u,d,f,g]=i.subarray(o,o+6);G.bezierBoundingBox(n,r,l,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#l();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#l();this.#c=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#h=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(j.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${j.svgRound(o)} ${j.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=j.PRECISION||Math.abs(c-r)<=j.PRECISION){const p=t+s/2-(o+l/2),b=e+i/2-(h+c/2);return{path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}const u=(s-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${j.svgRound(o)} ${j.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${j.svgRound(n)} ${j.svgRound(r)}) scale(${u} ${d}) translate(${j.svgRound(-n)} ${j.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=j.PRECISION||Math.abs(u-r)<=j.PRECISION){const b=t+s/2-(h+c/2),m=e+i/2-(l+u/2);for(const{line:v,points:y}of this.#i)j._translate(v,b,m,v),j._translate(y,b,m,y);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(h+n)+t+n,p=-f*(l+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:b,points:m}of this.#i)j._rescale(b,g,p,d,f,b),j._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)j._translate(l,o,h,l),j._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)j._rescale(u,o,h,l,c,u),j._rescale(d,o,h,l,c,d);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${j.svgRound(t[0])} ${j.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Ao extends Fg{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:W._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Ao(this.#t);return t.updateAll(this),t}}class To extends X{static _type="ink";static _editorType=q.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){W.initialize(t,e),this._defaultDrawingOptions=new Ao(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return Z(this,"typesMap",new Map([[tt.INK_THICKNESS,"stroke-width"],[tt.INK_COLOR,"stroke"],[tt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new Ig(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Wn.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof xo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:q.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.slice(0),rotation:h,id:l,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=To.getDefaultDrawingOptions({stroke:G.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":o}}=this,h={annotationType:q.INK,color:W._colorManager.convert(n),opacity:r,thickness:o,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?h:this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,o)=>r!==e[o])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class Eo extends W{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#h=null;#a=null;#c=!1;#l=!1;static _type="stamp";static _editorType=q.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){W.initialize(t,e)}static get supportedTypes(){return Z(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return Z(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(q.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#o()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#h){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,o=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=Eo.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#h?.remove(),this.#h=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#h===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#o():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#a!==null&&clearTimeout(this.#a);const t=200;this.#a=setTimeout(()=>{this.#a=null,this.#m()},t)}#o(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[o,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#h=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#l||(this.parent.addUndoableEditor(this),this.#l=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&l.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new ao;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const A=Math.min(e/i,e/n);h=Math.floor(i*A),l=Math.floor(n*A)}c=document.createElement("canvas");const d=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*r.sy);this.#c||(o=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",b="#42414d");const m=15,v=m*r.sx,y=m*r.sy,_=new OffscreenCanvas(v*2,y*2),S=_.getContext("2d");S.fillStyle=p,S.fillRect(0,0,v*2,y*2),S.fillStyle=b,S.fillRect(0,0,v,y),S.fillRect(v,y,v,y),g.fillStyle=g.createPattern(_,"repeat"),g.fillRect(0,0,d,f),g.drawImage(o,0,0,o.width,o.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&o.width<t&&o.height<t)d=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);d=Math.floor(i*b),f=Math.floor(n*b),this.#c||(o=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:h,height:l,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,o=this.#t;for(;n>2*t||r>2*e;){const h=n,l=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(o,0,0,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new ao,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#h;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#c?this.#t:this.#g(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}getImageForAltText(){return this.#h}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*js.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*js.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof Fl){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:y,parent:{page:{pageNumber:_}}}=t,S=y.querySelector("canvas"),A=s.imageManager.getFromCanvas(y.id,S);S.remove();const T=(await e._structTree.getAriaAttributes(`${io}${b}`))?.get("aria-label")||"";i=t={annotationType:q.STAMP,bitmapId:A.id,bitmap:A.bitmap,pageIndex:_-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:T},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:u}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,o&&(n.#t=o)):n.#i=h,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#l=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:q.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const o=this.#b(s);if(o.isSame)return null;o.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#p(!1))}return s}#b(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class Ve{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#h=!1;#a=!1;#c=!1;#l=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([Et,To,Eo,_t].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const u=[...Ve.#g.values()];if(!Ve._initialized){Ve._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#o=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#u=h,this.drawLayer=o,this._structTree=i,this.#o.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===q.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case q.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case q.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case q.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of Ve.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}cleanUndoStack(t){this.#o.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#o.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#o.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#a=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#o.isDeletedAnnotationElement(r))continue;let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#o.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#v(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of Ve.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#a=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#o.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#o.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Vt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),_t.startHighlighting(this,this.#o.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#o._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#o.combinedSignal(this.#i);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#o.isDeletedAnnotationElement(e)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#o.addDeletedAnnotationElement(t.annotationElementId),W.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#o.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#o.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#o._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#o.getId()}get#p(){return Ve.#g.get(this.#o.getMode())}combinedSignal(t){return this.#o.combinedSignal(t)}#b(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#o,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await Ve.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#o,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[u,d]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:e}=Vt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#h&&(this.#h=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#o.getMode()===q.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===q.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:e}=Vt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#h=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#o.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#l){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#o.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#o,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#l?(this.#o.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#o.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#o.removeLayer(this)}#v(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,ms(this.div,t);for(const e of this.#o.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#v();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,ms(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#o.viewParameters.realScale}}class Xt{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return Z(this,"_svgFactory",new _o)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=Xt._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#h(t,e){const s=Xt._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=Xt._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#a(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=Xt._svgFactory.createElement("defs");n.append(r);const o=Xt._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const l=s?this.#h(r,h):null,c=Xt._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=Xt._svgFactory.createElement("defs");i.append(n);const r=Xt._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const u=Xt._svgFactory.createElement("mask");n.append(u),h=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",h),u.setAttribute("maskUnits","objectBoundingBox");const d=Xt._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=Xt._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=Xt._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,o=typeof t=="number"?this.#s.get(t):t;if(o){if(s&&this.#a(o,s),i&&Xt.#r(o,i),n){const{classList:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:So},Y.AbortException,Y.AnnotationEditorLayer,Y.AnnotationEditorParamsType,Y.AnnotationEditorType,Y.AnnotationEditorUIManager,Y.AnnotationLayer,Y.AnnotationMode,Y.ColorPicker,Y.DOMSVGFactory,Y.DrawLayer,Y.FeatureTest;var Ng=Y.GlobalWorkerOptions;Y.ImageKind,Y.InvalidPDFException,Y.MissingPDFException,Y.OPS,Y.OutputScale,Y.PDFDataRangeTransport,Y.PDFDateString,Y.PDFWorker,Y.PasswordResponses,Y.PermissionFlag,Y.PixelsPerInch,Y.RenderingCancelledException,Y.TextLayer,Y.TouchManager,Y.UnexpectedResponseException,Y.Util,Y.VerbosityLevel,Y.XfaLayer,Y.build,Y.createValidAbsoluteUrl,Y.fetchData;var jg=Y.getDocument;Y.getFilenameFromUrl,Y.getPdfFilenameFromUrl,Y.getXfaPageViewport,Y.isDataScheme,Y.isPdfFile,Y.noContextMenu,Y.normalizeUnicode,Y.setLayerDimensions,Y.shadow,Y.stopEvent;var Bg=Y.version;let Nl=null;function Hg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function zg(){const a=Nl??Hg();return Nl=a,a/72}function Gg(a,t=500){if(typeof a!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,a.apply(this,s)},t)}}function Vg(a){return a.arrayBuffer?a.arrayBuffer():new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>{const i=s.result;if(!(i instanceof ArrayBuffer)){e(new Error("Failed to read file as ArrayBuffer."));return}t(i)}),s.addEventListener("error",e),s.readAsArrayBuffer(a)})}jl()||(Ng.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Bg}/pdf.worker.min.mjs`);function jl(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"}catch{return!1}}async function Wg({page:a,data:t,scale:e,password:s},i){const n=zg()/window.devicePixelRatio,r=await Vg(t);if(jl()){const o=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-DawqtvLM.js").href:new URL("assets/pdfjs.worker-DawqtvLM.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:mt&&mt.tagName.toUpperCase()==="SCRIPT"&&mt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return o.postMessage({data:r,password:s,id:i,page:a,units:n,scale:e}),await new Promise(l=>{o.addEventListener("message",c=>{if(c.data.status!=="success")return;const{bitmap:u,width:d,height:f,pages:g}=c.data;if(u){const p=document.createElement("canvas"),b=p.getContext("bitmaprenderer");p.width=d,p.height=f,b?.transferFromImageBitmap(u),l({pages:g,canvas:p})}else l({pages:g,canvas:null})})})}else{const o=await jg({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),u=document.createElement("canvas"),f={canvasContext:u.getContext("2d"),viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),l.render(f).promise.then(()=>({canvas:u,pages:h}))}}const Ut=new Map;function Xg(a){const t=new jr(a);return Ut.set(a,t),t}function Ug(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Yg({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await Td(a),n=s.filter(o=>o!==null),r=Vu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function $g(a,t){if(!Ut.get(a))return;const s=1/3,i=ep(t,s);Hl(a,i,s)}async function qg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Bl(t,{data:a}),{...i,pages:1}}async function Bl(a,{data:t,scale:e=.5}){if(!Ut.get(a))return;const i=URL.createObjectURL(t),n=await Dt.fromURL(i);n.scale(e),Hl(a,n,e),URL.revokeObjectURL(i)}function Hl(a,t,e){const s=Ut.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Kg(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function Jg(a,t,e){!e||!a||(e.scale(1/t),Kg(a,e))}function Zg(a,t){if(!a)return;const e=a._cornerSize||6;a.borderScaleFactor=1/t,a.cornerSize=e*(1/t),a.touchCornerSize=e*4*(1/t),a.setCoords()}function Qg(a){const t=Ut.get(a);t&&(t.discardActiveObject(),t.renderAll())}function tp(a){const t=Ut.get(a);t&&(t.clear(),Ut.delete(a))}function ep(a,t){return new Dt(a,{scaleX:t,scaleY:t})}function ko(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function zl(a,t,e){const s=a.type;return{"application/pdf":sp,"image/png":Vl,"image/jpeg":Vl}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function sp(a,t,e){const s=Ug(a),i=await Gl({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Gl(a,t){return Wg(a,t).then(({canvas:e,pages:s})=>(e&&t&&$g(t,e),s))}async function Vl(a,t,e){return await qg(a,e)}function ip(a,t){const e=Ut.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof ee?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function np(a,t){const e=Ut.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(ac);i instanceof ee?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),ko(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function rp(a){const t=Ut.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof ee?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Wl(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{},h=J.useRef(null),l=J.useRef(null),c=J.useRef(1),u=J.useRef({...oc});function d(){if(!t||Ut.has(t))return;const O=Xg(t);return O.on("selection:created",D=>{if(r?.(D),D.selected.length<=1)return;const z=O.getActiveObject();z&&(l.current=z,e?.value&&l.current.set(e.value),l.current._cornerSize=l.current.cornerSize,S(c.current))}),O.on("selection:cleared",D=>{o?.(D),T(O)}),s&&O.on("mouse:down",s),i&&O.on("mouse:move",i),n&&O.on("mouse:up",n),O}function f(O,D){return zl(O,D,t)}function g(O){return Gl(O,t)}function p({data:O,scale:D=.5}){return Bl(t,{data:O,scale:D})}async function b(O,D,z){const M=Ut.get(t);if(!M)return;const R=await Dt.fromURL(O,{},{...ic,...D});ko(R,z),M.add(R),v(M,R),M.setActiveObject(R)}function m(O,D,z){const M=Ut.get(t);if(!M)return;const R=new Ot(O,{...nc,...D});ko(R,z),M.add(R),v(M,R),M.setActiveObject(R)}function v(O,D){D.on("selected",z=>y({canvas:O,target:z.target})),D.on("modified",z=>y({canvas:O,target:z.target})),D.on("scaling",()=>T(O)),D.on("moving",()=>T(O)),D.on("rotating",()=>T(O)),D._cornerSize=D._cornerSize??D.cornerSize}async function y({canvas:O,target:D,stroke:z=u.current.stroke,uuid:M=Date.now()}){if(O.getActiveObjects().length>1||h.current?.stroke===`${z}-${M}`)return;const U=await Yg(u.current,M,z);T(O),h.current=U,l.current=D,_(O,D,M),S(c.current,!0),U&&O.add(U)}function _(O,D,z){h.current&&(h.current.on("selected",()=>{O.remove(D),T(O)}),h.current.on("mouseover",()=>{y({canvas:O,target:D,stroke:u.current.hoverStroke,uuid:z})}),h.current.on("mouseout",()=>{y({canvas:O,target:D,stroke:u.current.stroke,uuid:z})}))}function S(O,D=!1){const z=Ut.get(t);c.current=O,z&&(Zg(l.current,O),Jg(l.current,O,h.current),!D&&z.renderAll())}function A(O){if(!O)return;u.current={...u.current,...O};const D=Ut.get(t);!h||!l.current||!D||y({target:l.current,canvas:D})}function T(O){l.current=null,h.current&&(O.remove(h.current),h.current=null)}function k(){Qg(t)}function P(){tp(t)}function B(O){ip(t,O)}function F(){return np(t,v)}function I(){rp(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:k,deleteCanvas:P,scaleFabric:S,setCloseSvgOptions:A,setActiveFabric:B,copyActiveFabric:F,deleteActiveFabric:I}}function op(a){const t=J.useRef(0),e=Gg(()=>{t.current!==window.innerWidth&&(t.current=window.innerWidth,a())});J.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const ap=J.forwardRef(hp);function hp({file:a,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:o=!1,password:h,dropTextOptions:l,dropImageOptions:c,closeSvgOptions:u,selectionOptions:d,manualReload:f,onLoaded:g,onReload:p,onPointerDown:b,onPointerMove:m,onPointerUp:v,onSelectionCreated:y,onSelectionCleared:_},S){const A=J.useRef(null),T=`${e}-${t-1}`,k=J.useMemo(()=>s*n,[s,n]),P=J.useMemo(()=>({...rc,...d}),[d]),{createCanvas:B,specifyPage:F,addFabric:I,addTextFabric:O,renderImage:D,clearActive:z,deleteCanvas:M,scaleFabric:R,setActiveFabric:U,setCloseSvgOptions:ht,copyActiveFabric:dt,deleteActiveFabric:E}=Wl({id:T,selectionOptions:P,pointerDown:b,pointerMove:m,pointerUp:v,selectionCreated:y,selectionCleared:_});op(rt);async function H(){globalThis.requestAnimationFrame(async()=>{if(B(),a.data?.type.startsWith("image/")){D({data:a.data,scale:i/3}),g?.();return}const N=a.canvas?.[t-1]??a.data;N&&await F({page:t,data:N,scale:i,password:h}),g?.()})}function V(N){if(N.preventDefault(),N.stopPropagation(),!o||!N.dataTransfer)return;const{dataTransfer:ft,nativeEvent:It}=N,{offsetX:Zt,offsetY:lp}=It,Xl=ft.getData("text/plain"),Ul=ft.getData("text/uri-list"),Yl=ft.getData("custom/offset"),$l=Yl?JSON.parse(Yl):null,ql={top:lp,left:Zt},Kl={x:$l?.offsetX??0,y:$l?.offsetY??0};Ul?Q(Ul,ql,Kl):Xl&&kt(Xl,ql,Kl)}function Q(N,ft,It){I(N,{...c,...ft},It)}function kt(N,ft,It){O(N,{...l,...ft},It)}function rt(){f||H(),p?.()}return J.useImperativeHandle(S,()=>({reload:H,addImage:Q,addText:kt,clearActive:z,deleteCanvas:M,setActiveFabric:U,copyActiveFabric:dt,deleteActiveFabric:E,canvasRef:A})),J.useEffect(()=>{rt()},[i,t,a,h]),J.useEffect(()=>{R(k)},[k]),J.useEffect(()=>{ht(u)},[u]),J.useEffect(()=>()=>M(),[]),Ro.jsx("div",{style:{transform:`scale(${k})`},onDragOver:N=>N.preventDefault(),onDragEnter:N=>N.preventDefault(),onDrop:V,children:Ro.jsx("canvas",{id:T,ref:A,className:r})})}st.default=ap,st.loadFile=zl,st.useFabric=Wl,Object.defineProperties(st,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
520
+ `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=Et._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class j{static PRECISION=1e-4;toSVGPath(){at("Abstract method `toSVGPath` must be implemented.")}get box(){at("Abstract getter `box` must be implemented.")}serialize(t,e){at("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o]*i,r[o+1]=s+t[o+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let o=0,h=t.length;o<h;o+=2)r[o]=e+t[o+1]*i,r[o+1]=s+t[o]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class ys{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#h;#a;#c;#l;#d;#u;#f=[];static#o=8;static#g=2;static#m=ys.#o+ys.#g;constructor({x:t,y:e},s,i,n,r,o=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=o,this.#l=ys.#o*i,this.#c=ys.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#h+(t[0]-e[0])/2-s)/n,(this.#a+(t[1]-e[1])/2-i)/r,(this.#h+(e[0]-t[0])/2-s)/n,(this.#a+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#h=t,this.#a=e;const[s,i,n,r]=this.#t;let[o,h,l,c]=this.#n.subarray(8,12);const u=t-l,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#l,p=g/f,b=p*u,m=p*d;let v=o,y=h;o=l,h=c,l+=b,c+=m,this.#f?.push(t,e);const _=-m/g,S=b/g,A=_*this.#u,T=S*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([l+A,c+T],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([l-A,c-T],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([o+A,h+T],2),this.#r.push(NaN,NaN,NaN,NaN,(o+A-s)/n,(h+T-i)/r),this.#n.set([o-A,h-T],14),this.#e.push(NaN,NaN,NaN,NaN,(o-A-s)/n,(h-T-i)/r)),this.#n.set([v,y,o,h,l,c],6),!this.isEmpty()):(this.#n.set([v,y,o,h,l,c],6),Math.abs(Math.atan2(y-h,v-o)-Math.atan2(m,b))<Math.PI/2?([o,h,l,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((o+l)/2-s)/n,((h+c)/2-i)/r),[o,h,v,y]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((v+o)/2-s)/n,((y+h)/2-i)/r),!0):([v,y,o,h,l,c]=this.#n.subarray(0,6),this.#r.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),[l,c,o,h,v,y]=this.#n.subarray(12,18),this.#e.push(((v+5*o)/6-s)/n,((y+5*h)/6-i)/r,((5*o+l)/6-s)/n,((5*h+c)/6-i)/r,((o+l)/2-s)/n,((h+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#b();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#v(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#_(s),s.join(" ")}#b(){const[t,e,s,i]=this.#t,[n,r,o,h]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${o} ${h} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#v(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),o=this.#n.subarray(16,18),[h,l,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${l} L${c} ${u} L${(o[0]-e)/i} ${(o[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new Il(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,o]=this.#t,h=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=h.length-2;u<d;u+=2)h[u]=(this.#f[u]-i)/r,h[u+1]=(this.#f[u+1]-n)/o;if(h[h.length-2]=(this.#h-i)/r,h[h.length-1]=(this.#a-n)/o,isNaN(s[6])&&!this.isEmpty())return this.#w(h);const l=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){l[u]=l[u+1]=NaN;continue}l[u]=t[u],l[u+1]=t[u+1]}c=this.#A(l,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){l[c]=l[c+1]=NaN,c+=2;continue}l[c]=e[u+d],l[c+1]=e[u+d+1],c+=2}return this.#S(l,c),this.newFreeDrawOutline(l,h,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[o,h,l,c]=this.#p(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,o,h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,o,h]=this.#t,[l,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/o,(s[1]-r)/h,NaN,NaN,NaN,NaN,l,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/o,(i[1]-r)/h],e),e+=24}}class Il extends j{#t;#e=new Float32Array(4);#s;#i;#r;#n;#h;constructor(t,e,s,i,n,r){super(),this.#h=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#a(r);const[o,h,l,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-o)/l,t[u+1]=(t[u+1]-h)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-o)/l,e[u+1]=(e[u+1]-h)/c}toSVGPath(){const t=[`M${this.#h[4]} ${this.#h[5]}`];for(let e=6,s=this.#h.length;e<s;e+=6){if(isNaN(this.#h[e])){t.push(`L${this.#h[e+4]} ${this.#h[e+5]}`);continue}t.push(`C${this.#h[e]} ${this.#h[e+1]} ${this.#h[e+2]} ${this.#h[e+3]} ${this.#h[e+4]} ${this.#h[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,o=i-e;let h,l;switch(n){case 0:h=j._rescale(this.#h,t,i,r,-o),l=j._rescale(this.#r,t,i,r,-o);break;case 90:h=j._rescaleAndSwap(this.#h,t,e,r,o),l=j._rescaleAndSwap(this.#r,t,e,r,o);break;case 180:h=j._rescale(this.#h,s,e,-r,o),l=j._rescale(this.#r,s,e,-r,o);break;case 270:h=j._rescaleAndSwap(this.#h,s,i,-r,-o),l=j._rescaleAndSwap(this.#r,s,i,-r,-o);break}return{outline:Array.from(h),points:[Array.from(l)]}}#a(t){const e=this.#h;let s=e[4],i=e[5],n=s,r=i,o=s,h=i,l=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),o=Math.max(o,e[f+4]),h=Math.max(h,e[f+5]),c<e[f+5]?(l=e[f+4],c=e[f+5]):c===e[f+5]&&(l=u(l,e[f+4]));else{const p=G.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),o=Math.max(o,p[2]),h=Math.max(h,p[3]),c<p[3]?(l=p[2],c=p[3]):c===p[3]&&(l=u(l,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=o-n+2*this.#s,d[3]=h-r+2*this.#s,this.lastPoint=[l,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new ys(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[o,h,l,c]=this.#t,u=n*l,d=r*c,f=s*l+o,g=i*c+h,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let b=2;b<this.#r.length;b+=2)p.add({x:this.#r[b]*u+f,y:this.#r[b+1]*d+g});return p.getOutlines()}}class So{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,o=1/0,h=-1/0;const l=10**-4;for(const{x:b,y:m,width:v,height:y}of t){const _=Math.floor((b-e)/l)*l,S=Math.ceil((b+v+e)/l)*l,A=Math.floor((m-e)/l)*l,T=Math.ceil((m+y+e)/l)*l,k=[_,A,T,!0],P=[S,A,T,!1];this.#s.push(k,P),n=Math.min(n,_),r=Math.max(r,S),o=Math.min(o,A),h=Math.max(h,T)}const c=r-n+2*s,u=h-o+2*s,d=n-s,f=o-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const b of this.#s){const[m,v,y]=b;b[0]=(m-d)/c,b[1]=(v-f)/u,b[2]=(y-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#h(e)):(this.#a(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[o,h,l]=r;e.push([o,h,r],[o,l,r])}e.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=e.length;r<o;r+=2){const h=e[r][2],l=e[r+1][2];h.push(l),l.push(h),s.add(h),s.add(l)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[o,h,l,c,u]=r;s.delete(r);let d=o,f=h;for(n=[o,l],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[o,h,l,c,u]=g,d!==o&&(n.push(d,f,o,f===h?h:l),d=o),f=f===h?l:h}n.push(d,f)}return new Rg(i,this.#t,this.#e)}#n(t){const e=this.#i;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#h([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#a([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let o=0;o<r;o++){const[h,l]=this.#i[o];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(l<=d||f<=h)){if(d>=h){if(f>l)n[c][1]=l;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=h,f>l&&n.push([e,l,f])}}}return n}}class Rg extends j{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],o=e[n+1];r===s?(t.push(`V${o}`),i=o):o===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],o=s-t,h=i-e;for(const l of this.#e){const c=new Array(l.length);for(let u=0;u<l.length;u+=2)c[u]=t+l[u]*o,c[u+1]=i-l[u+1]*h;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Co extends ys{newFreeDrawOutline(t,e,s,i,n,r){return new Lg(t,e,s,i,n,r)}}class Lg extends Il{newOutliner(t,e,s,i,n,r=0){return new Co(t,e,s,i,n,r)}}class he{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#h=null;#a;#c=null;#l=null;#d;static#u=null;static get _keyboardManager(){return Z(this,"_keyboardManager",new bi([[["Escape","mac+Escape"],he.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],he.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],he.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],he.prototype._moveToPrevious],[["Home","mac+Home"],he.prototype._moveToBeginning],[["End","mac+End"],he.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=tt.HIGHLIGHT_COLOR,this.#h=t):(this.#n=!0,this.#d=tt.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||e,this.#a=this.#l._eventBus,this.#s=t?.color||this.#l?.highlightColors.values().next().value||"#FFFF98",he.#u||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#l._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#l._signal;t.addEventListener("contextmenu",ve,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#l.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",he.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#o.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#o(t,e){e.stopPropagation(),this.#a.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#o(e,t)}_moveToNext(t){if(!this.#b){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#b){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#b){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){he._keyboardManager.exec(this,t)}#m(t){if(this.#b){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#b){this.#h?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#l.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class _t extends W{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#h=null;#a=0;#c=null;#l=null;#d=null;#u=!1;#f=null;#o;#g=null;#m="";#p;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=q.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=_t.prototype;return Z(this,"_keyboardManager",new bi([[["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||_t._defaultColor,this.#p=t.thickness||_t._defaultThickness,this.#o=t.opacity||_t._defaultOpacity,this.#s=t.boxes||null,this.#b=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#v(t),this.#M()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#h=t.focusNode,this.#a=t.focusOffset,this.#_(),this.#M(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#b}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new So(this.#s,.001);this.#l=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;const e=new So(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#v({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#l=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:_t.#x(this.#l.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:_t.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,o,h]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=o,this.height=h;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=o*u/c,this.height=h*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=o,this.height=h;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=o*u/c,this.height=h*c/u;break}}const{lastPoint:l}=this.#n;this.#f=[(l[0]-n)/o,(l[1]-r)/h]}static initialize(t,e){W.initialize(t,e),_t._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case tt.HIGHLIGHT_DEFAULT_COLOR:_t._defaultColor=e;break;case tt.HIGHLIGHT_THICKNESS:_t._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case tt.HIGHLIGHT_COLOR:this.#w(e);break;case tt.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[tt.HIGHLIGHT_DEFAULT_COLOR,_t._defaultColor],[tt.HIGHLIGHT_THICKNESS,_t._defaultThickness]]}get propertiesToUpdate(){return[[tt.HIGHLIGHT_COLOR,this.color||_t._defaultColor],[tt.HIGHLIGHT_THICKNESS,this.#p||_t._defaultThickness],[tt.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#o=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#o;this.addCommands({cmd:e.bind(this,t,_t._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:tt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new he({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#M(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#M(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#v({highlightOutlines:this.#l.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#M(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#l.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#o},rootClass:{highlight:!0,free:this.#u},path:{d:this.#l.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=_t.#x(this.#l.box,t)):s=_t.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:_t.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),In(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){_t._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#h,this.#a)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#L(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let o=0;for(const{x:h,y:l,width:c,height:u}of n){const d=h*t+s,f=(1-l)*e+i;r[o]=r[o+4]=d,r[o+1]=r[o+3]=f,r[o+2]=r[o+6]=d+c*t,r[o+5]=r[o+7]=f-u*e,o+=8}return r}#I(t){return this.#l.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:o,width:h,height:l}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",ne,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",ve,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new Co({x:i,y:n},[r,o,h,l],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof Ll){const{data:{quadPoints:g,rect:p,rotation:b,id:m,color:v,opacity:y,popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:q.HIGHLIGHT,color:Array.from(v),opacity:y,quadPoints:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}else if(t instanceof xo){const{data:{inkLists:g,rect:p,rotation:b,id:m,color:v,borderStyle:{rawWidth:y},popupRef:_},parent:{page:{pageNumber:S}}}=t;i=t={annotationType:q.HIGHLIGHT,color:Array.from(v),thickness:y,inkLists:g,boxes:null,pageIndex:S-1,rect:p.slice(0),rotation:b,id:m,deleted:!1,popupRef:_}}const{color:n,quadPoints:r,inkLists:o,opacity:h}=t,l=await super.deserialize(t,e,s);l.color=G.makeHexColor(...n),l.#o=h||1,o&&(l.#p=t.thickness),l.annotationElementId=t.id||null,l._initialData=i;const[c,u]=l.pageDimensions,[d,f]=l.pageTranslation;if(r){const g=l.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});l.#_(),l.#M(),l.rotate(l.rotation)}else if(o){l.#u=!0;const g=o[0],p={x:g[0]-d,y:u-(g[1]-f)},b=new Co(p,[0,0,c,u],1,l.#p/2,!0,.001);for(let y=0,_=g.length;y<_;y+=2)p.x=g[y]-d,p.y=u-(g[y+1]-f),b.add(p);const{id:m,clipPathId:v}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:l.color,"fill-opacity":l._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:b.toSVGPath()}},!0,!0);l.#v({highlightOutlines:b.getOutlines(),highlightId:m,clipPathId:v}),l.#M()}return l}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=W._colorManager.convert(this.color),i={annotationType:q.HIGHLIGHT,color:s,opacity:this.#o,thickness:this.#p,quadPoints:this.#L(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class Fg{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){at("Not implemented")}}class X extends W{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#h=null;static#a=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#l(t),this.#f())}#l({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(X._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){at("Not implemented")}static get typesMap(){at("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(X.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=o=>{i.updateProperty(e,o);const h=this.#t.updateProperty(e,o);h&&this.#m(h),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#o([t,e,s,i]){const{parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:o}=this;switch(o){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#o(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[o,h]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(o/h),i*(h/o),s*(o/h)];case 5:return[1-e,t,s*(o/h),i*(h/o)];case 6:return[1-t-i*(h/o),1-e,i*(h/o),s*(o/h)];case 7:return[e-s*(o/h),1-t-i*(h/o),s*(o/h),i*(h/o)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(h/o),e,i*(h/o),s*(o/h)];case 13:return[1-e-s*(o/h),t-i*(h/o),s*(o/h),i*(h/o)];case 14:return[1-t,1-e-s*(o/h),i*(h/o),s*(o/h)];case 15:return[e,1-t,s*(o/h),i*(h/o)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,X._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){at("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:o,pointerId:h,pointerType:l}=i;if(X.#h&&X.#h!==l)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=X.#i=new AbortController,g=t.combinedSignal(f);if(X.#n||=h,X.#h??=l,window.addEventListener("pointerup",p=>{X.#n===p.pointerId?this._endDraw(p):X.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{X.#n===p.pointerId?this._currentParent.endDrawingSession():X.#a?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{X.#h===p.pointerType&&((X.#a||=new Set).add(p.pointerId),X.#s.isCancellable()&&(X.#s.removeLastElement(),X.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",ve,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===X.#c&&ne(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),X.#s){t.drawLayer.updateProperties(this._currentDrawId,X.#s.startNew(r,o,u,d,c));return}e.updateUIForDefaultProperties(this),X.#s=this.createDrawerInstance(r,o,u,d,c),X.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(X.#r.toSVGProperties(),X.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(X.#c=-1,!X.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(X.#n===i){if(X.#a?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,X.#s.add(e,s)),X.#c=t.timeStamp,ne(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,X.#s=null,X.#r=null,X.#h=null,X.#c=NaN),X.#i&&(X.#i.abort(),X.#i=null,X.#n=NaN,X.#a=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,X.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=X.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:tt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(tt.DRAW_STEP),!X.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:X.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:X.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){at("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:o}}=e.viewport,h=this.deserializeDraw(r,o,i,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,s);return l.createDrawingOptions(t),l.#l({drawOutlines:h}),l.#f(),l.onScaleChanging(),l.rotate(),l}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class Ig{#t=new Float64Array(6);#e;#s;#i;#r;#n;#h="";#a=0;#c=new Wn;#l;#d;constructor(t,e,s,i,n,r){this.#l=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const o=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:o,points:this.#n}],this.#t.set(o,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return j._normalizePoint(t,e,this.#l,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),o=t-n,h=e-r;return Math.hypot(this.#l*o,this.#d*h)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...j.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#l=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const o=this.#s.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#a=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#a=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#h="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#a=0,this.toSVGPath()}return{path:{d:this.#h}}}toSVGPath(){const t=j.svgRound(this.#e[4]),e=j.svgRound(this.#e[5]);if(this.#n.length===2)return this.#h=`${this.#h} M ${t} ${e} Z`,this.#h;if(this.#n.length<=6){const i=this.#h.lastIndexOf("M");this.#h=`${this.#h.slice(0,i)} M ${t} ${e}`,this.#a=6}if(this.#n.length===4){const i=j.svgRound(this.#e[10]),n=j.svgRound(this.#e[11]);return this.#h=`${this.#h} L ${i} ${n}`,this.#a=12,this.#h}const s=[];this.#a===0&&(s.push(`M ${t} ${e}`),this.#a=6);for(let i=this.#a,n=this.#e.length;i<n;i+=6){const[r,o,h,l,c,u]=this.#e.slice(i,i+6).map(j.svgRound);s.push(`C${r} ${o} ${h} ${l} ${c} ${u}`)}return this.#h+=s.join(" "),this.#a=this.#e.length,this.#h}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#h=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class Wn extends j{#t;#e=0;#s;#i;#r;#n;#h;#a;#c;build(t,e,s,i,n,r,o){this.#r=e,this.#n=s,this.#h=i,this.#a=n,this.#c=r,this.#s=o??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${j.svgRound(e[4])} ${j.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${j.svgRound(e[10])} ${j.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,o,h,l,c]=e.subarray(s,s+6).map(j.svgRound);t.push(`C${n} ${r} ${o} ${h} ${l} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],o=[],[h,l,c,u]=this.#d();let d,f,g,p,b,m,v,y,_;switch(this.#a){case 0:_=j._rescale,d=t,f=e+i,g=s,p=-i,b=t+h*s,m=e+(1-l-u)*i,v=t+(h+c)*s,y=e+(1-l)*i;break;case 90:_=j._rescaleAndSwap,d=t,f=e,g=s,p=i,b=t+l*s,m=e+h*i,v=t+(l+u)*s,y=e+(h+c)*i;break;case 180:_=j._rescale,d=t+s,f=e,g=-s,p=i,b=t+(1-h-c)*s,m=e+l*i,v=t+(1-h)*s,y=e+(l+u)*i;break;case 270:_=j._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,b=t+(1-l-u)*s,m=e+(1-h-c)*i,v=t+(1-l)*s,y=e+(1-h)*i;break}for(const{line:S,points:A}of this.#i)r.push(_(S,d,f,g,p,n?new Array(S.length):null)),o.push(_(A,d,f,g,p,n?new Array(A.length):null));return{lines:r,points:o,rect:[b,m,v,y]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:o},rotation:h,thickness:l}){const c=[];let u,d,f,g,p;switch(h){case 0:p=j._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=j._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=j._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=j._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of o){const v=m.length;if(v===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(v===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const y=new Float32Array(3*(v-2));r.push(y);let[_,S,A,T]=m.subarray(0,4);y.set([NaN,NaN,NaN,NaN,_,S],0);for(let k=4;k<v;k+=2){const P=m[k],B=m[k+1];y.set(j.createBezierPoints(_,S,A,T,P,B),(k-2)*3),[_,S,A,T]=[A,T,P,B]}}}for(let m=0,v=r.length;m<v;m++)c.push({line:p(r[m].map(y=>y??NaN),u,d,f,g),points:p(o[m].map(y=>y??NaN),u,d,f,g)});const b=new Wn;return b.build(c,s,i,1,h,l,n),b}#l(t=this.#c){const e=this.#s+t/2*this.#h;return this.#a%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#l(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let o=4,h=i.length;o<h;o+=6){const[l,c]=i.subarray(o,o+2);t[0]=Math.min(t[0],l),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],l),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let o=6,h=i.length;o<h;o+=6){const[l,c,u,d,f,g]=i.subarray(o,o+6);G.bezierBoundingBox(n,r,l,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#l();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#l();this.#c=t;const[i,n]=this.#l(),[r,o]=[i-e,n-s],h=this.#t;return h[0]-=r,h[1]-=o,h[2]+=2*r,h[3]+=2*o,h}updateParentDimensions([t,e],s){const[i,n]=this.#l();this.#r=t,this.#n=e,this.#h=s;const[r,o]=this.#l(),h=r-i,l=o-n,c=this.#t;return c[0]-=h,c[1]-=l,c[2]+=2*h,c[3]+=2*l,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(j.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,o=0,h=0;switch(this.#e){case 90:i=e/t,n=-t/e,o=t;break;case 180:s=-1,r=-1,o=t,h=e;break;case 270:i=-e/t,n=t/e,h=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${j.svgRound(o)} ${j.svgRound(h)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#l(),[o,h,l,c]=this.#t;if(Math.abs(l-n)<=j.PRECISION||Math.abs(c-r)<=j.PRECISION){const p=t+s/2-(o+l/2),b=e+i/2-(h+c/2);return{path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${b})`}}}const u=(s-2*n)/(l-2*n),d=(i-2*r)/(c-2*r),f=l/s,g=c/i;return{path:{"transform-origin":`${j.svgRound(o)} ${j.svgRound(h)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${j.svgRound(n)} ${j.svgRound(r)}) scale(${u} ${d}) translate(${j.svgRound(-n)} ${j.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#l(),o=this.#t,[h,l,c,u]=o;if(o[0]=t,o[1]=e,o[2]=s,o[3]=i,Math.abs(c-n)<=j.PRECISION||Math.abs(u-r)<=j.PRECISION){const b=t+s/2-(h+c/2),m=e+i/2-(l+u/2);for(const{line:v,points:y}of this.#i)j._translate(v,b,m,v),j._translate(y,b,m,y);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(h+n)+t+n,p=-f*(l+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:b,points:m}of this.#i)j._rescale(b,g,p,d,f,b),j._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,o=t-r[0],h=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:l,points:c}of this.#i)j._translate(l,o,h,l),j._translate(c,o,h,c);else{const l=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)j._rescale(u,o,h,l,c,u),j._rescale(d,o,h,l,c,d);r[2]*=l,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${j.svgRound(t)} ${j.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${j.svgRound(t[0])} ${j.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Ao extends Fg{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:W._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Ao(this.#t);return t.updateAll(this),t}}class To extends X{static _type="ink";static _editorType=q.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){W.initialize(t,e),this._defaultDrawingOptions=new Ao(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return Z(this,"typesMap",new Map([[tt.INK_THICKNESS,"stroke-width"],[tt.INK_COLOR,"stroke"],[tt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new Ig(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return Wn.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof xo){const{data:{inkLists:r,rect:o,rotation:h,id:l,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:q.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:o.slice(0),rotation:h,id:l,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=To.getDefaultDrawingOptions({stroke:G.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":o}}=this,h={annotationType:q.INK,color:W._colorManager.convert(n),opacity:r,thickness:o,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?h:this.annotationElementId&&!this.#t(h)?null:(h.id=this.annotationElementId,h)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,o)=>r!==e[o])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class Eo extends W{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#h=null;#a=null;#c=!1;#l=!1;static _type="stamp";static _editorType=q.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){W.initialize(t,e)}static get supportedTypes(){return Z(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return Z(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(q.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#o()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#h){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,o=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!o)throw new Error("No response from the AI service.");if(o.error)throw new Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw new Error("No valid response from the AI service.");const h=o.output;return await this.setGuessedAltText(h),e&&!this.hasAltTextData()&&(this.altTextData={alt:h,decorative:!1}),h}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=Eo.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#h?.remove(),this.#h=null,this.#a&&(clearTimeout(this.#a),this.#a=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#h===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#o():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#a!==null&&clearTimeout(this.#a);const t=200;this.#a=setTimeout(()=>{this.#a=null,this.#m()},t)}#o(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[o,h]=this.parentDimensions;this.setDims(e*o/i,s*h/n),this._uiManager.enableWaiting(!1);const l=this.#h=document.createElement("canvas");l.setAttribute("role","img"),this.addContainer(l),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#l||(this.parent.addUndoableEditor(this),this.#l=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&l.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new ao;let o=this.#t,h=i,l=n,c=null;if(e){if(i>e||n>e){const A=Math.min(e/i,e/n);h=Math.floor(i*A),l=Math.floor(n*A)}c=document.createElement("canvas");const d=c.width=Math.ceil(h*r.sx),f=c.height=Math.ceil(l*r.sy);this.#c||(o=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",b="#42414d");const m=15,v=m*r.sx,y=m*r.sy,_=new OffscreenCanvas(v*2,y*2),S=_.getContext("2d");S.fillStyle=p,S.fillRect(0,0,v*2,y*2),S.fillStyle=b,S.fillRect(0,0,v,y),S.fillRect(v,y,v,y),g.fillStyle=g.createPattern(_,"repeat"),g.fillRect(0,0,d,f),g.drawImage(o,0,0,o.width,o.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&o.width<t&&o.height<t)d=o.width,f=o.height;else if(o=this.#t,i>t||n>t){const b=Math.min(t/i,t/n);d=Math.floor(i*b),f=Math.floor(n*b),this.#c||(o=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(o,0,0,o.width,o.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:h,height:l,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,o=this.#t;for(;n>2*t||r>2*e;){const h=n,l=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(o,0,0,h,l,0,0,n,r),o=c.transferToImageBitmap()}return o}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new ao,r=Math.ceil(s*t*n.sx),o=Math.ceil(i*e*n.sy),h=this.#h;if(!h||h.width===r&&h.height===o)return;h.width=r,h.height=o;const l=this.#c?this.#t:this.#g(r,o),c=h.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(l,0,0,l.width,l.height,0,0,r,o)}getImageForAltText(){return this.#h}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*js.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*js.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof Fl){const{data:{rect:g,rotation:p,id:b,structParent:m,popupRef:v},container:y,parent:{page:{pageNumber:_}}}=t,S=y.querySelector("canvas"),A=s.imageManager.getFromCanvas(y.id,S);S.remove();const T=(await e._structTree.getAriaAttributes(`${io}${b}`))?.get("aria-label")||"";i=t={annotationType:q.STAMP,bitmapId:A.id,bitmap:A.bitmap,pageIndex:_-1,rect:g.slice(0),rotation:p,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:T},isSvg:!1,structParent:m,popupRef:v}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:o,bitmapUrl:h,bitmapId:l,isSvg:c,accessibilityData:u}=t;l&&s.imageManager.isValidId(l)?(n.#e=l,o&&(n.#t=o)):n.#i=h,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#l=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:q.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const o=this.#b(s);if(o.isSame)return null;o.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const o=e.stamps.get(this.#e);r>o.area&&(o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#p(!1))}return s}#b(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class Ve{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#h=!1;#a=!1;#c=!1;#l=null;#d=null;#u=null;#f=null;#o;static _initialized=!1;static#g=new Map([Et,To,Eo,_t].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:o,textLayer:h,viewport:l,l10n:c}){const u=[...Ve.#g.values()];if(!Ve._initialized){Ve._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#o=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=l,this.#u=h,this.drawLayer=o,this._structTree=i,this.#o.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===q.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#v(),t){case q.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case q.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case q.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of Ve.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}cleanUndoStack(t){this.#o.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#o.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#o.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#a=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#o.isDeletedAnnotationElement(r))continue;let o=e.get(r);if(o){o.resetAnnotationElement(n),o.show(!1),n.show();continue}o=t.get(r),o&&(this.#o.addChangedExistingAnnotation(o),o.renderAnnotationElement(n)&&o.show(!1)),n.show()}}this.#v(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of Ve.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#a=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#o.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#o.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Wt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#o.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),_t.startHighlighting(this,this.#o.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#o._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#o.combinedSignal(this.#i);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#o.isDeletedAnnotationElement(e)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#a&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#o.addDeletedAnnotationElement(t.annotationElementId),W.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#o.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#o.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#o._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#o.getId()}get#p(){return Ve.#g.get(this.#o.getMode())}combinedSignal(t){return this.#o.combinedSignal(t)}#b(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#b({parent:this,id:n,x:s,y:i,uiManager:this.#o,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await Ve.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#b({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#o,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),o=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),l=(n+o)/2-t,c=(r+h)/2-e,[u,d]=this.viewport.rotation%180===0?[l,c]:[c,l];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:e}=Wt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#h&&(this.#h=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#o.getMode()===q.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===q.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:e}=Wt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#h=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#o.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#l){this.#p.startDrawing(this,this.#o,!1,t);return}this.#o.setCurrentDrawingSession(this),this.#l=new AbortController;const e=this.#o.combinedSignal(this.#l);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#o,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#l?(this.#o.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#o.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#o.removeLayer(this)}#v(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,ms(this.div,t);for(const e of this.#o.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#v();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,ms(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#o.viewParameters.realScale}}class Ut{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return Z(this,"_svgFactory",new _o)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=Ut._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#h(t,e){const s=Ut._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=Ut._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#a(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=Ut._svgFactory.createElement("defs");n.append(r);const o=Ut._svgFactory.createElement("path");r.append(o);const h=`path_p${this.pageIndex}_${i}`;o.setAttribute("id",h),o.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,o);const l=s?this.#h(r,h):null,c=Ut._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${h}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=Ut._svgFactory.createElement("defs");i.append(n);const r=Ut._svgFactory.createElement("path");n.append(r);const o=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const u=Ut._svgFactory.createElement("mask");n.append(u),h=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",h),u.setAttribute("maskUnits","objectBoundingBox");const d=Ut._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=Ut._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${o}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const l=Ut._svgFactory.createElement("use");i.append(l),l.setAttribute("href",`#${o}`),h&&l.setAttribute("mask",`url(#${h})`);const c=l.cloneNode();return i.append(c),l.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,o=typeof t=="number"?this.#s.get(t):t;if(o){if(s&&this.#a(o,s),i&&Ut.#r(o,i),n){const{classList:h}=o;for(const[l,c]of Object.entries(n))h.toggle(l,c)}if(r){const l=o.firstChild.firstChild;this.#a(l,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:So},Y.AbortException,Y.AnnotationEditorLayer,Y.AnnotationEditorParamsType,Y.AnnotationEditorType,Y.AnnotationEditorUIManager,Y.AnnotationLayer,Y.AnnotationMode,Y.ColorPicker,Y.DOMSVGFactory,Y.DrawLayer,Y.FeatureTest;var Ng=Y.GlobalWorkerOptions;Y.ImageKind,Y.InvalidPDFException,Y.MissingPDFException,Y.OPS,Y.OutputScale,Y.PDFDataRangeTransport,Y.PDFDateString,Y.PDFWorker,Y.PasswordResponses,Y.PermissionFlag,Y.PixelsPerInch,Y.RenderingCancelledException,Y.TextLayer,Y.TouchManager,Y.UnexpectedResponseException,Y.Util,Y.VerbosityLevel,Y.XfaLayer,Y.build,Y.createValidAbsoluteUrl,Y.fetchData;var jg=Y.getDocument;Y.getFilenameFromUrl,Y.getPdfFilenameFromUrl,Y.getXfaPageViewport,Y.isDataScheme,Y.isPdfFile,Y.noContextMenu,Y.normalizeUnicode,Y.setLayerDimensions,Y.shadow,Y.stopEvent;var Bg=Y.version;let Nl=null;function Hg(){const a=document.createElement("div");a.style.width="1in",document.body.append(a);const t=a.offsetWidth;return a.remove(),t}function zg(){const a=Nl??Hg();return Nl=a,a/72}function Gg(a,t=500){if(typeof a!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,a.apply(this,s)},t)}}function Vg(a){return a.arrayBuffer?a.arrayBuffer():new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>{const i=s.result;if(!(i instanceof ArrayBuffer)){e(new Error("Failed to read file as ArrayBuffer."));return}t(i)}),s.addEventListener("error",e),s.readAsArrayBuffer(a)})}jl()||(Ng.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Bg}/pdf.worker.min.mjs`);function jl(){try{return typeof OffscreenCanvas<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function"}catch{return!1}}async function Wg({page:a,data:t,scale:e,password:s},i){const n=zg()/window.devicePixelRatio,r=await Vg(t);if(jl()){const o=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/pdfjs.worker-DawqtvLM.js").href:new URL("assets/pdfjs.worker-DawqtvLM.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:mt&&mt.tagName.toUpperCase()==="SCRIPT"&&mt.src||new URL("pdf-canvas.umd.js",document.baseURI).href),{type:"module"});return o.postMessage({data:r,password:s,id:i,page:a,units:n,scale:e}),await new Promise(l=>{o.addEventListener("message",c=>{if(c.data.status!=="success")return;const{bitmap:u,width:d,height:f,pages:g}=c.data;if(u){const p=document.createElement("canvas"),b=p.getContext("bitmaprenderer");p.width=d,p.height=f,b?.transferFromImageBitmap(u),l({pages:g,canvas:p})}else l({pages:g,canvas:null})})})}else{const o=await jg({data:r,password:s}).promise,h=o.numPages;if(!i)return{canvas:null,pages:h};const l=await o.getPage(a),c=l.getViewport({scale:e}),u=document.createElement("canvas"),f={canvasContext:u.getContext("2d"),viewport:c,transform:[n,0,0,n,0,0]};return u.width=Math.floor(c.width*n),u.height=Math.floor(c.height*n),l.render(f).promise.then(()=>({canvas:u,pages:h}))}}const Yt=new Map;function Xg(a){const t=new jr(a);return Yt.set(a,t),t}function Ug(a){const t=Date.now();return{PDFId:`${a.name}-${t}`,name:a.name.replace(/.pdf/,""),updateDate:t,data:a}}async function Yg({src:a},t,e){if(!a||!e)return null;const{objects:s,options:i}=await Td(a),n=s.filter(o=>o!==null),r=Vu.groupSVGElements(n,i);return n.forEach(o=>{o.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function $g(a,t){if(!Yt.get(a))return;const s=1/3,i=ep(t,s);Hl(a,i,s)}async function qg(a,t){const e=Date.now(),i={PDFId:`${a.name}-${e}`,name:a.name.replace(/.png|.jpg|.jpeg/,""),updateDate:e,data:a};return t&&Bl(t,{data:a}),{...i,pages:1}}async function Bl(a,{data:t,scale:e=.5}){if(!Yt.get(a))return;const i=URL.createObjectURL(t),n=await Lt.fromURL(i);n.scale(e),Hl(a,n,e),URL.revokeObjectURL(i)}function Hl(a,t,e){const s=Yt.get(a);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Kg(a,t){if(!t)return;const{oCoords:e}=a;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:o,scaleX:h}=t;t.top=i-n*o/2,t.left=s-r*h/2,t.setCoords()}function Jg(a,t,e){!e||!a||(e.scale(1/t),Kg(a,e))}function Zg(a,t){if(!a)return;const e=a._cornerSize||6;a.borderScaleFactor=1/t,a.cornerSize=e*(1/t),a.touchCornerSize=e*4*(1/t),a.setCoords()}function Qg(a){const t=Yt.get(a);t&&(t.discardActiveObject(),t.renderAll())}function tp(a){const t=Yt.get(a);t&&(t.clear(),Yt.delete(a))}function ep(a,t){return new Lt(a,{scaleX:t,scaleY:t})}function ko(a,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:o}=a,h=t.x*r*i,l=t.y*o*n;a.set({left:e-h,top:s-l})}function zl(a,t,e){const s=a.type;return{"application/pdf":sp,"image/png":Vl,"image/jpeg":Vl}[s]?.(a,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function sp(a,t,e){const s=Ug(a),i=await Gl({page:1,data:a,scale:.8,password:t},e);return{...s,pages:i}}function Gl(a,t){return Wg(a,t).then(({canvas:e,pages:s})=>(e&&t&&$g(t,e),s))}async function Vl(a,t,e){return await qg(a,e)}function ip(a,t){const e=Yt.get(a);if(!e)return;const s=e.getActiveObject();s&&(s instanceof ee?s.forEachObject(i=>{i.set(t)}):s.set(t),e.renderAll())}async function np(a,t){const e=Yt.get(a);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(ac);i instanceof ee?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),ko(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function rp(a){const t=Yt.get(a);if(!t)return;const e=t.getActiveObject();e&&(e instanceof ee?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Wl(a){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:o}=a||{},h=J.useRef(null),l=J.useRef(null),c=J.useRef(1),u=J.useRef({...oc});function d(){if(!t||Yt.has(t))return;const O=Xg(t);return O.on("selection:created",D=>{if(r?.(D),D.selected.length<=1)return;const z=O.getActiveObject();z&&(l.current=z,e?.value&&l.current.set(e.value),l.current._cornerSize=l.current.cornerSize,S(c.current))}),O.on("selection:cleared",D=>{o?.(D),T(O)}),s&&O.on("mouse:down",s),i&&O.on("mouse:move",i),n&&O.on("mouse:up",n),O}function f(O,D){return zl(O,D,t)}function g(O){return Gl(O,t)}function p({data:O,scale:D=.5}){return Bl(t,{data:O,scale:D})}async function b(O,D,z){const M=Yt.get(t);if(!M)return;const R=await Lt.fromURL(O,{},{...ic,...D});ko(R,z),M.add(R),v(M,R),M.setActiveObject(R)}function m(O,D,z){const M=Yt.get(t);if(!M)return;const R=new Rt(O,{...nc,...D});ko(R,z),M.add(R),v(M,R),M.setActiveObject(R)}function v(O,D){D.on("selected",z=>y({canvas:O,target:z.target})),D.on("modified",z=>y({canvas:O,target:z.target})),D.on("scaling",()=>T(O)),D.on("moving",()=>T(O)),D.on("rotating",()=>T(O)),D._cornerSize=D._cornerSize??D.cornerSize}async function y({canvas:O,target:D,stroke:z=u.current.stroke,uuid:M=Date.now()}){if(O.getActiveObjects().length>1||h.current?.stroke===`${z}-${M}`)return;const U=await Yg(u.current,M,z);T(O),h.current=U,l.current=D,_(O,D,M),S(c.current,!0),U&&O.add(U)}function _(O,D,z){h.current&&(h.current.on("selected",()=>{O.remove(D),T(O)}),h.current.on("mouseover",()=>{y({canvas:O,target:D,stroke:u.current.hoverStroke,uuid:z})}),h.current.on("mouseout",()=>{y({canvas:O,target:D,stroke:u.current.stroke,uuid:z})}))}function S(O,D=!1){const z=Yt.get(t);c.current=O,z&&(Zg(l.current,O),Jg(l.current,O,h.current),!D&&z.renderAll())}function A(O){if(!O)return;u.current={...u.current,...O};const D=Yt.get(t);!h||!l.current||!D||y({target:l.current,canvas:D})}function T(O){l.current=null,h.current&&(O.remove(h.current),h.current=null)}function k(){Qg(t)}function P(){tp(t)}function B(O){ip(t,O)}function F(){return np(t,v)}function I(){rp(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:b,addTextFabric:m,clearActive:k,deleteCanvas:P,scaleFabric:S,setCloseSvgOptions:A,setActiveFabric:B,copyActiveFabric:F,deleteActiveFabric:I}}function op(a){const t=J.useRef(0),e=Gg(()=>{t.current!==window.innerWidth&&(t.current=window.innerWidth,a())});J.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const ap=J.forwardRef(hp);function hp({file:a,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:o=!1,password:h,dropTextOptions:l,dropImageOptions:c,closeSvgOptions:u,selectionOptions:d,manualReload:f,onLoaded:g,onReload:p,onPointerDown:b,onPointerMove:m,onPointerUp:v,onSelectionCreated:y,onSelectionCleared:_},S){const A=J.useRef(null),T=`${e}-${t-1}`,k=J.useMemo(()=>s*n,[s,n]),P=J.useMemo(()=>({...rc,...d}),[d]),{createCanvas:B,specifyPage:F,addFabric:I,addTextFabric:O,renderImage:D,clearActive:z,deleteCanvas:M,scaleFabric:R,setActiveFabric:U,setCloseSvgOptions:lt,copyActiveFabric:ft,deleteActiveFabric:E}=Wl({id:T,selectionOptions:P,pointerDown:b,pointerMove:m,pointerUp:v,selectionCreated:y,selectionCleared:_});op(rt);async function H(){globalThis.requestAnimationFrame(async()=>{if(B(),a.data?.type.startsWith("image/")||a.canvas){const{canvas:ht}=a,Mt=ht?7:3,Pt=ht?.length?ht[t-1]:a.data;Pt&&D({data:Pt,scale:i/Mt}),g?.();return}const N=a.canvas?.[t-1]??a.data;N&&await F({page:t,data:N,scale:i,password:h}),g?.()})}function V(N){if(N.preventDefault(),N.stopPropagation(),!o||!N.dataTransfer)return;const{dataTransfer:ht,nativeEvent:Mt}=N,{offsetX:Pt,offsetY:lp}=Mt,Xl=ht.getData("text/plain"),Ul=ht.getData("text/uri-list"),Yl=ht.getData("custom/offset"),$l=Yl?JSON.parse(Yl):null,ql={top:lp,left:Pt},Kl={x:$l?.offsetX??0,y:$l?.offsetY??0};Ul?Q(Ul,ql,Kl):Xl&&kt(Xl,ql,Kl)}function Q(N,ht,Mt){I(N,{...c,...ht},Mt)}function kt(N,ht,Mt){O(N,{...l,...ht},Mt)}function rt(){f||H(),p?.()}return J.useImperativeHandle(S,()=>({reload:H,addImage:Q,addText:kt,clearActive:z,deleteCanvas:M,setActiveFabric:U,copyActiveFabric:ft,deleteActiveFabric:E,canvasRef:A})),J.useEffect(()=>{rt()},[i,t,a,h]),J.useEffect(()=>{R(k)},[k]),J.useEffect(()=>{lt(u)},[u]),J.useEffect(()=>()=>M(),[]),Ro.jsx("div",{style:{transform:`scale(${k})`},onDragOver:N=>N.preventDefault(),onDragEnter:N=>N.preventDefault(),onDrop:V,children:Ro.jsx("canvas",{id:T,ref:A,className:r})})}st.default=ap,st.loadFile=zl,st.useFabric=Wl,Object.defineProperties(st,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));