diff --git a/README.md b/README.md index 6b1851e..677d0f5 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,9 @@ There were a number of improvements I wanted to make. This was initially done fo ### Copy Any Message - A copy button is now present on any message, allowing the user to copy it to their clipboard. +### PDF Upload Queries +- When using a GPT model, the user can upload a PDF, which is parsed for text entirely browser-side. Then the user may ask the AI questions about the contents of the PDF. + ### Mid-conversation Editing - Just like on the official UI, the user may edit any message. This branches the conversation at that point. diff --git a/dist/assets/__vite-browser-external-b25bb000.js b/dist/assets/__vite-browser-external-b25bb000.js new file mode 100644 index 0000000..b480ffe --- /dev/null +++ b/dist/assets/__vite-browser-external-b25bb000.js @@ -0,0 +1 @@ +const e={};export{e as default}; diff --git a/dist/assets/index-0a8895ee.js b/dist/assets/index-0a8895ee.js deleted file mode 100644 index 0743dd3..0000000 --- a/dist/assets/index-0a8895ee.js +++ /dev/null @@ -1,67 +0,0 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function t(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=t(n);fetch(n.href,i)}})();function B(){}function et(s,e){for(const t in e)s[t]=e[t];return s}function Qs(s){return s()}function Tr(){return Object.create(null)}function De(s){s.forEach(Qs)}function Ys(s){return typeof s=="function"}function K(s,e){return s!=s?e==e:s!==e||s&&typeof s=="object"||typeof s=="function"}let Nt;function Pe(s,e){return Nt||(Nt=document.createElement("a")),Nt.href=e,s===Nt.href}function xi(s){return Object.keys(s).length===0}function Ks(s,...e){if(s==null)return B;const t=s.subscribe(...e);return t.unsubscribe?()=>t.unsubscribe():t}function V(s){let e;return Ks(s,t=>e=t)(),e}function _e(s,e,t){s.$$.on_destroy.push(Ks(e,t))}function de(s,e,t,r){if(s){const n=Zs(s,e,t,r);return s[0](n)}}function Zs(s,e,t,r){return s[1]&&r?et(t.ctx.slice(),s[1](r(e))):t.ctx}function he(s,e,t,r){if(s[2]&&r){const n=s[2](r(t));if(e.dirty===void 0)return n;if(typeof n=="object"){const i=[],l=Math.max(e.dirty.length,n.length);for(let a=0;a32){const e=[],t=s.ctx.length/32;for(let r=0;rs.removeEventListener(e,t,r)}function Zt(s){return function(e){return e.stopPropagation(),s.call(this,e)}}function p(s,e,t){t==null?s.removeAttribute(e):s.getAttribute(e)!==t&&s.setAttribute(e,t)}function Mi(s){return Array.from(s.childNodes)}function Te(s,e){e=""+e,s.wholeText!==e&&(s.data=e)}function He(s,e){s.value=e??""}function lt(s,e,t,r){t===null?s.style.removeProperty(e):s.style.setProperty(e,t,r?"important":"")}function rt(s,e){for(let t=0;t{const n=s.$$.callbacks[e];if(n){const i=Fi(e,t,{cancelable:r});return n.slice().forEach(l=>{l.call(s,i)}),!i.defaultPrevented}return!0}}function Li(s,e){return $t().$$.context.set(s,e),e}function Di(s){return $t().$$.context.get(s)}const St=[],st=[],Gt=[],qn=[],qi=Promise.resolve();let Nn=!1;function Ni(){Nn||(Nn=!0,qi.then(Ws))}function ft(s){Gt.push(s)}function zi(s){qn.push(s)}const yn=new Set;let wt=0;function Ws(){if(wt!==0)return;const s=Mt;do{try{for(;wt{Jt.delete(s),r&&(t&&s.d(1),r())}),s.o(e)}else r&&r()}function Et(s,e){const t={},r={},n={$$scope:1};let i=s.length;for(;i--;){const l=s[i],a=e[i];if(a){for(const o in l)o in a||(r[o]=1);for(const o in a)n[o]||(t[o]=a[o],n[o]=1);s[i]=a}else for(const o in l)n[o]=1}for(const l in r)l in t||(t[l]=void 0);return t}function Tt(s){return typeof s=="object"&&s!==null?s:{}}function Gi(s,e,t){const r=s.$$.props[e];r!==void 0&&(s.$$.bound[r]=t,t(s.$$.ctx[r]))}function Y(s){s&&s.c()}function J(s,e,t,r){const{fragment:n,after_update:i}=s.$$;n&&n.m(e,t),r||ft(()=>{const l=s.$$.on_mount.map(Qs).filter(Ys);s.$$.on_destroy?s.$$.on_destroy.push(...l):De(l),s.$$.on_mount=[]}),i.forEach(ft)}function Q(s,e){const t=s.$$;t.fragment!==null&&(De(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function Ji(s,e){s.$$.dirty[0]===-1&&(St.push(s),Ni(),s.$$.dirty.fill(0)),s.$$.dirty[e/31|0]|=1<{const m=h.length?h[0]:d;return c.ctx&&n(c.ctx[f],c.ctx[f]=m)&&(!c.skip_bound&&c.bound[f]&&c.bound[f](m),u&&Ji(s,f)),d}):[],c.update(),u=!0,De(c.before_update),c.fragment=r?r(c.ctx):!1,e.target){if(e.hydrate){const f=Mi(e.target);c.fragment&&c.fragment.l(f),f.forEach(O)}else c.fragment&&c.fragment.c();e.intro&&v(s.$$.fragment),J(s,e.target,e.anchor,e.customElement),Ws()}xt(o)}class W{$destroy(){Q(this,1),this.$destroy=B}$on(e,t){if(!Ys(t))return B;const r=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return r.push(t),()=>{const n=r.indexOf(t);n!==-1&&r.splice(n,1)}}$set(e){this.$$set&&!xi(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const yt=[];function Se(s,e=B){let t;const r=new Set;function n(a){if(K(s,a)&&(s=a,t)){const o=!yt.length;for(const c of r)c[1](),yt.push(c,s);if(o){for(let c=0;c{r.delete(c),r.size===0&&(t(),t=null)}}return{set:n,update:i,subscribe:l}}var it=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},zn={},Xs={},Wt={},Qi={get exports(){return Wt},set exports(s){Wt=s}},Xt={},Yi={get exports(){return Xt},set exports(s){Xt=s}},ei=function(e,t){return function(){for(var n=new Array(arguments.length),i=0;i"u"}function Zi(s){return s!==null&&!Hn(s)&&s.constructor!==null&&!Hn(s.constructor)&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function ti(s){return at.call(s)==="[object ArrayBuffer]"}function Wi(s){return at.call(s)==="[object FormData]"}function Xi(s){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&ti(s.buffer),e}function el(s){return typeof s=="string"}function tl(s){return typeof s=="number"}function ni(s){return s!==null&&typeof s=="object"}function Qt(s){if(at.call(s)!=="[object Object]")return!1;var e=Object.getPrototypeOf(s);return e===null||e===Object.prototype}function nl(s){return at.call(s)==="[object Date]"}function rl(s){return at.call(s)==="[object File]"}function sl(s){return at.call(s)==="[object Blob]"}function ri(s){return at.call(s)==="[object Function]"}function il(s){return ni(s)&&ri(s.pipe)}function ll(s){return at.call(s)==="[object URLSearchParams]"}function ol(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function al(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function ir(s,e){if(!(s===null||typeof s>"u"))if(typeof s!="object"&&(s=[s]),sr(s))for(var t=0,r=s.length;t"u"||(kt.isArray(o)?c=c+"[]":o=[o],kt.forEach(o,function(f){kt.isDate(f)?f=f.toISOString():kt.isObject(f)&&(f=JSON.stringify(f)),i.push(Cr(c)+"="+Cr(f))}))}),n=i.join("&")}if(n){var l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+n}return e},fl=qe;function un(){this.handlers=[]}un.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1};un.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};un.prototype.forEach=function(e){fl.forEach(this.handlers,function(r){r!==null&&e(r)})};var dl=un,hl=qe,pl=function(e,t){hl.forEach(e,function(n,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[i])})},ii=function(e,t,r,n,i){return e.config=t,r&&(e.code=r),e.request=n,e.response=i,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},e},li={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},kn,Rr;function oi(){if(Rr)return kn;Rr=1;var s=ii;return kn=function(t,r,n,i,l){var a=new Error(t);return s(a,r,n,i,l)},kn}var On,xr;function ml(){if(xr)return On;xr=1;var s=oi();return On=function(t,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?t(n):r(s("Request failed with status code "+n.status,n.config,null,n.request,n))},On}var Sn,Ir;function gl(){if(Ir)return Sn;Ir=1;var s=qe;return Sn=s.isStandardBrowserEnv()?function(){return{write:function(r,n,i,l,a,o){var c=[];c.push(r+"="+encodeURIComponent(n)),s.isNumber(i)&&c.push("expires="+new Date(i).toGMTString()),s.isString(l)&&c.push("path="+l),s.isString(a)&&c.push("domain="+a),o===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(r){var n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Sn}var An,jr;function _l(){return jr||(jr=1,An=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}),An}var $n,Mr;function bl(){return Mr||(Mr=1,$n=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}),$n}var En,Fr;function vl(){if(Fr)return En;Fr=1;var s=_l(),e=bl();return En=function(r,n){return r&&!s(n)?e(r,n):n},En}var Tn,Ur;function wl(){if(Ur)return Tn;Ur=1;var s=qe,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return Tn=function(r){var n={},i,l,a;return r&&s.forEach(r.split(` -`),function(c){if(a=c.indexOf(":"),i=s.trim(c.substr(0,a)).toLowerCase(),l=s.trim(c.substr(a+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([l]):n[i]=n[i]?n[i]+", "+l:l}}),n},Tn}var Pn,Vr;function yl(){if(Vr)return Pn;Vr=1;var s=qe;return Pn=s.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(l){var a=l;return t&&(r.setAttribute("href",a),a=r.href),r.setAttribute("href",a),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(a){var o=s.isString(a)?i(a):a;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),Pn}var Cn,Br;function fn(){if(Br)return Cn;Br=1;function s(e){this.message=e}return s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,Cn=s,Cn}var Rn,Lr;function Dr(){if(Lr)return Rn;Lr=1;var s=qe,e=ml(),t=gl(),r=si,n=vl(),i=wl(),l=yl(),a=oi(),o=li,c=fn();return Rn=function(f){return new Promise(function(h,m){var g=f.data,y=f.headers,k=f.responseType,A;function E(){f.cancelToken&&f.cancelToken.unsubscribe(A),f.signal&&f.signal.removeEventListener("abort",A)}s.isFormData(g)&&delete y["Content-Type"];var w=new XMLHttpRequest;if(f.auth){var j=f.auth.username||"",I=f.auth.password?unescape(encodeURIComponent(f.auth.password)):"";y.Authorization="Basic "+btoa(j+":"+I)}var H=n(f.baseURL,f.url);w.open(f.method.toUpperCase(),r(H,f.params,f.paramsSerializer),!0),w.timeout=f.timeout;function ee(){if(w){var re="getAllResponseHeaders"in w?i(w.getAllResponseHeaders()):null,te=!k||k==="text"||k==="json"?w.responseText:w.response,ae={data:te,status:w.status,statusText:w.statusText,headers:re,config:f,request:w};e(function(be){h(be),E()},function(be){m(be),E()},ae),w=null}}if("onloadend"in w?w.onloadend=ee:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(ee)},w.onabort=function(){w&&(m(a("Request aborted",f,"ECONNABORTED",w)),w=null)},w.onerror=function(){m(a("Network Error",f,null,w)),w=null},w.ontimeout=function(){var te=f.timeout?"timeout of "+f.timeout+"ms exceeded":"timeout exceeded",ae=f.transitional||o;f.timeoutErrorMessage&&(te=f.timeoutErrorMessage),m(a(te,f,ae.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",w)),w=null},s.isStandardBrowserEnv()){var X=(f.withCredentials||l(H))&&f.xsrfCookieName?t.read(f.xsrfCookieName):void 0;X&&(y[f.xsrfHeaderName]=X)}"setRequestHeader"in w&&s.forEach(y,function(te,ae){typeof g>"u"&&ae.toLowerCase()==="content-type"?delete y[ae]:w.setRequestHeader(ae,te)}),s.isUndefined(f.withCredentials)||(w.withCredentials=!!f.withCredentials),k&&k!=="json"&&(w.responseType=f.responseType),typeof f.onDownloadProgress=="function"&&w.addEventListener("progress",f.onDownloadProgress),typeof f.onUploadProgress=="function"&&w.upload&&w.upload.addEventListener("progress",f.onUploadProgress),(f.cancelToken||f.signal)&&(A=function(re){w&&(m(!re||re&&re.type?new c("canceled"):re),w.abort(),w=null)},f.cancelToken&&f.cancelToken.subscribe(A),f.signal&&(f.signal.aborted?A():f.signal.addEventListener("abort",A))),g||(g=null),w.send(g)})},Rn}var Ce=qe,qr=pl,kl=ii,Ol=li,Sl={"Content-Type":"application/x-www-form-urlencoded"};function Nr(s,e){!Ce.isUndefined(s)&&Ce.isUndefined(s["Content-Type"])&&(s["Content-Type"]=e)}function Al(){var s;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(s=Dr()),s}function $l(s,e,t){if(Ce.isString(s))try{return(e||JSON.parse)(s),Ce.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(t||JSON.stringify)(s)}var dn={transitional:Ol,adapter:Al(),transformRequest:[function(e,t){return qr(t,"Accept"),qr(t,"Content-Type"),Ce.isFormData(e)||Ce.isArrayBuffer(e)||Ce.isBuffer(e)||Ce.isStream(e)||Ce.isFile(e)||Ce.isBlob(e)?e:Ce.isArrayBufferView(e)?e.buffer:Ce.isURLSearchParams(e)?(Nr(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):Ce.isObject(e)||t&&t["Content-Type"]==="application/json"?(Nr(t,"application/json"),$l(e)):e}],transformResponse:[function(e){var t=this.transitional||dn.transitional,r=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,i=!r&&this.responseType==="json";if(i||n&&Ce.isString(e)&&e.length)try{return JSON.parse(e)}catch(l){if(i)throw l.name==="SyntaxError"?kl(l,this,"E_JSON_PARSE"):l}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Ce.forEach(["delete","get","head"],function(e){dn.headers[e]={}});Ce.forEach(["post","put","patch"],function(e){dn.headers[e]=Ce.merge(Sl)});var lr=dn,El=qe,Tl=lr,Pl=function(e,t,r){var n=this||Tl;return El.forEach(r,function(l){e=l.call(n,e,t)}),e},xn,zr;function ai(){return zr||(zr=1,xn=function(e){return!!(e&&e.__CANCEL__)}),xn}var Hr=qe,In=Pl,Cl=ai(),Rl=lr,xl=fn();function jn(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new xl("canceled")}var Il=function(e){jn(e),e.headers=e.headers||{},e.data=In.call(e,e.data,e.headers,e.transformRequest),e.headers=Hr.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Hr.forEach(["delete","get","head","post","put","patch","common"],function(n){delete e.headers[n]});var t=e.adapter||Rl.adapter;return t(e).then(function(n){return jn(e),n.data=In.call(e,n.data,n.headers,e.transformResponse),n},function(n){return Cl(n)||(jn(e),n&&n.response&&(n.response.data=In.call(e,n.response.data,n.response.headers,e.transformResponse))),Promise.reject(n)})},Ne=qe,ci=function(e,t){t=t||{};var r={};function n(u,f){return Ne.isPlainObject(u)&&Ne.isPlainObject(f)?Ne.merge(u,f):Ne.isPlainObject(f)?Ne.merge({},f):Ne.isArray(f)?f.slice():f}function i(u){if(Ne.isUndefined(t[u])){if(!Ne.isUndefined(e[u]))return n(void 0,e[u])}else return n(e[u],t[u])}function l(u){if(!Ne.isUndefined(t[u]))return n(void 0,t[u])}function a(u){if(Ne.isUndefined(t[u])){if(!Ne.isUndefined(e[u]))return n(void 0,e[u])}else return n(void 0,t[u])}function o(u){if(u in t)return n(e[u],t[u]);if(u in e)return n(void 0,e[u])}var c={url:l,method:l,data:l,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o};return Ne.forEach(Object.keys(e).concat(Object.keys(t)),function(f){var d=c[f]||i,h=d(f);Ne.isUndefined(h)&&d!==o||(r[f]=h)}),r},Mn,Gr;function ui(){return Gr||(Gr=1,Mn={version:"0.26.1"}),Mn}var jl=ui().version,or={};["object","boolean","number","function","string","symbol"].forEach(function(s,e){or[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});var Jr={};or.transitional=function(e,t,r){function n(i,l){return"[Axios v"+jl+"] Transitional option '"+i+"'"+l+(r?". "+r:"")}return function(i,l,a){if(e===!1)throw new Error(n(l," has been removed"+(t?" in "+t:"")));return t&&!Jr[l]&&(Jr[l]=!0,console.warn(n(l," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,l,a):!0}};function Ml(s,e,t){if(typeof s!="object")throw new TypeError("options must be an object");for(var r=Object.keys(s),n=r.length;n-- >0;){var i=r[n],l=e[i];if(l){var a=s[i],o=a===void 0||l(a,i,s);if(o!==!0)throw new TypeError("option "+i+" must be "+o);continue}if(t!==!0)throw Error("Unknown option "+i)}}var Fl={assertOptions:Ml,validators:or},fi=qe,Ul=si,Qr=dl,Yr=Il,hn=ci,di=Fl,Ot=di.validators;function Ft(s){this.defaults=s,this.interceptors={request:new Qr,response:new Qr}}Ft.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=hn(this.defaults,t),t.method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var r=t.transitional;r!==void 0&&di.assertOptions(r,{silentJSONParsing:Ot.transitional(Ot.boolean),forcedJSONParsing:Ot.transitional(Ot.boolean),clarifyTimeoutError:Ot.transitional(Ot.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(t)===!1||(i=i&&h.synchronous,n.unshift(h.fulfilled,h.rejected))});var l=[];this.interceptors.response.forEach(function(h){l.push(h.fulfilled,h.rejected)});var a;if(!i){var o=[Yr,void 0];for(Array.prototype.unshift.apply(o,n),o=o.concat(l),a=Promise.resolve(t);o.length;)a=a.then(o.shift(),o.shift());return a}for(var c=t;n.length;){var u=n.shift(),f=n.shift();try{c=u(c)}catch(d){f(d);break}}try{a=Yr(c)}catch(d){return Promise.reject(d)}for(;l.length;)a=a.then(l.shift(),l.shift());return a};Ft.prototype.getUri=function(e){return e=hn(this.defaults,e),Ul(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")};fi.forEach(["delete","get","head","options"],function(e){Ft.prototype[e]=function(t,r){return this.request(hn(r||{},{method:e,url:t,data:(r||{}).data}))}});fi.forEach(["post","put","patch"],function(e){Ft.prototype[e]=function(t,r,n){return this.request(hn(n||{},{method:e,url:t,data:r}))}});var Vl=Ft,Fn,Kr;function Bl(){if(Kr)return Fn;Kr=1;var s=fn();function e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var r;this.promise=new Promise(function(l){r=l});var n=this;this.promise.then(function(i){if(n._listeners){var l,a=n._listeners.length;for(l=0;lJn(s,r,t)):Object.keys(e).forEach(r=>Jn(s,e[r],`${t}${t!==""?".":""}${r}`)):s.has(t)?s.append(t,e):s.set(t,e))}Oe.setSearchParams=function(s,...e){const t=new URLSearchParams(s.search);Jn(t,e),s.search=t.toString()};Oe.serializeDataIfNeeded=function(s,e,t){const r=typeof s!="string";return(r&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):r)?JSON.stringify(s!==void 0?s:{}):s||""};Oe.toPathString=function(s){return s.pathname+s.search+s.hash};Oe.createRequestFunction=function(s,e,t,r){return(n=e,i=t)=>{const l=Object.assign(Object.assign({},s.options),{url:((r==null?void 0:r.basePath)||i)+s.url});return n.request(l)}};(function(s){var e=it&&it.__awaiter||function(l,a,o,c){function u(f){return f instanceof o?f:new o(function(d){d(f)})}return new(o||(o=Promise))(function(f,d){function h(y){try{g(c.next(y))}catch(k){d(k)}}function m(y){try{g(c.throw(y))}catch(k){d(k)}}function g(y){y.done?f(y.value):u(y.value).then(h,m)}g((c=c.apply(l,a||[])).next())})};Object.defineProperty(s,"__esModule",{value:!0}),s.OpenAIApi=s.OpenAIApiFactory=s.OpenAIApiFp=s.OpenAIApiAxiosParamCreator=s.CreateImageRequestResponseFormatEnum=s.CreateImageRequestSizeEnum=s.ChatCompletionResponseMessageRoleEnum=s.ChatCompletionRequestMessageRoleEnum=void 0;const t=Wt,r=Oe,n=ar;s.ChatCompletionRequestMessageRoleEnum={System:"system",User:"user",Assistant:"assistant"},s.ChatCompletionResponseMessageRoleEnum={System:"system",User:"user",Assistant:"assistant"},s.CreateImageRequestSizeEnum={_256x256:"256x256",_512x512:"512x512",_1024x1024:"1024x1024"},s.CreateImageRequestResponseFormatEnum={Url:"url",B64Json:"b64_json"},s.OpenAIApiAxiosParamCreator=function(l){return{cancelFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("cancelFineTune","fineTuneId",a);const c="/fine-tunes/{fine_tune_id}/cancel".replace("{fine_tune_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),createAnswer:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createAnswer","createAnswerRequest",a);const c="/answers",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createChatCompletion:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createChatCompletion","createChatCompletionRequest",a);const c="/chat/completions",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createClassification:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createClassification","createClassificationRequest",a);const c="/classifications",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createCompletion:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createCompletion","createCompletionRequest",a);const c="/completions",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createEdit:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createEdit","createEditRequest",a);const c="/edits",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createEmbedding:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createEmbedding","createEmbeddingRequest",a);const c="/embeddings",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createFile:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createFile","file",a),r.assertParamExists("createFile","purpose",o);const u="/files",f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"POST"},d),c),m={},g={},y=new(l&&l.formDataCtor||FormData);a!==void 0&&y.append("file",a),o!==void 0&&y.append("purpose",o),m["Content-Type"]="multipart/form-data",r.setSearchParams(f,g);let k=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign(Object.assign({},m),y.getHeaders()),k),c.headers),h.data=y,{url:r.toPathString(f),options:h}}),createFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createFineTune","createFineTuneRequest",a);const c="/fine-tunes",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createImage:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImage","createImageRequest",a);const c="/images/generations",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createImageEdit:(a,o,c,u,f,d,h,m={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImageEdit","image",a),r.assertParamExists("createImageEdit","prompt",o);const g="/images/edits",y=new URL(g,r.DUMMY_BASE_URL);let k;l&&(k=l.baseOptions);const A=Object.assign(Object.assign({method:"POST"},k),m),E={},w={},j=new(l&&l.formDataCtor||FormData);a!==void 0&&j.append("image",a),c!==void 0&&j.append("mask",c),o!==void 0&&j.append("prompt",o),u!==void 0&&j.append("n",u),f!==void 0&&j.append("size",f),d!==void 0&&j.append("response_format",d),h!==void 0&&j.append("user",h),E["Content-Type"]="multipart/form-data",r.setSearchParams(y,w);let I=k&&k.headers?k.headers:{};return A.headers=Object.assign(Object.assign(Object.assign(Object.assign({},E),j.getHeaders()),I),m.headers),A.data=j,{url:r.toPathString(y),options:A}}),createImageVariation:(a,o,c,u,f,d={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImageVariation","image",a);const h="/images/variations",m=new URL(h,r.DUMMY_BASE_URL);let g;l&&(g=l.baseOptions);const y=Object.assign(Object.assign({method:"POST"},g),d),k={},A={},E=new(l&&l.formDataCtor||FormData);a!==void 0&&E.append("image",a),o!==void 0&&E.append("n",o),c!==void 0&&E.append("size",c),u!==void 0&&E.append("response_format",u),f!==void 0&&E.append("user",f),k["Content-Type"]="multipart/form-data",r.setSearchParams(m,A);let w=g&&g.headers?g.headers:{};return y.headers=Object.assign(Object.assign(Object.assign(Object.assign({},k),E.getHeaders()),w),d.headers),y.data=E,{url:r.toPathString(m),options:y}}),createModeration:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createModeration","createModerationRequest",a);const c="/moderations",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},m={};h["Content-Type"]="application/json",r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createSearch:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createSearch","engineId",a),r.assertParamExists("createSearch","createSearchRequest",o);const u="/engines/{engine_id}/search".replace("{engine_id}",encodeURIComponent(String(a))),f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"POST"},d),c),m={},g={};m["Content-Type"]="application/json",r.setSearchParams(f,g);let y=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign({},m),y),c.headers),h.data=r.serializeDataIfNeeded(o,h,l),{url:r.toPathString(f),options:h}}),createTranscription:(a,o,c,u,f,d,h={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createTranscription","file",a),r.assertParamExists("createTranscription","model",o);const m="/audio/transcriptions",g=new URL(m,r.DUMMY_BASE_URL);let y;l&&(y=l.baseOptions);const k=Object.assign(Object.assign({method:"POST"},y),h),A={},E={},w=new(l&&l.formDataCtor||FormData);a!==void 0&&w.append("file",a),o!==void 0&&w.append("model",o),c!==void 0&&w.append("prompt",c),u!==void 0&&w.append("response_format",u),f!==void 0&&w.append("temperature",f),d!==void 0&&w.append("language",d),A["Content-Type"]="multipart/form-data",r.setSearchParams(g,E);let j=y&&y.headers?y.headers:{};return k.headers=Object.assign(Object.assign(Object.assign(Object.assign({},A),w.getHeaders()),j),h.headers),k.data=w,{url:r.toPathString(g),options:k}}),createTranslation:(a,o,c,u,f,d={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createTranslation","file",a),r.assertParamExists("createTranslation","model",o);const h="/audio/translations",m=new URL(h,r.DUMMY_BASE_URL);let g;l&&(g=l.baseOptions);const y=Object.assign(Object.assign({method:"POST"},g),d),k={},A={},E=new(l&&l.formDataCtor||FormData);a!==void 0&&E.append("file",a),o!==void 0&&E.append("model",o),c!==void 0&&E.append("prompt",c),u!==void 0&&E.append("response_format",u),f!==void 0&&E.append("temperature",f),k["Content-Type"]="multipart/form-data",r.setSearchParams(m,A);let w=g&&g.headers?g.headers:{};return y.headers=Object.assign(Object.assign(Object.assign(Object.assign({},k),E.getHeaders()),w),d.headers),y.data=E,{url:r.toPathString(m),options:y}}),deleteFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("deleteFile","fileId",a);const c="/files/{file_id}".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"DELETE"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),deleteModel:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("deleteModel","model",a);const c="/models/{model}".replace("{model}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"DELETE"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),downloadFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("downloadFile","fileId",a);const c="/files/{file_id}/content".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),listEngines:(a={})=>e(this,void 0,void 0,function*(){const o="/engines",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let m=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),m),a.headers),{url:r.toPathString(c),options:f}}),listFiles:(a={})=>e(this,void 0,void 0,function*(){const o="/files",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let m=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),m),a.headers),{url:r.toPathString(c),options:f}}),listFineTuneEvents:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("listFineTuneEvents","fineTuneId",a);const u="/fine-tunes/{fine_tune_id}/events".replace("{fine_tune_id}",encodeURIComponent(String(a))),f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"GET"},d),c),m={},g={};o!==void 0&&(g.stream=o),r.setSearchParams(f,g);let y=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign({},m),y),c.headers),{url:r.toPathString(f),options:h}}),listFineTunes:(a={})=>e(this,void 0,void 0,function*(){const o="/fine-tunes",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let m=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),m),a.headers),{url:r.toPathString(c),options:f}}),listModels:(a={})=>e(this,void 0,void 0,function*(){const o="/models",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let m=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),m),a.headers),{url:r.toPathString(c),options:f}}),retrieveEngine:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveEngine","engineId",a);const c="/engines/{engine_id}".replace("{engine_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),retrieveFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveFile","fileId",a);const c="/files/{file_id}".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),retrieveFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveFineTune","fineTuneId",a);const c="/fine-tunes/{fine_tune_id}".replace("{fine_tune_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}}),retrieveModel:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveModel","model",a);const c="/models/{model}".replace("{model}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},m={};r.setSearchParams(u,m);let g=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),g),o.headers),{url:r.toPathString(u),options:d}})}},s.OpenAIApiFp=function(l){const a=s.OpenAIApiAxiosParamCreator(l);return{cancelFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.cancelFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createAnswer(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createAnswer(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createChatCompletion(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createChatCompletion(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createClassification(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createClassification(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createCompletion(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createCompletion(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createEdit(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createEdit(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createEmbedding(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createEmbedding(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createFile(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.createFile(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},createFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createImage(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createImage(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createImageEdit(o,c,u,f,d,h,m,g){return e(this,void 0,void 0,function*(){const y=yield a.createImageEdit(o,c,u,f,d,h,m,g);return r.createRequestFunction(y,t.default,n.BASE_PATH,l)})},createImageVariation(o,c,u,f,d,h){return e(this,void 0,void 0,function*(){const m=yield a.createImageVariation(o,c,u,f,d,h);return r.createRequestFunction(m,t.default,n.BASE_PATH,l)})},createModeration(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createModeration(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createSearch(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.createSearch(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},createTranscription(o,c,u,f,d,h,m){return e(this,void 0,void 0,function*(){const g=yield a.createTranscription(o,c,u,f,d,h,m);return r.createRequestFunction(g,t.default,n.BASE_PATH,l)})},createTranslation(o,c,u,f,d,h){return e(this,void 0,void 0,function*(){const m=yield a.createTranslation(o,c,u,f,d,h);return r.createRequestFunction(m,t.default,n.BASE_PATH,l)})},deleteFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.deleteFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},deleteModel(o,c){return e(this,void 0,void 0,function*(){const u=yield a.deleteModel(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},downloadFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.downloadFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},listEngines(o){return e(this,void 0,void 0,function*(){const c=yield a.listEngines(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listFiles(o){return e(this,void 0,void 0,function*(){const c=yield a.listFiles(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listFineTuneEvents(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.listFineTuneEvents(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},listFineTunes(o){return e(this,void 0,void 0,function*(){const c=yield a.listFineTunes(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listModels(o){return e(this,void 0,void 0,function*(){const c=yield a.listModels(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},retrieveEngine(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveEngine(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveModel(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveModel(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})}}},s.OpenAIApiFactory=function(l,a,o){const c=s.OpenAIApiFp(l);return{cancelFineTune(u,f){return c.cancelFineTune(u,f).then(d=>d(o,a))},createAnswer(u,f){return c.createAnswer(u,f).then(d=>d(o,a))},createChatCompletion(u,f){return c.createChatCompletion(u,f).then(d=>d(o,a))},createClassification(u,f){return c.createClassification(u,f).then(d=>d(o,a))},createCompletion(u,f){return c.createCompletion(u,f).then(d=>d(o,a))},createEdit(u,f){return c.createEdit(u,f).then(d=>d(o,a))},createEmbedding(u,f){return c.createEmbedding(u,f).then(d=>d(o,a))},createFile(u,f,d){return c.createFile(u,f,d).then(h=>h(o,a))},createFineTune(u,f){return c.createFineTune(u,f).then(d=>d(o,a))},createImage(u,f){return c.createImage(u,f).then(d=>d(o,a))},createImageEdit(u,f,d,h,m,g,y,k){return c.createImageEdit(u,f,d,h,m,g,y,k).then(A=>A(o,a))},createImageVariation(u,f,d,h,m,g){return c.createImageVariation(u,f,d,h,m,g).then(y=>y(o,a))},createModeration(u,f){return c.createModeration(u,f).then(d=>d(o,a))},createSearch(u,f,d){return c.createSearch(u,f,d).then(h=>h(o,a))},createTranscription(u,f,d,h,m,g,y){return c.createTranscription(u,f,d,h,m,g,y).then(k=>k(o,a))},createTranslation(u,f,d,h,m,g){return c.createTranslation(u,f,d,h,m,g).then(y=>y(o,a))},deleteFile(u,f){return c.deleteFile(u,f).then(d=>d(o,a))},deleteModel(u,f){return c.deleteModel(u,f).then(d=>d(o,a))},downloadFile(u,f){return c.downloadFile(u,f).then(d=>d(o,a))},listEngines(u){return c.listEngines(u).then(f=>f(o,a))},listFiles(u){return c.listFiles(u).then(f=>f(o,a))},listFineTuneEvents(u,f,d){return c.listFineTuneEvents(u,f,d).then(h=>h(o,a))},listFineTunes(u){return c.listFineTunes(u).then(f=>f(o,a))},listModels(u){return c.listModels(u).then(f=>f(o,a))},retrieveEngine(u,f){return c.retrieveEngine(u,f).then(d=>d(o,a))},retrieveFile(u,f){return c.retrieveFile(u,f).then(d=>d(o,a))},retrieveFineTune(u,f){return c.retrieveFineTune(u,f).then(d=>d(o,a))},retrieveModel(u,f){return c.retrieveModel(u,f).then(d=>d(o,a))}}};class i extends n.BaseAPI{cancelFineTune(a,o){return s.OpenAIApiFp(this.configuration).cancelFineTune(a,o).then(c=>c(this.axios,this.basePath))}createAnswer(a,o){return s.OpenAIApiFp(this.configuration).createAnswer(a,o).then(c=>c(this.axios,this.basePath))}createChatCompletion(a,o){return s.OpenAIApiFp(this.configuration).createChatCompletion(a,o).then(c=>c(this.axios,this.basePath))}createClassification(a,o){return s.OpenAIApiFp(this.configuration).createClassification(a,o).then(c=>c(this.axios,this.basePath))}createCompletion(a,o){return s.OpenAIApiFp(this.configuration).createCompletion(a,o).then(c=>c(this.axios,this.basePath))}createEdit(a,o){return s.OpenAIApiFp(this.configuration).createEdit(a,o).then(c=>c(this.axios,this.basePath))}createEmbedding(a,o){return s.OpenAIApiFp(this.configuration).createEmbedding(a,o).then(c=>c(this.axios,this.basePath))}createFile(a,o,c){return s.OpenAIApiFp(this.configuration).createFile(a,o,c).then(u=>u(this.axios,this.basePath))}createFineTune(a,o){return s.OpenAIApiFp(this.configuration).createFineTune(a,o).then(c=>c(this.axios,this.basePath))}createImage(a,o){return s.OpenAIApiFp(this.configuration).createImage(a,o).then(c=>c(this.axios,this.basePath))}createImageEdit(a,o,c,u,f,d,h,m){return s.OpenAIApiFp(this.configuration).createImageEdit(a,o,c,u,f,d,h,m).then(g=>g(this.axios,this.basePath))}createImageVariation(a,o,c,u,f,d){return s.OpenAIApiFp(this.configuration).createImageVariation(a,o,c,u,f,d).then(h=>h(this.axios,this.basePath))}createModeration(a,o){return s.OpenAIApiFp(this.configuration).createModeration(a,o).then(c=>c(this.axios,this.basePath))}createSearch(a,o,c){return s.OpenAIApiFp(this.configuration).createSearch(a,o,c).then(u=>u(this.axios,this.basePath))}createTranscription(a,o,c,u,f,d,h){return s.OpenAIApiFp(this.configuration).createTranscription(a,o,c,u,f,d,h).then(m=>m(this.axios,this.basePath))}createTranslation(a,o,c,u,f,d){return s.OpenAIApiFp(this.configuration).createTranslation(a,o,c,u,f,d).then(h=>h(this.axios,this.basePath))}deleteFile(a,o){return s.OpenAIApiFp(this.configuration).deleteFile(a,o).then(c=>c(this.axios,this.basePath))}deleteModel(a,o){return s.OpenAIApiFp(this.configuration).deleteModel(a,o).then(c=>c(this.axios,this.basePath))}downloadFile(a,o){return s.OpenAIApiFp(this.configuration).downloadFile(a,o).then(c=>c(this.axios,this.basePath))}listEngines(a){return s.OpenAIApiFp(this.configuration).listEngines(a).then(o=>o(this.axios,this.basePath))}listFiles(a){return s.OpenAIApiFp(this.configuration).listFiles(a).then(o=>o(this.axios,this.basePath))}listFineTuneEvents(a,o,c){return s.OpenAIApiFp(this.configuration).listFineTuneEvents(a,o,c).then(u=>u(this.axios,this.basePath))}listFineTunes(a){return s.OpenAIApiFp(this.configuration).listFineTunes(a).then(o=>o(this.axios,this.basePath))}listModels(a){return s.OpenAIApiFp(this.configuration).listModels(a).then(o=>o(this.axios,this.basePath))}retrieveEngine(a,o){return s.OpenAIApiFp(this.configuration).retrieveEngine(a,o).then(c=>c(this.axios,this.basePath))}retrieveFile(a,o){return s.OpenAIApiFp(this.configuration).retrieveFile(a,o).then(c=>c(this.axios,this.basePath))}retrieveFineTune(a,o){return s.OpenAIApiFp(this.configuration).retrieveFineTune(a,o).then(c=>c(this.axios,this.basePath))}retrieveModel(a,o){return s.OpenAIApiFp(this.configuration).retrieveModel(a,o).then(c=>c(this.axios,this.basePath))}}s.OpenAIApi=i})(Xs);var pn={};const Gl="openai",Jl="3.2.1",Ql="Node.js library for the OpenAI API",Yl={type:"git",url:"git@github.com:openai/openai-node.git"},Kl=["openai","open","ai","gpt-3","gpt3"],Zl="OpenAI",Wl="MIT",Xl="./dist/index.js",eo="./dist/index.d.ts",to={build:"tsc --outDir dist/"},no={axios:"^0.26.0","form-data":"^4.0.0"},ro={"@types/node":"^12.11.5",typescript:"^3.6.4"},so={name:Gl,version:Jl,description:Ql,repository:Yl,keywords:Kl,author:Zl,license:Wl,main:Xl,types:eo,scripts:to,dependencies:no,devDependencies:ro};var Bn,es;function io(){return es||(es=1,Bn=typeof self=="object"?self.FormData:window.FormData),Bn}Object.defineProperty(pn,"__esModule",{value:!0});pn.Configuration=void 0;const lo=so;class oo{constructor(e={}){this.apiKey=e.apiKey,this.organization=e.organization,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor,this.baseOptions||(this.baseOptions={}),this.baseOptions.headers=Object.assign({"User-Agent":`OpenAI/NodeJS/${lo.version}`,Authorization:`Bearer ${this.apiKey}`},this.baseOptions.headers),this.organization&&(this.baseOptions.headers["OpenAI-Organization"]=this.organization),this.formDataCtor||(this.formDataCtor=io())}isJsonMime(e){const t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}}pn.Configuration=oo;(function(s){var e=it&&it.__createBinding||(Object.create?function(r,n,i,l){l===void 0&&(l=i),Object.defineProperty(r,l,{enumerable:!0,get:function(){return n[i]}})}:function(r,n,i,l){l===void 0&&(l=i),r[l]=n[i]}),t=it&&it.__exportStar||function(r,n){for(var i in r)i!=="default"&&!n.hasOwnProperty(i)&&e(n,r,i)};Object.defineProperty(s,"__esModule",{value:!0}),t(Xs,s),t(pn,s)})(zn);const en=Se(!1),tn=Se(!1),Qn=Se(!1);let ts=localStorage.getItem("api_key"),ao=ts!==null?JSON.parse(ts):null;const ze=Se(ao);ze.subscribe(s=>localStorage.setItem("api_key",JSON.stringify(s)));let ns=localStorage.getItem("combined_tokens"),co=ns!==null?JSON.parse(ns):0;const pt=Se(co);pt.subscribe(s=>localStorage.setItem("combined_tokens",JSON.stringify(s)));let rs=localStorage.getItem("default_assistant_role"),uo=rs!==null?JSON.parse(rs):0;const mt=Se(uo||{role:"You are a helpful assistant.",type:"system"});mt.subscribe(s=>localStorage.setItem("default_assistant_role",JSON.stringify(s)));const Ee=Se(0);let ss=localStorage.getItem("conversations"),fo=ss!==null?JSON.parse(ss):null;const ue=Se(fo||[{history:[],conversationTokens:0,assistantRole:"You are a helpful assistant.",title:""}]);ue.subscribe(s=>{localStorage.setItem("conversations",JSON.stringify(s))});const Ve=Se(localStorage.getItem("selectedModel")||"gpt-3.5-turbo"),It=Se(localStorage.getItem("selectedVoice")||"alloy"),At=Se(localStorage.getItem("selectedMode")||"GPT");Ve.subscribe(s=>{localStorage.setItem("selectedModel",s)});It.subscribe(s=>{localStorage.setItem("selectedVoice",s)});const nn=Se(!1),Ut=Se([]),Yn=Se(!1),Qe=Se(!1),dt=Se(!1),rn=Se({streamText:"",convId:null});let ho="";function ot(s,e=V(Ee)){return new Promise((t,r)=>{try{let n=V(ue);n[e].history=s,ue.set(n),t()}catch(n){console.error("Failed to update history",n),r(n)}})}function is(s){const e=V(Ee),t=V(ue),r=t[e].history.filter((n,i)=>i!==s);t[e].history=r,ue.set(t)}function pi(){const s=V(ue);if(s.length>0&&s[s.length-1].history.length===0){console.log("Jumping to recent conversation."),Ee.set(s.length-1);return}const e={history:[],conversationTokens:0,assistantRole:V(mt).role,title:""};ue.update(t=>[...t,e]),Ee.set(V(ue).length-1)}function mi(s){const e=["role","content"];let t=Object.keys(s).filter(r=>e.includes(r)).reduce((r,n)=>(r[n]=s[n],r),{});return Array.isArray(t.content)||(t.content=t.content.toString()),t}async function ls(s,e){let t=V(ue)[e].history,r=t;t=[...t,{role:"user",content:s}],ot(t);const n="gpt-3.5-turbo",i="alloy",l=V(Ve)||n,a=V(It)||i;let o;if(o=[...r,{role:"user",content:s}],l.includes("tts"))await Bo(s,l,a);else if(l.includes("vision")){const c=V(Ut);await Lo(o,c,e)}else await Do(o,e);V(ue)[e].history.length===1&&await mo(s)}function po(s){let e=V(ue);e[V(Ee)].title=s,ue.set(e)}async function mo(s){let t=await Vo([{role:"user",content:s},{role:"user",content:"Generate a title for this conversation, so I can easily reference it later. Maximum 6 words. Don't provide anything other than the title. Don't use quotes."}],"gpt-4-turbo-preview");if(t){let r=t.data.choices[0].message.content;po(r.toString())}}function go(s){const e={role:"assistant",content:"Audio file generated.",audioUrl:s,isAudio:!0};ot([...V(ue)[V(Ee)].history,e])}function _o(s){let e=V(ue);e[V(Ee)].conversationTokens=e[V(Ee)].conversationTokens+s.total_tokens,ue.set(e),pt.set(V(pt)+s.total_tokens),console.log("Counted tokens: "+s.total_tokens)}function gi(s,e){let t=0;s.map(i=>{t+=i.content.length}),t+=ho.length;let r=t/4,n=V(ue);n[e].conversationTokens=n[e].conversationTokens+r,ue.set(n),pt.set(V(pt)+r)}var ur={};(function(s){var e=function(t,r){if(!(this instanceof e))return new e(t,r);this.INITIALIZING=-1,this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.url=t,r=r||{},this.headers=r.headers||{},this.payload=r.payload!==void 0?r.payload:"",this.method=r.method||this.payload&&"POST"||"GET",this.withCredentials=!!r.withCredentials,this.FIELD_SEPARATOR=":",this.listeners={},this.xhr=null,this.readyState=this.INITIALIZING,this.progress=0,this.chunk="",this.addEventListener=function(n,i){this.listeners[n]===void 0&&(this.listeners[n]=[]),this.listeners[n].indexOf(i)===-1&&this.listeners[n].push(i)},this.removeEventListener=function(n,i){if(this.listeners[n]!==void 0){var l=[];this.listeners[n].forEach(function(a){a!==i&&l.push(a)}),l.length===0?delete this.listeners[n]:this.listeners[n]=l}},this.dispatchEvent=function(n){if(!n)return!0;n.source=this;var i="on"+n.type;return this.hasOwnProperty(i)&&(this[i].call(this,n),n.defaultPrevented)?!1:this.listeners[n.type]?this.listeners[n.type].every(function(l){return l(n),!n.defaultPrevented}):!0},this._setReadyState=function(n){var i=new CustomEvent("readystatechange");i.readyState=n,this.readyState=n,this.dispatchEvent(i)},this._onStreamFailure=function(n){var i=new CustomEvent("error");i.data=n.currentTarget.response,this.dispatchEvent(i),this.close()},this._onStreamAbort=function(n){this.dispatchEvent(new CustomEvent("abort")),this.close()},this._onStreamProgress=function(n){if(this.xhr){if(this.xhr.status!==200){this._onStreamFailure(n);return}this.readyState==this.CONNECTING&&(this.dispatchEvent(new CustomEvent("open")),this._setReadyState(this.OPEN));var i=this.xhr.responseText.substring(this.progress);this.progress+=i.length,i.split(/(\r\n|\r|\n){2}/g).forEach(function(l){l.trim().length===0?(this.dispatchEvent(this._parseEventChunk(this.chunk.trim())),this.chunk=""):this.chunk+=l}.bind(this))}},this._onStreamLoaded=function(n){this._onStreamProgress(n),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=""},this._parseEventChunk=function(n){if(!n||n.length===0)return null;var i={id:null,retry:null,data:"",event:"message"};n.split(/\n|\r\n|\r/).forEach(function(a){a=a.trimRight();var o=a.indexOf(this.FIELD_SEPARATOR);if(!(o<=0)){var c=a.substring(0,o);if(c in i){var u=a.substring(o+1).trimLeft();c==="data"?i[c]+=u:i[c]=u}}}.bind(this));var l=new CustomEvent(i.event);return l.data=i.data,l.id=i.id,l},this._checkStreamClosed=function(){this.xhr&&this.xhr.readyState===XMLHttpRequest.DONE&&this._setReadyState(this.CLOSED)},this.stream=function(){this._setReadyState(this.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener("progress",this._onStreamProgress.bind(this)),this.xhr.addEventListener("load",this._onStreamLoaded.bind(this)),this.xhr.addEventListener("readystatechange",this._checkStreamClosed.bind(this)),this.xhr.addEventListener("error",this._onStreamFailure.bind(this)),this.xhr.addEventListener("abort",this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url);for(var n in this.headers)this.xhr.setRequestHeader(n,this.headers[n]);this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)},this.close=function(){this.readyState!==this.CLOSED&&(this.xhr.abort(),this.xhr=null,this._setReadyState(this.CLOSED))}};s.SSE=e})(ur);function os(s){return s.replace(/\n/g,` -`)}async function bo(s){try{return await navigator.clipboard.writeText(s),console.log("Text successfully copied to clipboard"),!0}catch(e){return console.error("Failed to copy text to clipboard: ",e),!1}}function Kn(s){return s.isAudio===!0}function _i(s){return s.split("").filter(t=>t==="`").length}const Zn=(s,e)=>e.some(t=>s instanceof t);let as,cs;function vo(){return as||(as=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function wo(){return cs||(cs=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Wn=new WeakMap,Ln=new WeakMap,mn=new WeakMap;function yo(s){const e=new Promise((t,r)=>{const n=()=>{s.removeEventListener("success",i),s.removeEventListener("error",l)},i=()=>{t(ht(s.result)),n()},l=()=>{r(s.error),n()};s.addEventListener("success",i),s.addEventListener("error",l)});return mn.set(e,s),e}function ko(s){if(Wn.has(s))return;const e=new Promise((t,r)=>{const n=()=>{s.removeEventListener("complete",i),s.removeEventListener("error",l),s.removeEventListener("abort",l)},i=()=>{t(),n()},l=()=>{r(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",i),s.addEventListener("error",l),s.addEventListener("abort",l)});Wn.set(s,e)}let Xn={get(s,e,t){if(s instanceof IDBTransaction){if(e==="done")return Wn.get(s);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ht(s[e])},set(s,e,t){return s[e]=t,!0},has(s,e){return s instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in s}};function bi(s){Xn=s(Xn)}function Oo(s){return wo().includes(s)?function(...e){return s.apply(er(this),e),ht(this.request)}:function(...e){return ht(s.apply(er(this),e))}}function So(s){return typeof s=="function"?Oo(s):(s instanceof IDBTransaction&&ko(s),Zn(s,vo())?new Proxy(s,Xn):s)}function ht(s){if(s instanceof IDBRequest)return yo(s);if(Ln.has(s))return Ln.get(s);const e=So(s);return e!==s&&(Ln.set(s,e),mn.set(e,s)),e}const er=s=>mn.get(s);function Ao(s,e,{blocked:t,upgrade:r,blocking:n,terminated:i}={}){const l=indexedDB.open(s,e),a=ht(l);return r&&l.addEventListener("upgradeneeded",o=>{r(ht(l.result),o.oldVersion,o.newVersion,ht(l.transaction),o)}),t&&l.addEventListener("blocked",o=>t(o.oldVersion,o.newVersion,o)),a.then(o=>{i&&o.addEventListener("close",()=>i()),n&&o.addEventListener("versionchange",c=>n(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}const $o=["get","getKey","getAll","getAllKeys","count"],Eo=["put","add","delete","clear"],Dn=new Map;function us(s,e){if(!(s instanceof IDBDatabase&&!(e in s)&&typeof e=="string"))return;if(Dn.get(e))return Dn.get(e);const t=e.replace(/FromIndex$/,""),r=e!==t,n=Eo.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(n||$o.includes(t)))return;const i=async function(l,...a){const o=this.transaction(l,n?"readwrite":"readonly");let c=o.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[t](...a),n&&o.done]))[0]};return Dn.set(e,i),i}bi(s=>({...s,get:(e,t,r)=>us(e,t)||s.get(e,t,r),has:(e,t)=>!!us(e,t)||s.has(e,t)}));const To=["continue","continuePrimaryKey","advance"],fs={},tr=new WeakMap,vi=new WeakMap,Po={get(s,e){if(!To.includes(e))return s[e];let t=fs[e];return t||(t=fs[e]=function(...r){tr.set(this,vi.get(this)[e](...r))}),t}};async function*Co(...s){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...s)),!e)return;e=e;const t=new Proxy(e,Po);for(vi.set(t,e),mn.set(t,er(e));e;)yield t,e=await(tr.get(t)||e.continue()),tr.delete(t)}function ds(s,e){return e===Symbol.asyncIterator&&Zn(s,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Zn(s,[IDBIndex,IDBObjectStore])}bi(s=>({...s,get(e,t,r){return ds(e,t)?Co:s.get(e,t,r)},has(e,t){return ds(e,t)||s.has(e,t)}}));const fr=Ao("audio-store",1,{upgrade(s){s.createObjectStore("audios",{keyPath:"id"})}});async function Ro(s,e,t){const n=(await fr).transaction("audios","readwrite");return n.objectStore("audios").put({id:s,blob:e,conversationId:t}),n.done}async function xo(s){const r=await(await fr).transaction("audios","readonly").objectStore("audios").get(s);return r==null?void 0:r.blob}async function Io(){const e=(await fr).transaction("audios","readwrite");return await e.objectStore("audios").clear(),e.done}function jo(s){jt();const e=s.target.files;for(let t of e){const r=new FileReader;r.onloadend=()=>{Ut.update(n=>[...n,r.result])},r.readAsDataURL(t)}}function jt(){Ut.set([]),Yn.set(!0)}let nr=null,wi=null,sn=null;const Mo=async()=>{if(sn){sn.close(),console.log("Stream closed by user."),Qe.set(!1);const{streamText:s,convId:e}=V(rn);if(s&&e!==null){const t=s.replace(/█+$/,""),r=V(ue)[e].history;let n=r.length?r[r.length-1]:null;n&&n.content.endsWith("█")?r[r.length-1]={...n,content:t}:r.push({role:"assistant",content:t}),await ot(r,e),rn.set({streamText:"",convId:null})}dt.set(!0),jt()}},Fo=[{role:"assistant",content:"There was an error. Maybe the API key is wrong? Or the servers could be down?"}];function yi(){const s=V(ze);s?(nr=new zn.Configuration({apiKey:s}),wi=new zn.OpenAIApi(nr),console.log("OpenAI API initialized.")):console.warn("API key is not set. Please set the API key before initializing.")}function Uo(){yi(),console.log("Configuration reloaded.")}async function Vo(s,e=V(Ve)){try{s=[{role:"system",content:V(ue)[V(Ee)].assistantRole},...s];const t=await wi.createChatCompletion({model:e,messages:s});if(t)return _o(t.data.usage),t}catch(t){throw console.error("Error in sendRequest:",t),nr=null,await ot(Fo),t}}function ki(s){try{const e=/\{"id".*?\]\}/g;return(s.match(e)||[]).map(JSON.parse)}catch(e){return console.error("Error parsing JSON chunk:",e),null}}async function Bo(s,e,t,r){console.log("Sending TTS message.");const n={model:e,voice:t,input:s};try{const i=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${V(ze)}`},body:JSON.stringify(n)});if(!i.ok)throw new Error(`Failed to generate audio, response status: ${i.status}`);const l=await i.blob(),a=`audio-${Date.now()}-${Math.floor(Math.random()*1e4)}`;Ro(a,l).then(()=>{console.log("Audio blob saved to IndexedDB with ID:",a)}).catch(console.error),xo(a).then(o=>{if(console.log(a),console.log(o),o instanceof Blob)if(o){const c=URL.createObjectURL(o);go(c)}else console.error("Blob is null or undefined");else console.error("Retrieved object is not a Blob:",o)}).catch(o=>console.error("Error retrieving audio blob:",o))}catch(i){console.error("TTS request error:",i)}}async function Lo(s,e,t){var k;console.log("Sending vision message."),dt.set(!1);let r=!1,n=0,i=!1,l=V(ue)[t].history,a=l.map(A=>({role:A.role,content:typeof A.content=="string"?[{type:"text",text:A.content}]:A.content})),o=((k=[...s].reverse().find(A=>A.role==="user"))==null?void 0:k.content)||"",c=e.map(A=>({type:"image_url",image_url:{url:A}})),f={role:"user",content:o?[{type:"text",text:o},...c]:[...c]},h=[...a.map(mi),f],m=!1,g="";l=[...l],Qe.set(!0);let y=new ur.SSE("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${V(ze)}`},method:"POST",payload:JSON.stringify({model:V(Ve),messages:h,stream:!0})});console.log("payload",JSON.stringify({model:V(Ve),messages:h,stream:!0})),y.addEventListener("message",async A=>{if(A.data!=="[DONE]")try{r||ki(A.data).forEach(w=>{var I,H;let j=(H=(I=w.choices[0])==null?void 0:I.delta)==null?void 0:H.content;if(j){let ee=_i(j);n+=ee,ee===0&&(n=0),n===3&&(i=!i,n=0),g+=j,rn.set({streamText:g,convId:t}),ot([...l,{role:"assistant",content:g+"█"+(i?"\n```":"")}],t)}})}catch(E){console.error("Error parsing JSON:",E),r=!0,y.close(),jt(),console.log("Stream closed due to parsing error."),Qe.set(!1);return}else m=!0,V(dt)&&(g=g.replace(/█+$/,""),dt.set(!1)),await ot([...l,{role:"assistant",content:g}],t),gi(s,t),g="",m=!0,console.log("Stream closed"),y.close(),jt(),Qe.set(!1)}),y.addEventListener("error",A=>{try{if(m)return;console.error("Stream error:",A)}finally{y.close(),jt(),Qe.set(!1)}}),y.stream(),sn=y}async function Do(s,e){dt.set(!1);let t=!1,r=0,n=!1,i=V(ue)[e].history;s=[{role:V(mt).type,content:V(ue)[e].assistantRole},...s];const a=s.map(mi);let o=!1,c="";i=[...i],Qe.set(!0);let u=new ur.SSE("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${V(ze)}`},method:"POST",payload:JSON.stringify({model:V(Ve),messages:a,stream:!0})});console.log("payload",JSON.stringify({model:V(Ve),messages:a,stream:!0})),u.addEventListener("message",async f=>{if(f.data!=="[DONE]")try{t||ki(f.data).forEach(h=>{var g,y;let m=(y=(g=h.choices[0])==null?void 0:g.delta)==null?void 0:y.content;if(m){let k=_i(m);r+=k,k===0&&(r=0),r===3&&(n=!n,r=0),c+=m,rn.set({streamText:c,convId:e}),ot([...i,{role:"assistant",content:c+"█"+(n?"\n```":"")}],e)}})}catch(d){console.error("Error parsing JSON:",d),t=!0,u.close(),console.log("Stream closed due to parsing error."),Qe.set(!1);return}else o=!0,V(dt)&&(c=c.replace(/█+$/,""),dt.set(!1)),await ot([...i,{role:"assistant",content:c}],e),gi(s,e),c="",o=!0,console.log("Stream closed"),u.close(),Qe.set(!1)}),u.addEventListener("error",f=>{try{if(o)return;console.error("Stream error:",f)}finally{u.close(),Qe.set(!1)}}),u.stream(),sn=u}function rr(){const s=window.innerHeight*.01;document.documentElement.style.setProperty("--app-height",`${s}px`)}async function qo(){V(ue).length>0&&Ee.set(V(ue).length-1),rr(),window.addEventListener("resize",rr);try{await Io()}catch(s){console.error("Failed to clear audio blobs:",s)}Ut.set([]),ze.subscribe(s=>{s&&yi()})}function No(){window.removeEventListener("resize",rr)}function zo(s){let e,t,r,n,i,l,a,o,c,u,f,d,h;return{c(){e=b("div"),t=b("div"),t.textContent="Your audio file is ready:",r=C(),n=b("button"),n.innerHTML='▶ Play',i=ce(`\r - | `),l=b("span"),a=b("a"),o=ce("⇓ Download"),c=b("div"),c.textContent="(unavailable after refresh!)",u=C(),f=b("audio"),p(t,"class","mb-2"),p(a,"href",s[0]),p(a,"download","response.mp3"),p(l,"class","downloadbutton svelte-2tsp55"),p(c,"class","notice svelte-2tsp55"),lt(f,"display","none")},m(m,g){S(m,e,g),_(e,t),_(e,r),_(e,n),_(e,i),_(e,l),_(l,a),_(a,o),_(e,c),_(e,u),_(e,f),s[3](f),d||(h=N(n,"click",s[2]),d=!0)},p(m,[g]){g&1&&p(a,"href",m[0])},i:B,o:B,d(m){m&&O(e),s[3](null),d=!1,h()}}}function Ho(s,e,t){let{audioUrl:r=""}=e,n;function i(){n&&n.paused?n.play():n&&(n.pause(),t(1,n.currentTime=0,n))}function l(a){st[a?"unshift":"push"](()=>{n=a,t(1,n),t(0,r)})}return s.$$set=a=>{"audioUrl"in a&&t(0,r=a.audioUrl)},s.$$.update=()=>{s.$$.dirty&3&&n&&r&&(t(1,n.src=r,n),n.load())},[r,n,i,l]}class Go extends W{constructor(e){super(),Z(this,e,Ho,zo,K,{audioUrl:0})}}const Jo="/assets/menu-fd7c077d.svg",Qo="/assets/add-1d344fcd.svg";function Yo(s){let e,t,r,n,i,l,a=(s[0]===""?"New Conversation":s[0])+"",o,c,u,f,d,h,m;return{c(){e=b("div"),t=b("button"),r=b("img"),i=C(),l=b("div"),o=ce(a),c=C(),u=b("button"),f=b("img"),p(r,"class","icon-white w-8"),p(r,"alt","Menu"),Pe(r.src,n=Jo)||p(r,"src",n),p(t,"class","text-lg font-medium"),p(l,"class","text-lg font-medium pt-[3px] text-center overflow-hidden h-8"),p(f,"class","icon-white w-8"),p(f,"alt","+"),Pe(f.src,d=Qo)||p(f,"src",d),p(u,"class","text-lg font-medium"),p(e,"class","bg-secondary text-white/90 py-2 px-4 flex justify-between md:hidden shrink grow-0 max-h-16")},m(g,y){S(g,e,y),_(e,t),_(t,r),_(e,i),_(e,l),_(l,o),_(e,c),_(e,u),_(u,f),h||(m=[N(t,"click",s[2]),N(u,"click",s[1])],h=!0)},p(g,[y]){y&1&&a!==(a=(g[0]===""?"New Conversation":g[0])+"")&&Te(o,a)},i:B,o:B,d(g){g&&O(e),h=!1,De(m)}}}function Ko(s,e,t){const r=cn();function n(){r("new-chat")}let{conversation_title:i}=e;const l=()=>{Qn.set(!0)};return s.$$set=a=>{"conversation_title"in a&&t(0,i=a.conversation_title)},[i,n,l]}class Zo extends W{constructor(e){super(),Z(this,e,Ko,Yo,K,{conversation_title:0})}}const ln="/assets/close-301080ff.svg",Wo="/assets/NewChat-bf9b0f55.svg",Oi="/assets/edit-91842bde.svg";function hs(s,e,t){const r=s.slice();return r[30]=e[t],r[32]=t,r}function Xo(s){let e;return{c(){e=b("textarea"),p(e,"placeholder","Select a conversation or start a new one..."),p(e,"class","bg-primary px-2 pt-1 pb-3 resize-none rounded focus:outline-none focus:outline-primary z-20")},m(t,r){S(t,e,r)},p:B,d(t){t&&O(e)}}}function ea(s){let e,t,r;return{c(){e=b("textarea"),p(e,"placeholder",s[7]),p(e,"class","bg-primary px-2 pt-1 pb-3 resize-none rounded focus:outline-none focus:outline-primary z-20")},m(n,i){S(n,e,i),He(e,s[4][s[3]].assistantRole),t||(r=N(e,"input",s[17]),t=!0)},p(n,i){i[0]&24&&He(e,n[4][n[3]].assistantRole)},d(n){n&&O(e),t=!1,r()}}}function ta(s){let e,t=(s[30].title===""?"New conversation":s[30].title)+"",r,n;return{c(){e=b("p"),r=ce(t),p(e,"class",n="text-left text-sm flex-grow title-text "+(s[2],"")+" svelte-2c65x7")},m(i,l){S(i,e,l),_(e,r)},p(i,l){l[0]&16&&t!==(t=(i[30].title===""?"New conversation":i[30].title)+"")&&Te(r,t),l[0]&4&&n!==(n="text-left text-sm flex-grow title-text "+(i[2],"")+" svelte-2c65x7")&&p(e,"class",n)},d(i){i&&O(e)}}}function na(s){let e,t,r;function n(){return s[19](s[32])}function i(...l){return s[20](s[32],...l)}return{c(){e=b("input"),p(e,"type","text"),p(e,"class","edit-input svelte-2c65x7")},m(l,a){S(l,e,a),He(e,s[1]),t||(r=[N(e,"input",s[18]),N(e,"blur",n),N(e,"keydown",i)],t=!0)},p(l,a){s=l,a[0]&2&&e.value!==s[1]&&He(e,s[1])},d(l){l&&O(e),t=!1,De(r)}}}function ps(s){let e,t,r,n,i;function l(...o){return s[23](s[32],...o)}function a(...o){return s[24](s[32],...o)}return{c(){e=b("button"),t=b("img"),Pe(t.src,r=ln)||p(t,"src",r),p(t,"alt","Delete"),p(t,"class","icon-white min-w-5 w-5 h-5"),p(e,"tabindex","0"),p(e,"class","delete hidden rounded w-7 h-7 font-bold flex justify-center items-center hover:bg-warning svelte-2c65x7")},m(o,c){S(o,e,c),_(e,t),n||(i=[N(e,"click",Zt(l)),N(e,"keydown",Zt(a))],n=!0)},p(o,c){s=o},d(o){o&&O(e),n=!1,De(i)}}}function ms(s){let e,t=s[30].conversationTokens.toFixed(0)+"",r;return{c(){e=b("p"),r=ce(t),p(e,"class","text-blue-200 tokens z-20 ml-5 svelte-2c65x7")},m(n,i){S(n,e,i),_(e,r)},p(n,i){i[0]&16&&t!==(t=n[30].conversationTokens.toFixed(0)+"")&&Te(r,t)},d(n){n&&O(e)}}}function gs(s){let e,t,r,n,i,l,a,o,c,u,f,d;function h(I,H){return I[0]===I[4].length-I[32]-1?na:ta}let m=h(s),g=m(s);function y(...I){return s[21](s[32],s[30],...I)}function k(...I){return s[22](s[32],s[30],...I)}let A=s[4].length>=2&&ps(s),E=s[2]===!0&&ms(s);function w(){return s[25](s[32])}function j(...I){return s[26](s[32],...I)}return{c(){e=b("div"),g.c(),t=C(),r=b("div"),n=b("button"),i=b("img"),a=C(),A&&A.c(),o=C(),E&&E.c(),c=C(),Pe(i.src,l=Oi)||p(i,"src",l),p(i,"alt","Edit"),p(i,"class","icon-white min-w-4 w-4 h-4"),p(n,"tabindex","0"),p(n,"class","edit hidden rounded w-7 h-7 font-bold flex justify-center items-center hover:bg-blue-600 svelte-2c65x7"),p(r,"class","flex items-center gap-2"),p(e,"class",u=(s[3]===s[4].length-s[32]-1?"bg-hover2 hover:bg-hover2":"")+" title-container conversation flex justify-between min-h-[50px] py-1 pl-3 items-center rounded-md hover:bg-hover cursor-pointer text-sm transition-colors duration-200 svelte-2c65x7"),p(e,"tabindex","-1")},m(I,H){S(I,e,H),g.m(e,null),_(e,t),_(e,r),_(r,n),_(n,i),_(r,a),A&&A.m(r,null),_(e,o),E&&E.m(e,null),_(e,c),f||(d=[N(n,"click",Zt(y)),N(n,"keydown",Zt(k)),N(e,"click",w),N(e,"keydown",j)],f=!0)},p(I,H){s=I,m===(m=h(s))&&g?g.p(s,H):(g.d(1),g=m(s),g&&(g.c(),g.m(e,t))),s[4].length>=2?A?A.p(s,H):(A=ps(s),A.c(),A.m(r,null)):A&&(A.d(1),A=null),s[2]===!0?E?E.p(s,H):(E=ms(s),E.c(),E.m(e,c)):E&&(E.d(1),E=null),H[0]&24&&u!==(u=(s[3]===s[4].length-s[32]-1?"bg-hover2 hover:bg-hover2":"")+" title-container conversation flex justify-between min-h-[50px] py-1 pl-3 items-center rounded-md hover:bg-hover cursor-pointer text-sm transition-colors duration-200 svelte-2c65x7")&&p(e,"class",u)},d(I){I&&O(e),g.d(),A&&A.d(),E&&E.d(),f=!1,De(d)}}}function ra(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,m,g,y,k,A,E,w,j,I,H,ee,X,re=s[6]===null?"(Insert API key)":"",te,ae,$e,be;function Ae(M,D){return M[4][M[3]]?ea:Xo}let xe=Ae(s),T=xe(s),G=s[4].slice().reverse(),z=[];for(let M=0;MSystem Role:

',h=C(),T.c(),m=C(),g=b("div");for(let M=0;Mt(2,r=T)),_e(s,Ve,T=>t(27,n=T)),_e(s,mt,T=>t(28,i=T)),_e(s,Ee,T=>t(3,l=T)),_e(s,ue,T=>t(4,a=T)),_e(s,Qn,T=>t(5,o=T)),_e(s,ze,T=>t(6,c=T));const u=cn();let f="You are a helpful assistant.";function d(){u("new-chat")}function h(){tn.set(!1),en.set(!0)}function m(){en.set(!1),tn.set(!0)}async function g(T){if(console.log("Attempting to delete conversation at index:",T),a.length<=1){console.log("Deletion aborted: Cannot delete the last conversation.");return}let G=a.filter((z,M)=>M!==T);console.log("Updated conversations list after deletion attempt:",G),T===l?(Ee.set(T>0?T-1:0),console.log("Selected conversation index adjusted to:",T>0?T-1:0)):T{let z=[...G];return z[T].title=k,z}),t(0,y=null)}function w(){let G=JSON.stringify({conversations:a,chosenConversationId:l,defaultAssistantRole:i,selectedModel:n,showTokens:r}),z=new Blob([G],{type:"application/json"}),M=URL.createObjectURL(z),D=document.createElement("a");D.href=M,D.download="smoothgpt-session.json",D.click(),URL.revokeObjectURL(M)}function j(){let T=document.createElement("input");T.type="file",T.accept=".json",T.onchange=async G=>{let z=T.files[0],M=new FileReader;M.onload=async D=>{let q=D.target.result,F=JSON.parse(q);ue.set(F.conversations),Ee.set(F.chosenConversationId),mt.set(F.defaultAssistantRole),Ve.set(F.selectedModel),nn.set(F.showTokens)},M.readAsText(z)},T.click()}const I=()=>{Qn.set(!1)};function H(){a[l].assistantRole=this.value,ue.set(a)}function ee(){k=this.value,t(1,k)}return[y,k,r,l,a,o,c,f,d,h,m,g,A,E,w,j,I,H,ee,T=>E(a.length-T-1),(T,G)=>{G.key==="Enter"&&(E(a.length-T-1),G.preventDefault())},(T,G,z)=>{let M=a.length-T-1;A(M,G.title)},(T,G,z)=>{if(z.key==="Enter"){z.preventDefault();let M=a.length-T-1;A(M,G.title)}},(T,G)=>{let z=a.length-T-1;g(z)},(T,G)=>{if(G.key==="Enter"){G.preventDefault();let z=a.length-T-1;g(z)}},T=>{let G=a.length-T-1;Ee.set(G)},(T,G)=>{if(G.key==="Enter"){G.preventDefault();let z=a.length-T-1;Ee.set(z)}}]}class ia extends W{constructor(e){super(),Z(this,e,sa,ra,K,{},null,[-1,-1])}}function _s(s,e,t){const r=s.slice();return r[36]=e[t],r}function bs(s){let e,t=s[36].id+"",r,n;return{c(){e=b("option"),r=ce(t),e.__value=n=s[36].id,e.value=e.__value},m(i,l){S(i,e,l),_(e,r)},p(i,l){l[0]&256&&t!==(t=i[36].id+"")&&Te(r,t),l[0]&256&&n!==(n=i[36].id)&&(e.__value=n,e.value=e.__value)},d(i){i&&O(e)}}}function vs(s){let e,t,r,n,i,l,a,o,c,u,f,d;return{c(){e=b("div"),t=b("label"),t.textContent="Voice Selection",r=C(),n=b("select"),i=b("option"),i.textContent="Alloy",l=b("option"),l.textContent="Echo",a=b("option"),a.textContent="Fable",o=b("option"),o.textContent="Onyx",c=b("option"),c.textContent="Nova",u=b("option"),u.textContent="Shimmer",p(t,"for","voice-selection"),p(t,"class","block font-medium mb-2"),i.__value="alloy",i.value=i.__value,l.__value="echo",l.value=l.__value,a.__value="fable",a.value=a.__value,o.__value="onyx",o.value=o.__value,c.__value="nova",c.value=c.__value,u.__value="shimmer",u.value=u.__value,p(n,"class","border text-black border-gray-300 p-2 rounded w-full"),p(n,"id","voice-selection"),s[9]===void 0&&ft(()=>s[25].call(n)),p(e,"class","mb-4")},m(h,m){S(h,e,m),_(e,t),_(e,r),_(e,n),_(n,i),_(n,l),_(n,a),_(n,o),_(n,c),_(n,u),rt(n,s[9]),f||(d=N(n,"change",s[25]),f=!0)},p(h,m){m[0]&512&&rt(n,h[9])},d(h){h&&O(e),f=!1,d()}}}function la(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,m,g,y,k,A,E,w,j,I,H,ee,X,re,te,ae,$e,be,Ae,xe,T,G,z=s[7].startsWith("tts"),M,D,q,F,ve,Ie,fe,je,we,Ge,P,le,x,oe,Me,We,mr,Vt=s[10].toFixed(0)+"",gn,gr,Ct,_r,Bt=(s[10]/1e3*.02).toFixed(2)+"",_n,br,Lt,vr,Dt,ct,nt,Xe,wr,bn,yr,vn,kr,qt,Or,_t,bt,Sr,Ar,Rt,wn,$r,vt=s[8],Be=[];for(let ne=0;neSee all API pricing',vr=C(),Dt=b("div"),ct=b("label"),nt=b("div"),Xe=b("input"),wr=C(),bn=b("div"),yr=C(),vn=b("div"),kr=C(),qt=b("div"),qt.textContent="Show estimated tokens in sidebar",Or=C(),_t=b("button"),bt=b("img"),Ar=C(),Rt=b("button"),Rt.textContent="Save",p(i,"class","icon-white w-8"),p(i,"alt","Close"),Pe(i.src,l=ln)||p(i,"src",l),p(n,"class","absolute top-0 right-0 mt-2 mr-2 text-gray-500 hover:text-gray-600"),p(o,"class","text-xl font-bold mb-4"),p(f,"for","api-key"),p(f,"class","block font-medium mb-2"),p(m,"type","password"),p(m,"id","api-key"),p(m,"name","api-key"),p(m,"class","border text-black border-gray-300 p-2 rounded w-full"),p(y,"class","ml-2 bg-blue-600 hover:bg-blue-400 transition-colors duration-800 text-white p-2 rounded text-xs"),p(h,"class","flex items-center"),p(A,"class",w="mt-2 text-white rounded-lg p-2 "+(s[5]==="yellow"?"bg-yellow-600":"")+" "+(s[5]==="red"?"bg-red-600":"")+" "+(s[5]==="green"?"bg-green-600":"")),lt(A,"display",s[12]?"block":"none"),p(u,"class","mb-4"),p(H,"for","mode-selection"),p(H,"class","block font-medium mb-2"),re.__value="GPT",re.value=re.__value,te.__value="GPT + Vision",te.value=te.__value,ae.__value="TTS",ae.value=ae.__value,p(X,"class","border text-black border-gray-300 p-2 rounded w-full"),p(X,"id","mode-selection"),s[0]===void 0&&ft(()=>s[23].call(X)),p(I,"class","mb-4"),p(Ae,"for","model-selection"),p(Ae,"class","block font-medium mb-2"),p(T,"class","border text-black border-gray-300 p-2 rounded w-full"),p(T,"id","model-selection"),s[7]===void 0&&ft(()=>s[24].call(T)),p(be,"class","mb-4"),p(q,"for","api-key"),p(q,"class","block font-medium mb-2"),p(ve,"class","border text-black border-gray-300 p-2 rounded w-full"),we.__value="system",we.value=we.__value,Ge.__value="user",Ge.value=Ge.__value,p(je,"class","text-black p-2 rounded focus:outline-none focus:bg-white max-w-24"),s[3]===void 0&&ft(()=>s[27].call(je)),p(le,"href","https://platform.openai.com/docs/guides/prompt-engineering/tactic-ask-the-model-to-adopt-a-persona"),p(le,"target","_blank"),p(le,"rel","noreferrer"),p(le,"class","text-blue-300 transition underline text-xs hover:text-blue-500"),p(fe,"class","flex items-center my-2 space-x-2"),p(D,"class","mb-4"),p(We,"class","font-bold mb-2"),p(Ct,"class",""),p(Lt,"class","text-blue-300 transition underline text-xs hover:text-blue-500 mt-2"),p(Xe,"type","checkbox"),p(Xe,"id","show-tokens-toggle"),p(Xe,"class","sr-only"),p(bn,"class","block bg-gray-600 w-14 h-8 rounded-full"),p(vn,"class","dot absolute left-1 top-1 bg-gray-100 w-6 h-6 rounded-full transition"),p(nt,"class","relative"),p(qt,"class","ml-3 text-gray-200"),p(ct,"for","show-tokens-toggle"),p(ct,"class","flex items-center cursor-pointer"),p(Dt,"class","mt-4"),p(Me,"class","flex flex-col"),p(bt,"class","icon-white w-3"),p(bt,"alt","Close"),Pe(bt.src,Sr=ln)||p(bt,"src",Sr),p(_t,"class","bg-warning hover:bg-warningHover transition-colors duration-200 text-white ml-10 px-4 py-2 flex align-middle justify-center rounded"),lt(_t,"font-size","1rem"),p(oe,"class","flex justify-between items-start"),p(Rt,"class","bg-good hover:bg-good2 transition-colors duration-200 text-white py-2 px-4 mt-8 rounded"),p(r,"class","bg-primary text-white rounded-lg shadow-xl p-8 relative"),p(t,"class","flex items-center justify-center min-h-screen"),p(e,"class","fixed z-50 inset-0 overflow-y-auto animate-fade-in")},m(ne,Fe){S(ne,e,Fe),_(e,t),_(t,r),_(r,n),_(n,i),_(r,a),_(r,o),_(r,c),_(r,u),_(u,f),_(u,d),_(u,h),_(h,m),He(m,s[1]),_(h,g),_(h,y),_(u,k),_(u,A),_(A,E),_(r,j),_(r,I),_(I,H),_(I,ee),_(I,X),_(X,re),_(X,te),_(X,ae),rt(X,s[0]),_(r,$e),_(r,be),_(be,Ae),_(be,xe),_(be,T);for(let Ue=0;Uet(30,r=F)),_e(s,ze,F=>t(20,n=F)),_e(s,At,F=>t(0,l=F)),_e(s,Ve,F=>t(7,c=F)),_e(s,It,F=>t(9,f=F)),_e(s,pt,F=>t(10,d=F));const h=cn();let m=Se("");_e(s,m,F=>t(6,o=F));let g=Se("");_e(s,g,F=>t(5,a=F));let y=Se([]);_e(s,y,F=>t(21,i=F));let k=Se([]);_e(s,k,F=>t(8,u=F));let A=V(ze)||"",E="";ze.subscribe(F=>{E=F||"",t(1,A=E)});let w=r.role,j=r.type;ze.subscribe(F=>{localStorage.setItem("api_key",JSON.stringify(F))});let I=!1;nn.subscribe(F=>{t(4,I=F)}),an(async()=>{await X()});function H(){nn.set(I)}function ee(){let F=V(At),ve=V(y),Ie=[];F==="GPT"?Ie=ve.filter(fe=>fe.id.includes("gpt")&&!fe.id.includes("vision")):F==="GPT + Vision"?Ie=ve.filter(fe=>fe.id.includes("vision")):F==="TTS"&&(Ie=ve.filter(fe=>fe.id.includes("tts"))),k.set(Ie),Ie.length>0&&(!V(Ve)||!Ie.some(fe=>fe.id===V(Ve)))&&Ve.set(Ie[0].id)}async function X(){const F=localStorage.getItem("selectedMode");if(At.set(F||"GPT"),E)await te(E);else{const ve=localStorage.getItem("models");ve&&y.set(JSON.parse(ve))}ee()}async function re(){if(!A){g.set("yellow"),m.set("API key is missing.");return}try{const F=await fetch("https://api.openai.com/v1/models",{method:"GET",headers:{Authorization:`Bearer ${A}`,"Content-Type":"application/json"}});if(F.ok)g.set("green"),m.set("API connection succeeded."),$e(),await te(E),ee();else throw new Error(`HTTP error! status: ${F.status}`)}catch(F){console.error("API connection failed:",F),g.set("red"),m.set("API connection failed.")}}async function te(F){if(!F){g.set("yellow"),console.log("showMessage",g),console.error("API key is missing.");return}try{const ve=await fetch("https://api.openai.com/v1/models",{method:"GET",headers:{Authorization:`Bearer ${F}`,"Content-Type":"application/json"}});if(!ve.ok)throw new Error(`HTTP error! status: ${ve.status}`);const fe=(await ve.json()).data.sort((je,we)=>je.id.localeCompare(we.id));y.set(fe),localStorage.setItem("models",JSON.stringify(fe))}catch(ve){console.error("Failed to fetch models:",ve)}}function ae(){pt.set(0)}function $e(){mt.set({role:w,type:j}),ze.set(A),localStorage.setItem("selectedModel",V(Ve)),localStorage.setItem("selectedVoice",V(It)),localStorage.setItem("selectedMode",V(At)),h("settings-changed"),console.log("Settings saved.")}function be(){en.set(!1)}function Ae(){$e(),be()}function xe(){A=this.value,t(1,A),t(20,n)}function T(){l=zt(this),At.set(l)}function G(){c=zt(this),Ve.set(c)}function z(){f=zt(this),It.set(f)}function M(){w=this.value,t(2,w)}function D(){j=zt(this),t(3,j)}function q(){I=this.checked,t(4,I)}return s.$$.update=()=>{s.$$.dirty[0]&1&&ee(),s.$$.dirty[0]&2097152&&ee(),s.$$.dirty[0]&1048576&&t(1,A=n||"")},[l,A,w,j,I,a,o,c,u,f,d,m,g,y,k,H,re,ae,be,Ae,n,i,xe,T,G,z,M,D,q]}class aa extends W{constructor(e){super(),Z(this,e,oa,la,K,{},null,[-1,-1])}}function ca(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,m;return{c(){e=b("div"),t=b("div"),r=b("div"),n=b("button"),i=b("img"),a=C(),o=b("h2"),o.textContent="Help & FAQ",c=C(),u=b("div"),u.innerHTML=`

What is SmoothGPT?

-

OpenAI offers ChatGPT Plus for a monthly subscription, which allows you to use their UI to converse with ChatGPT. However, this comes with usage limits, and the $20/mo fee is expensive. Alternatively, you can use the OpenAI API, which is much more affordable with a pay-as-you-go rate. But, the API is not end-user friendly! It's designed for developers who can build apps around it.

-

That's where SmoothGPT comes in! SmoothGPT provides a UI that is extremely similar to the ChatGPT official site.

- -

Key Features:

-
  • Your API calls are safely made directly in the browser, not server-side. All data is stored in your browser cache or session.
  • -
  • Switch between GPT, Vision, and TTS models with shared conversation context.
  • -
  • Copy or delete messages easily.
  • -
  • Edit messages to change the conversation.
  • -
  • Safely stop incoming messages.
  • -
  • Edit conversation titles.
  • -
  • It's absolutely free.
- - - - - -

Note on data storage: If you browse away while a response is streaming in, you will miss that data. If you refresh your page, TTS MP3 files are lost, but conversations are maintained. If you wipe your browser cache, ALL content is lost. You can download your session locally and restore it anytime.

`,f=C(),d=b("button"),d.textContent="Got it!",p(i,"class","icon-white w-8"),p(i,"alt","Close"),Pe(i.src,l=ln)||p(i,"src",l),p(n,"class","absolute top-0 right-0 mt-2 mr-2 text-gray-500 hover:text-gray-600"),p(o,"class","text-xl font-bold mb-4"),p(u,"class","text-left"),p(d,"class","bg-good hover:bg-good2 transition-colors duration-200 text-white py-2 px-4 mt-4 rounded"),p(r,"class","bg-primary text-white rounded-lg shadow-xl p-8 relative max-w-lg mx-4"),p(t,"class","flex items-center justify-center min-h-screen"),p(e,"class","fixed z-50 inset-0 overflow-y-auto animate-fade-in")},m(g,y){S(g,e,y),_(e,t),_(t,r),_(r,n),_(n,i),_(r,a),_(r,o),_(r,c),_(r,u),_(r,f),_(r,d),h||(m=[N(n,"click",s[0]),N(d,"click",s[0])],h=!0)},p:B,i:B,o:B,d(g){g&&O(e),h=!1,De(m)}}}function ua(s){function e(){tn.set(!1)}return[e]}class fa extends W{constructor(e){super(),Z(this,e,ua,ca,K,{})}}function da(){const s=console.warn;console.warn=e=>{e.includes("unknown prop")||e.includes("unexpected slot")||s(e)},an(()=>{console.warn=s})}function ws(s,e,t){const r=s.slice();return r[18]=e[t],r}function ys(s,e,t){const r=s.slice();return r[18]=e[t],r}function ks(s,e,t){const r=s.slice();return r[10]=e[t],r}function Os(s,e,t){const r=s.slice();return r[13]=e[t],r[15]=t,r}function Ss(s,e,t){const r=s.slice();return r[16]=e[t],r[15]=t,r}function As(s,e,t){const r=s.slice();return r[7]=e[t],r}function ha(s){let e,t,r,n;const i=[_a,ga,ma],l=[];function a(o,c){return o[0]==="table"?0:o[0]==="list"?1:2}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function pa(s){let e,t,r=s[1],n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(u,1)}),ie()}i?(e=ke(i,l(a)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&v(e.$$.fragment,a),r=!0)},o(a){e&&$(e.$$.fragment,a),r=!1},d(a){a&&O(t),e&&Q(e,a)}}}function ga(s){let e,t,r,n;const i=[ka,ya],l=[];function a(o,c){return o[4]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function _a(s){let e,t,r;var n=s[5].table;function i(l){return{props:{$$slots:{default:[Ia]},$$scope:{ctx:l}}}}return n&&(e=ke(n,i(s))),{c(){e&&Y(e.$$.fragment),t=ye()},m(l,a){e&&J(e,l,a),S(l,t,a),r=!0},p(l,a){const o={};if(a&8388716&&(o.$$scope={dirty:a,ctx:l}),n!==(n=l[5].table)){if(e){se();const c=e;$(c.$$.fragment,1,0,()=>{Q(c,1)}),ie()}n?(e=ke(n,i(l)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&v(e.$$.fragment,l),r=!0)},o(l){e&&$(e.$$.fragment,l),r=!1},d(l){l&&O(t),e&&Q(e,l)}}}function ba(s){let e=s[6].raw+"",t;return{c(){t=ce(e)},m(r,n){S(r,t,n)},p(r,n){n&64&&e!==(e=r[6].raw+"")&&Te(t,e)},i:B,o:B,d(r){r&&O(t)}}}function va(s){let e,t;return e=new gt({props:{tokens:s[1],renderers:s[5]}}),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},p(r,n){const i={};n&2&&(i.tokens=r[1]),n&32&&(i.renderers=r[5]),e.$set(i)},i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function wa(s){let e,t,r,n;const i=[va,ba],l=[];function a(o,c){return o[1]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function ya(s){let e,t,r;const n=[{ordered:s[4]},s[6]];var i=s[5].list;function l(a){let o={$$slots:{default:[Sa]},$$scope:{ctx:a}};for(let c=0;c{Q(u,1)}),ie()}i?(e=ke(i,l(a)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&v(e.$$.fragment,a),r=!0)},o(a){e&&$(e.$$.fragment,a),r=!1},d(a){a&&O(t),e&&Q(e,a)}}}function ka(s){let e,t,r;const n=[{ordered:s[4]},s[6]];var i=s[5].list;function l(a){let o={$$slots:{default:[$a]},$$scope:{ctx:a}};for(let c=0;c{Q(u,1)}),ie()}i?(e=ke(i,l(a)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&v(e.$$.fragment,a),r=!0)},o(a){e&&$(e.$$.fragment,a),r=!1},d(a){a&&O(t),e&&Q(e,a)}}}function Oa(s){let e,t,r;return e=new gt({props:{tokens:s[18].tokens,renderers:s[5]}}),{c(){Y(e.$$.fragment),t=C()},m(n,i){J(e,n,i),S(n,t,i),r=!0},p(n,i){const l={};i&64&&(l.tokens=n[18].tokens),i&32&&(l.renderers=n[5]),e.$set(l)},i(n){r||(v(e.$$.fragment,n),r=!0)},o(n){$(e.$$.fragment,n),r=!1},d(n){Q(e,n),n&&O(t)}}}function $s(s){let e,t,r;const n=[s[18]];var i=s[5].unorderedlistitem||s[5].listitem;function l(a){let o={$$slots:{default:[Oa]},$$scope:{ctx:a}};for(let c=0;c{Q(u,1)}),ie()}i?(e=ke(i,l(a)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&v(e.$$.fragment,a),r=!0)},o(a){e&&$(e.$$.fragment,a),r=!1},d(a){a&&O(t),e&&Q(e,a)}}}function Sa(s){let e,t,r=s[6].items,n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(u,1)}),ie()}i?(e=ke(i,l(a)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&v(e.$$.fragment,a),r=!0)},o(a){e&&$(e.$$.fragment,a),r=!1},d(a){a&&O(t),e&&Q(e,a)}}}function $a(s){let e,t,r=s[6].items,n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(c,1)}),ie()}n?(e=ke(n,i(l)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&v(e.$$.fragment,l),r=!0)},o(l){e&&$(e.$$.fragment,l),r=!1},d(l){l&&O(t),e&&Q(e,l)}}}function Ta(s){let e,t,r=s[2],n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(c,1)}),ie()}n?(e=ke(n,i(l)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&v(e.$$.fragment,l),r=!0)},o(l){e&&$(e.$$.fragment,l),r=!1},d(l){l&&O(t),e&&Q(e,l)}}}function Ca(s){let e,t;return e=new gt({props:{tokens:s[13].tokens,renderers:s[5]}}),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},p(r,n){const i={};n&8&&(i.tokens=r[13].tokens),n&32&&(i.renderers=r[5]),e.$set(i)},i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function Ps(s){let e,t,r;var n=s[5].tablecell;function i(l){return{props:{header:!1,align:l[6].align[l[15]]||"center",$$slots:{default:[Ca]},$$scope:{ctx:l}}}}return n&&(e=ke(n,i(s))),{c(){e&&Y(e.$$.fragment),t=ye()},m(l,a){e&&J(e,l,a),S(l,t,a),r=!0},p(l,a){const o={};if(a&64&&(o.align=l[6].align[l[15]]||"center"),a&8388648&&(o.$$scope={dirty:a,ctx:l}),n!==(n=l[5].tablecell)){if(e){se();const c=e;$(c.$$.fragment,1,0,()=>{Q(c,1)}),ie()}n?(e=ke(n,i(l)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&v(e.$$.fragment,l),r=!0)},o(l){e&&$(e.$$.fragment,l),r=!1},d(l){l&&O(t),e&&Q(e,l)}}}function Ra(s){let e,t,r=s[10],n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(c,1)}),ie()}n?(e=ke(n,i(l)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&v(e.$$.fragment,l),r=!0)},o(l){e&&$(e.$$.fragment,l),r=!1},d(l){l&&O(t),e&&Q(e,l)}}}function xa(s){let e,t,r=s[3],n=[];for(let l=0;l$(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{Q(m,1)}),ie()}l?(e=ke(l,a(u)),Y(e.$$.fragment),v(e.$$.fragment,1),J(e,t.parentNode,t)):e=null}else l&&e.$set(d);const h={};if(f&8388712&&(h.$$scope={dirty:f,ctx:u}),o!==(o=u[5].tablebody)){if(r){se();const m=r;$(m.$$.fragment,1,0,()=>{Q(m,1)}),ie()}o?(r=ke(o,c(u)),Y(r.$$.fragment),v(r.$$.fragment,1),J(r,n.parentNode,n)):r=null}else o&&r.$set(h)},i(u){i||(e&&v(e.$$.fragment,u),r&&v(r.$$.fragment,u),i=!0)},o(u){e&&$(e.$$.fragment,u),r&&$(r.$$.fragment,u),i=!1},d(u){e&&Q(e,u),u&&O(t),u&&O(n),r&&Q(r,u)}}}function Rs(s){let e,t;const r=[s[7],{renderers:s[5]}];let n={};for(let i=0;i{l[u]=null}),ie()),~e?(t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r)):t=null)},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){~e&&l[e].d(o),o&&O(r)}}}function Ma(s,e,t){const r=["type","tokens","header","rows","ordered","renderers"];let n=Pr(e,r),{type:i=void 0}=e,{tokens:l=void 0}=e,{header:a=void 0}=e,{rows:o=void 0}=e,{ordered:c=!1}=e,{renderers:u}=e;return da(),s.$$set=f=>{e=et(et({},e),Ii(f)),t(6,n=Pr(e,r)),"type"in f&&t(0,i=f.type),"tokens"in f&&t(1,l=f.tokens),"header"in f&&t(2,a=f.header),"rows"in f&&t(3,o=f.rows),"ordered"in f&&t(4,c=f.ordered),"renderers"in f&&t(5,u=f.renderers)},[i,l,a,o,c,u,n]}let gt=class extends W{constructor(e){super(),Z(this,e,Ma,ja,K,{type:0,tokens:1,header:2,rows:3,ordered:4,renderers:5})}};function Si(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Pt=Si();function Fa(s){Pt=s}const Ai=/[&<>"']/,Ua=new RegExp(Ai.source,"g"),$i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Va=new RegExp($i.source,"g"),Ba={"&":"&","<":"<",">":">",'"':""","'":"'"},xs=s=>Ba[s];function Re(s,e){if(e){if(Ai.test(s))return s.replace(Ua,xs)}else if($i.test(s))return s.replace(Va,xs);return s}const La=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Ei(s){return s.replace(La,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const Da=/(^|[^\[])\^/g;function ge(s,e){s=typeof s=="string"?s:s.source,e=e||"";const t={replace:(r,n)=>(n=n.source||n,n=n.replace(Da,"$1"),s=s.replace(r,n),t),getRegex:()=>new RegExp(s,e)};return t}const qa=/[^\w:]/g,Na=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Is(s,e,t){if(s){let r;try{r=decodeURIComponent(Ei(t)).replace(qa,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}e&&!Na.test(t)&&(t=Ja(e,t));try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}const Ht={},za=/^[^:]+:\/*[^/]*$/,Ha=/^([^:]+:)[\s\S]*$/,Ga=/^([^:]+:\/*[^/]*)[\s\S]*$/;function Ja(s,e){Ht[" "+s]||(za.test(s)?Ht[" "+s]=s+"/":Ht[" "+s]=Kt(s,"/",!0)),s=Ht[" "+s];const t=s.indexOf(":")===-1;return e.substring(0,2)==="//"?t?e:s.replace(Ha,"$1")+e:e.charAt(0)==="/"?t?e:s.replace(Ga,"$1")+e:s+e}const on={exec:function(){}};function Je(s){let e=1,t,r;for(;e{let o=!1,c=l;for(;--c>=0&&a[c]==="\\";)o=!o;return o?"|":" |"}),r=t.split(/ \|/);let n=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>e)r.splice(e);else for(;r.length1;)e&1&&(t+=s),e>>=1,s+=s;return t+s}function Fs(s,e,t,r){const n=e.href,i=e.title?Re(e.title):null,l=s[1].replace(/\\([\[\]])/g,"$1");if(s[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:t,href:n,title:i,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}return{type:"image",raw:t,href:n,title:i,text:Re(l)}}function Ya(s,e){const t=s.match(/^(\s+)(?:```)/);if(t===null)return e;const r=t[1];return e.split(` -`).map(n=>{const i=n.match(/^\s+/);if(i===null)return n;const[l]=i;return l.length>=r.length?n.slice(r.length):n}).join(` -`)}class dr{constructor(e){this.options=e||Pt}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const r=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Kt(r,` -`)}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const r=t[0],n=Ya(r,t[3]||"");return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline._escapes,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(/#$/.test(r)){const n=Kt(r,"#");(this.options.pedantic||!n||/ $/.test(n))&&(r=n.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const r=t[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const i=this.lexer.blockTokens(r);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r,n,i,l,a,o,c,u,f,d,h,m,g=t[1].trim();const y=g.length>1,k={type:"list",raw:"",ordered:y,start:y?+g.slice(0,-1):"",loose:!1,items:[]};g=y?`\\d{1,9}\\${g.slice(-1)}`:`\\${g}`,this.options.pedantic&&(g=y?g:"[*+-]");const A=new RegExp(`^( {0,3}${g})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;e&&(m=!1,!(!(t=A.exec(e))||this.rules.block.hr.test(e)));){if(r=t[0],e=e.substring(r.length),u=t[2].split(` -`,1)[0].replace(/^\t+/,w=>" ".repeat(3*w.length)),f=e.split(` -`,1)[0],this.options.pedantic?(l=2,h=u.trimLeft()):(l=t[2].search(/[^ ]/),l=l>4?1:l,h=u.slice(l),l+=t[1].length),o=!1,!u&&/^ *$/.test(f)&&(r+=f+` -`,e=e.substring(f.length+1),m=!0),!m){const w=new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),j=new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),I=new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),H=new RegExp(`^ {0,${Math.min(3,l-1)}}#`);for(;e&&(d=e.split(` -`,1)[0],f=d,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(I.test(f)||H.test(f)||w.test(f)||j.test(e)));){if(f.search(/[^ ]/)>=l||!f.trim())h+=` -`+f.slice(l);else{if(o||u.search(/[^ ]/)>=4||I.test(u)||H.test(u)||j.test(u))break;h+=` -`+f}!o&&!f.trim()&&(o=!0),r+=d+` -`,e=e.substring(d.length+1),u=f.slice(l)}}k.loose||(c?k.loose=!0:/\n *\n *$/.test(r)&&(c=!0)),this.options.gfm&&(n=/^\[[ xX]\] /.exec(h),n&&(i=n[0]!=="[ ] ",h=h.replace(/^\[[ xX]\] +/,""))),k.items.push({type:"list_item",raw:r,task:!!n,checked:i,loose:!1,text:h}),k.raw+=r}k.items[k.items.length-1].raw=r.trimRight(),k.items[k.items.length-1].text=h.trimRight(),k.raw=k.raw.trimRight();const E=k.items.length;for(a=0;aI.type==="space"),j=w.length>0&&w.some(I=>/\n.*\n/.test(I.raw));k.loose=j}if(k.loose)for(a=0;a$/,"$1").replace(this.rules.inline._escapes,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline._escapes,"$1"):t[3];return{type:"def",tag:r,raw:t[0],href:n,title:i}}}table(e){const t=this.rules.block.table.exec(e);if(t){const r={type:"table",header:js(t[1]).map(n=>({text:n})),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(` -`):[]};if(r.header.length===r.align.length){r.raw=t[0];let n=r.align.length,i,l,a,o;for(i=0;i({text:c}));for(n=r.header.length,l=0;l/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):Re(t[0]):t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const r=t[2].trim();if(!this.options.pedantic&&/^$/.test(r))return;const l=Kt(r.slice(0,-1),"\\");if((r.length-l.length)%2===0)return}else{const l=Qa(t[2],"()");if(l>-1){const o=(t[0].indexOf("!")===0?5:4)+t[1].length+l;t[2]=t[2].substring(0,l),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){const l=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);l&&(n=l[1],i=l[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^$/.test(r)?n=n.slice(1):n=n.slice(1,-1)),Fs(t,{href:n&&n.replace(this.rules.inline._escapes,"$1"),title:i&&i.replace(this.rules.inline._escapes,"$1")},t[0],this.lexer)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(/\s+/g," ");if(n=t[n.toLowerCase()],!n){const i=r[0].charAt(0);return{type:"text",raw:i,text:i}}return Fs(r,n,r[0],this.lexer)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrong.lDelim.exec(e);if(!n||n[3]&&r.match(/[\p{L}\p{N}]/u))return;const i=n[1]||n[2]||"";if(!i||i&&(r===""||this.rules.inline.punctuation.exec(r))){const l=n[0].length-1;let a,o,c=l,u=0;const f=n[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+l);(n=f.exec(t))!=null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a)continue;if(o=a.length,n[3]||n[4]){c+=o;continue}else if((n[5]||n[6])&&l%3&&!((l+o)%3)){u+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c+u);const d=e.slice(0,l+n.index+(n[0].length-a.length)+o);if(Math.min(l,o)%2){const m=d.slice(1,-1);return{type:"em",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}const h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(/\n/g," ");const n=/[^ ]/.test(r),i=/^ /.test(r)&&/ $/.test(r);return n&&i&&(r=r.substring(1,r.length-1)),r=Re(r,!0),{type:"codespan",raw:t[0],text:r}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e,t){const r=this.rules.inline.autolink.exec(e);if(r){let n,i;return r[2]==="@"?(n=Re(this.options.mangle?t(r[1]):r[1]),i="mailto:"+n):(n=Re(r[1]),i=n),{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e,t){let r;if(r=this.rules.inline.url.exec(e)){let n,i;if(r[2]==="@")n=Re(this.options.mangle?t(r[0]):r[0]),i="mailto:"+n;else{let l;do l=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(l!==r[0]);n=Re(r[0]),r[1]==="www."?i="http://"+r[0]:i=r[0]}return{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e,t){const r=this.rules.inline.text.exec(e);if(r){let n;return this.lexer.state.inRawBlock?n=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):Re(r[0]):r[0]:n=Re(this.options.smartypants?t(r[0]):r[0]),{type:"text",raw:r[0],text:n}}}}const U={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:on,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};U._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/;U._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;U.def=ge(U.def).replace("label",U._label).replace("title",U._title).getRegex();U.bullet=/(?:[*+-]|\d{1,9}[.)])/;U.listItemStart=ge(/^( *)(bull) */).replace("bull",U.bullet).getRegex();U.list=ge(U.list).replace(/bull/g,U.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+U.def.source+")").getRegex();U._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";U._comment=/|$)/;U.html=ge(U.html,"i").replace("comment",U._comment).replace("tag",U._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();U.paragraph=ge(U._paragraph).replace("hr",U.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",U._tag).getRegex();U.blockquote=ge(U.blockquote).replace("paragraph",U.paragraph).getRegex();U.normal=Je({},U);U.gfm=Je({},U.normal,{table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"});U.gfm.table=ge(U.gfm.table).replace("hr",U.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",U._tag).getRegex();U.gfm.paragraph=ge(U._paragraph).replace("hr",U.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",U.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",U._tag).getRegex();U.pedantic=Je({},U.normal,{html:ge(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",U._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:on,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ge(U.normal._paragraph).replace("hr",U.hr).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",U.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});const R={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:on,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:on,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~";R.punctuation=ge(R.punctuation).replace(/punctuation/g,R._punctuation).getRegex();R.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;R.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g;R._comment=ge(U._comment).replace("(?:-->|$)","-->").getRegex();R.emStrong.lDelim=ge(R.emStrong.lDelim).replace(/punct/g,R._punctuation).getRegex();R.emStrong.rDelimAst=ge(R.emStrong.rDelimAst,"g").replace(/punct/g,R._punctuation).getRegex();R.emStrong.rDelimUnd=ge(R.emStrong.rDelimUnd,"g").replace(/punct/g,R._punctuation).getRegex();R._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;R._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;R._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;R.autolink=ge(R.autolink).replace("scheme",R._scheme).replace("email",R._email).getRegex();R._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;R.tag=ge(R.tag).replace("comment",R._comment).replace("attribute",R._attribute).getRegex();R._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;R._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;R._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;R.link=ge(R.link).replace("label",R._label).replace("href",R._href).replace("title",R._title).getRegex();R.reflink=ge(R.reflink).replace("label",R._label).replace("ref",U._label).getRegex();R.nolink=ge(R.nolink).replace("ref",U._label).getRegex();R.reflinkSearch=ge(R.reflinkSearch,"g").replace("reflink",R.reflink).replace("nolink",R.nolink).getRegex();R.normal=Je({},R);R.pedantic=Je({},R.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:ge(/^!?\[(label)\]\((.*?)\)/).replace("label",R._label).getRegex(),reflink:ge(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",R._label).getRegex()});R.gfm=Je({},R.normal,{escape:ge(R.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\.5&&(r="x"+r.toString(16)),e+="&#"+r+";";return e}class Ke{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Pt,this.options.tokenizer=this.options.tokenizer||new dr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={block:U.normal,inline:R.normal};this.options.pedantic?(t.block=U.pedantic,t.inline=R.pedantic):this.options.gfm&&(t.block=U.gfm,this.options.breaks?t.inline=R.breaks:t.inline=R.gfm),this.tokenizer.rules=t}static get rules(){return{block:U,inline:R}}static lex(e,t){return new Ke(t).lex(e)}static lexInline(e,t){return new Ke(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,` -`),this.blockTokens(e,this.tokens);let t;for(;t=this.inlineQueue.shift();)this.inlineTokens(t.src,t.tokens);return this.tokens}blockTokens(e,t=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(a,o,c)=>o+" ".repeat(c.length));let r,n,i,l;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(r=a.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))){if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length),r.raw.length===1&&t.length>0?t[t.length-1].raw+=` -`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=` -`+r.raw,n.text+=` -`+r.text,this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=` -`+r.raw,n.text+=` -`+r.raw,this.inlineQueue[this.inlineQueue.length-1].src=n.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title});continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(i=e,this.options.extensions&&this.options.extensions.startBlock){let a=1/0;const o=e.slice(1);let c;this.options.extensions.startBlock.forEach(function(u){c=u.call({lexer:this},o),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(i=e.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){n=t[t.length-1],l&&n.type==="paragraph"?(n.raw+=` -`+r.raw,n.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r),l=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&n.type==="text"?(n.raw+=` -`+r.raw,n.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r);continue}if(e){const a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let r,n,i,l=e,a,o,c;if(this.tokens.links){const u=Object.keys(this.tokens.links);if(u.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(l))!=null;)u.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(l=l.slice(0,a.index)+"["+Ms("a",a[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(l))!=null;)l=l.slice(0,a.index)+"["+Ms("a",a[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(l))!=null;)l=l.slice(0,a.index+a[0].length-2)+"++"+l.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;e;)if(o||(c=""),o=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(r=u.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))){if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&r.type==="text"&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length),n=t[t.length-1],n&&r.type==="text"&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,l,c)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e,Us)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e,Us))){e=e.substring(r.raw.length),t.push(r);continue}if(i=e,this.options.extensions&&this.options.extensions.startInline){let u=1/0;const f=e.slice(1);let d;this.options.extensions.startInline.forEach(function(h){d=h.call({lexer:this},f),typeof d=="number"&&d>=0&&(u=Math.min(u,d))}),u<1/0&&u>=0&&(i=e.substring(0,u+1))}if(r=this.tokenizer.inlineText(i,Ka)){e=e.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(c=r.raw.slice(-1)),o=!0,n=t[t.length-1],n&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){const u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}}class hr{constructor(e){this.options=e||Pt}code(e,t,r){const n=(t||"").match(/\S*/)[0];if(this.options.highlight){const i=this.options.highlight(e,n);i!=null&&i!==e&&(r=!0,e=i)}return e=e.replace(/\n$/,"")+` -`,n?'
'+(r?e:Re(e,!0))+`
-`:"
"+(r?e:Re(e,!0))+`
-`}blockquote(e){return`
-${e}
-`}html(e){return e}heading(e,t,r,n){if(this.options.headerIds){const i=this.options.headerPrefix+n.slug(r);return`${e} -`}return`${e} -`}hr(){return this.options.xhtml?`
-`:`
-`}list(e,t,r){const n=t?"ol":"ul",i=t&&r!==1?' start="'+r+'"':"";return"<"+n+i+`> -`+e+" -`}listitem(e){return`
  • ${e}
  • -`}checkbox(e){return" "}paragraph(e){return`

    ${e}

    -`}table(e,t){return t&&(t=`${t}`),` - -`+e+` -`+t+`
    -`}tablerow(e){return` -${e} -`}tablecell(e,t){const r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+` -`}strong(e){return`${e}`}em(e){return`${e}`}codespan(e){return`${e}`}br(){return this.options.xhtml?"
    ":"
    "}del(e){return`${e}`}link(e,t,r){if(e=Is(this.options.sanitize,this.options.baseUrl,e),e===null)return r;let n='",n}image(e,t,r){if(e=Is(this.options.sanitize,this.options.baseUrl,e),e===null)return r;let n=`${r}":">",n}text(e){return e}}class Pi{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,r){return""+r}image(e,t,r){return""+r}br(){return""}}class pr{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let r=e,n=0;if(this.seen.hasOwnProperty(r)){n=this.seen[e];do n++,r=e+"-"+n;while(this.seen.hasOwnProperty(r))}return t||(this.seen[e]=n,this.seen[r]=0),r}slug(e,t={}){const r=this.serialize(e);return this.getNextSafeSlug(r,t.dryrun)}}class Ye{constructor(e){this.options=e||Pt,this.options.renderer=this.options.renderer||new hr,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Pi,this.slugger=new pr}static parse(e,t){return new Ye(t).parse(e)}static parseInline(e,t){return new Ye(t).parseInline(e)}parse(e,t=!0){let r="",n,i,l,a,o,c,u,f,d,h,m,g,y,k,A,E,w,j,I;const H=e.length;for(n=0;n0&&A.tokens[0].type==="paragraph"?(A.tokens[0].text=j+" "+A.tokens[0].text,A.tokens[0].tokens&&A.tokens[0].tokens.length>0&&A.tokens[0].tokens[0].type==="text"&&(A.tokens[0].tokens[0].text=j+" "+A.tokens[0].tokens[0].text)):A.tokens.unshift({type:"text",text:j}):k+=j),k+=this.parse(A.tokens,y),d+=this.renderer.listitem(k,w,E);r+=this.renderer.list(d,m,g);continue}case"html":{r+=this.renderer.html(h.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(h.tokens));continue}case"text":{for(d=h.tokens?this.parseInline(h.tokens):h.text;n+1"u"||s===null)throw new Error("marked(): input parameter is undefined or null");if(typeof s!="string")throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(s)+", string expected");if(typeof e=="function"&&(t=e,e=null),e=Je({},L.defaults,e||{}),Ti(e),t){const n=e.highlight;let i;try{i=Ke.lex(s,e)}catch(o){return t(o)}const l=function(o){let c;if(!o)try{e.walkTokens&&L.walkTokens(i,e.walkTokens),c=Ye.parse(i,e)}catch(u){o=u}return e.highlight=n,o?t(o):t(null,c)};if(!n||n.length<3||(delete e.highlight,!i.length))return l();let a=0;L.walkTokens(i,function(o){o.type==="code"&&(a++,setTimeout(()=>{n(o.text,o.lang,function(c,u){if(c)return l(c);u!=null&&u!==o.text&&(o.text=u,o.escaped=!0),a--,a===0&&l()})},0))}),a===0&&l();return}function r(n){if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+Re(n.message+"",!0)+"
    ";throw n}try{const n=Ke.lex(s,e);if(e.walkTokens){if(e.async)return Promise.all(L.walkTokens(n,e.walkTokens)).then(()=>Ye.parse(n,e)).catch(r);L.walkTokens(n,e.walkTokens)}return Ye.parse(n,e)}catch(n){r(n)}}L.options=L.setOptions=function(s){return Je(L.defaults,s),Fa(L.defaults),L};L.getDefaults=Si;L.defaults=Pt;L.use=function(...s){const e=L.defaults.extensions||{renderers:{},childTokens:{}};s.forEach(t=>{const r=Je({},t);if(r.async=L.defaults.async||r.async,t.extensions&&(t.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if(n.renderer){const i=e.renderers[n.name];i?e.renderers[n.name]=function(...l){let a=n.renderer.apply(this,l);return a===!1&&(a=i.apply(this,l)),a}:e.renderers[n.name]=n.renderer}if(n.tokenizer){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");e[n.level]?e[n.level].unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),r.extensions=e),t.renderer){const n=L.defaults.renderer||new hr;for(const i in t.renderer){const l=n[i];n[i]=(...a)=>{let o=t.renderer[i].apply(n,a);return o===!1&&(o=l.apply(n,a)),o}}r.renderer=n}if(t.tokenizer){const n=L.defaults.tokenizer||new dr;for(const i in t.tokenizer){const l=n[i];n[i]=(...a)=>{let o=t.tokenizer[i].apply(n,a);return o===!1&&(o=l.apply(n,a)),o}}r.tokenizer=n}if(t.walkTokens){const n=L.defaults.walkTokens;r.walkTokens=function(i){let l=[];return l.push(t.walkTokens.call(this,i)),n&&(l=l.concat(n.call(this,i))),l}}L.setOptions(r)})};L.walkTokens=function(s,e){let t=[];for(const r of s)switch(t=t.concat(e.call(L,r)),r.type){case"table":{for(const n of r.header)t=t.concat(L.walkTokens(n.tokens,e));for(const n of r.rows)for(const i of n)t=t.concat(L.walkTokens(i.tokens,e));break}case"list":{t=t.concat(L.walkTokens(r.items,e));break}default:L.defaults.extensions&&L.defaults.extensions.childTokens&&L.defaults.extensions.childTokens[r.type]?L.defaults.extensions.childTokens[r.type].forEach(function(n){t=t.concat(L.walkTokens(r[n],e))}):r.tokens&&(t=t.concat(L.walkTokens(r.tokens,e)))}return t};L.parseInline=function(s,e){if(typeof s>"u"||s===null)throw new Error("marked.parseInline(): input parameter is undefined or null");if(typeof s!="string")throw new Error("marked.parseInline(): input parameter is of type "+Object.prototype.toString.call(s)+", string expected");e=Je({},L.defaults,e||{}),Ti(e);try{const t=Ke.lexInline(s,e);return e.walkTokens&&L.walkTokens(t,e.walkTokens),Ye.parseInline(t,e)}catch(t){if(t.message+=` -Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+Re(t.message+"",!0)+"
    ";throw t}};L.Parser=Ye;L.parser=Ye.parse;L.Renderer=hr;L.TextRenderer=Pi;L.Lexer=Ke;L.lexer=Ke.lex;L.Tokenizer=dr;L.Slugger=pr;L.parse=L;L.options;L.setOptions;L.use;L.walkTokens;L.parseInline;Ye.parse;Ke.lex;const Ci={};function Za(s){let e;return{c(){e=ce(s[1])},m(t,r){S(t,e,r)},p(t,r){r&2&&Te(e,t[1])},i:B,o:B,d(t){t&&O(e)}}}function Wa(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h6"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Xa(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h5"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function ec(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h4"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function tc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h3"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function nc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h2"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function rc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h1"),n&&n.c(),p(e,"id",s[2])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function sc(s){let e,t,r,n;const i=[rc,nc,tc,ec,Xa,Wa,Za],l=[];function a(o,c){return o[0]===1?0:o[0]===2?1:o[0]===3?2:o[0]===4?3:o[0]===5?4:o[0]===6?5:6}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function ic(s,e,t){let r,{$$slots:n={},$$scope:i}=e,{depth:l}=e,{raw:a}=e,{text:o}=e;const{slug:c,getOptions:u}=Di(Ci),f=u();return s.$$set=d=>{"depth"in d&&t(0,l=d.depth),"raw"in d&&t(1,a=d.raw),"text"in d&&t(3,o=d.text),"$$scope"in d&&t(4,i=d.$$scope)},s.$$.update=()=>{s.$$.dirty&8&&t(2,r=f.headerIds?f.headerPrefix+c(o):void 0)},[l,a,r,o,i,n]}class lc extends W{constructor(e){super(),Z(this,e,ic,sc,K,{depth:0,raw:1,text:3})}}function oc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("p"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function ac(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let cc=class extends W{constructor(e){super(),Z(this,e,ac,oc,K,{})}};function uc(s){let e;const t=s[3].default,r=de(t,s,s[2],null);return{c(){r&&r.c()},m(n,i){r&&r.m(n,i),e=!0},p(n,[i]){r&&r.p&&(!e||i&4)&&pe(r,t,n,n[2],e?he(t,n[2],i,null):me(n[2]),null)},i(n){e||(v(r,n),e=!0)},o(n){$(r,n),e=!1},d(n){r&&r.d(n)}}}function fc(s,e,t){let{$$slots:r={},$$scope:n}=e,{text:i}=e,{raw:l}=e;return s.$$set=a=>{"text"in a&&t(0,i=a.text),"raw"in a&&t(1,l=a.raw),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class dc extends W{constructor(e){super(),Z(this,e,fc,uc,K,{text:0,raw:1})}}function hc(s){let e,t;return{c(){e=b("img"),Pe(e.src,t=s[0])||p(e,"src",t),p(e,"title",s[1]),p(e,"alt",s[2])},m(r,n){S(r,e,n)},p(r,[n]){n&1&&!Pe(e.src,t=r[0])&&p(e,"src",t),n&2&&p(e,"title",r[1]),n&4&&p(e,"alt",r[2])},i:B,o:B,d(r){r&&O(e)}}}function pc(s,e,t){let{href:r=""}=e,{title:n=void 0}=e,{text:i=""}=e;return s.$$set=l=>{"href"in l&&t(0,r=l.href),"title"in l&&t(1,n=l.title),"text"in l&&t(2,i=l.text)},[r,n,i]}class mc extends W{constructor(e){super(),Z(this,e,pc,hc,K,{href:0,title:1,text:2})}}function gc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("a"),n&&n.c(),p(e,"href",s[0]),p(e,"title",s[1])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&1)&&p(e,"href",i[0]),(!t||l&2)&&p(e,"title",i[1])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function _c(s,e,t){let{$$slots:r={},$$scope:n}=e,{href:i=""}=e,{title:l=void 0}=e;return s.$$set=a=>{"href"in a&&t(0,i=a.href),"title"in a&&t(1,l=a.title),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class bc extends W{constructor(e){super(),Z(this,e,_c,gc,K,{href:0,title:1})}}function vc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("em"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function wc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let yc=class extends W{constructor(e){super(),Z(this,e,wc,vc,K,{})}};function kc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("del"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Oc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Sc extends W{constructor(e){super(),Z(this,e,Oc,kc,K,{})}}function Ac(s){let e,t=s[0].replace(/`/g,"")+"",r;return{c(){e=b("code"),r=ce(t)},m(n,i){S(n,e,i),_(e,r)},p(n,[i]){i&1&&t!==(t=n[0].replace(/`/g,"")+"")&&Te(r,t)},i:B,o:B,d(n){n&&O(e)}}}function $c(s,e,t){let{raw:r}=e;return s.$$set=n=>{"raw"in n&&t(0,r=n.raw)},[r]}class Ec extends W{constructor(e){super(),Z(this,e,$c,Ac,K,{raw:0})}}function Tc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("strong"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Pc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Cc extends W{constructor(e){super(),Z(this,e,Pc,Tc,K,{})}}function Rc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("table"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function xc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Ic extends W{constructor(e){super(),Z(this,e,xc,Rc,K,{})}}function jc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("thead"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Mc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Fc extends W{constructor(e){super(),Z(this,e,Mc,jc,K,{})}}function Uc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("tbody"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Vc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Bc extends W{constructor(e){super(),Z(this,e,Vc,Uc,K,{})}}function Lc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("tr"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Dc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class qc extends W{constructor(e){super(),Z(this,e,Dc,Lc,K,{})}}function Nc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("td"),n&&n.c(),p(e,"align",s[1])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"align",i[1])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function zc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("th"),n&&n.c(),p(e,"align",s[1])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"align",i[1])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Hc(s){let e,t,r,n;const i=[zc,Nc],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function Gc(s,e,t){let{$$slots:r={},$$scope:n}=e,{header:i}=e,{align:l}=e;return s.$$set=a=>{"header"in a&&t(0,i=a.header),"align"in a&&t(1,l=a.align),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class Jc extends W{constructor(e){super(),Z(this,e,Gc,Hc,K,{header:0,align:1})}}function Qc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ul"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Yc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ol"),n&&n.c(),p(e,"start",s[1])},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"start",i[1])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Kc(s){let e,t,r,n;const i=[Yc,Qc],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function Zc(s,e,t){let{$$slots:r={},$$scope:n}=e,{ordered:i}=e,{start:l}=e;return s.$$set=a=>{"ordered"in a&&t(0,i=a.ordered),"start"in a&&t(1,l=a.start),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class Wc extends W{constructor(e){super(),Z(this,e,Zc,Kc,K,{ordered:0,start:1})}}function Xc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("li"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function eu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let tu=class extends W{constructor(e){super(),Z(this,e,eu,Xc,K,{})}};function nu(s){let e;return{c(){e=b("hr")},m(t,r){S(t,e,r)},p:B,i:B,o:B,d(t){t&&O(e)}}}class ru extends W{constructor(e){super(),Z(this,e,null,nu,K,{})}}function su(s){let e,t;return{c(){e=new Ui(!1),t=ye(),e.a=t},m(r,n){e.m(s[0],r,n),S(r,t,n)},p(r,[n]){n&1&&e.p(r[0])},i:B,o:B,d(r){r&&O(t),r&&e.d()}}}function iu(s,e,t){let{text:r}=e;return s.$$set=n=>{"text"in n&&t(0,r=n.text)},[r]}let lu=class extends W{constructor(e){super(),Z(this,e,iu,su,K,{text:0})}};function ou(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("blockquote"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function au(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class cu extends W{constructor(e){super(),Z(this,e,au,ou,K,{})}}function uu(s){let e,t,r;return{c(){e=b("pre"),t=b("code"),r=ce(s[1]),p(e,"class",s[0])},m(n,i){S(n,e,i),_(e,t),_(t,r)},p(n,[i]){i&2&&Te(r,n[1]),i&1&&p(e,"class",n[0])},i:B,o:B,d(n){n&&O(e)}}}function fu(s,e,t){let{lang:r}=e,{text:n}=e;return s.$$set=i=>{"lang"in i&&t(0,r=i.lang),"text"in i&&t(1,n=i.text)},[r,n]}let du=class extends W{constructor(e){super(),Z(this,e,fu,uu,K,{lang:0,text:1})}};function hu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("br"),n&&n.c()},m(i,l){S(i,e,l),n&&n.m(i,l),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function pu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class mu extends W{constructor(e){super(),Z(this,e,pu,hu,K,{})}}const gu={heading:lc,paragraph:cc,text:dc,image:mc,link:bc,em:yc,strong:Cc,codespan:Ec,del:Sc,table:Ic,tablehead:Fc,tablebody:Bc,tablerow:qc,tablecell:Jc,list:Wc,orderedlistitem:null,unorderedlistitem:null,listitem:tu,hr:ru,html:lu,blockquote:cu,code:du,br:mu},_u={baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,xhtml:!1};function bu(s){let e,t;return e=new gt({props:{tokens:s[0],renderers:s[1]}}),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},p(r,[n]){const i={};n&1&&(i.tokens=r[0]),n&2&&(i.renderers=r[1]),e.$set(i)},i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function vu(s,e,t){let r,n,i,l,{source:a=[]}=e,{renderers:o={}}=e,{options:c={}}=e,{isInline:u=!1}=e;const f=cn();let d,h,m;return Li(Ci,{slug:g=>n?n.slug(g):"",getOptions:()=>i}),an(()=>{t(7,m=!0)}),s.$$set=g=>{"source"in g&&t(2,a=g.source),"renderers"in g&&t(3,o=g.renderers),"options"in g&&t(4,c=g.options),"isInline"in g&&t(5,u=g.isInline)},s.$$.update=()=>{s.$$.dirty&4&&t(8,r=Array.isArray(a)),s.$$.dirty&4&&(n=a?new pr:void 0),s.$$.dirty&16&&t(9,i={..._u,...c}),s.$$.dirty&869&&(r?t(0,d=a):(t(6,h=new Ke(i)),t(0,d=u?h.inlineTokens(a):h.lex(a)),f("parsed",{tokens:d}))),s.$$.dirty&8&&t(1,l={...gu,...o}),s.$$.dirty&385&&m&&!r&&f("parsed",{tokens:d})},[d,l,a,o,c,u,h,m,r,i]}class wu extends W{constructor(e){super(),Z(this,e,vu,bu,K,{source:2,renderers:3,options:4,isInline:5})}}function yu(s){let e,t,r,n,i,l,a,o,c;return{c(){e=b("div"),t=b("div"),r=b("button"),r.textContent="Copy code",n=C(),i=b("pre"),l=b("code"),a=ce(s[0]),p(r,"class","svelte-hssbda"),p(t,"class","copycode svelte-hssbda"),p(i,"class","svelte-hssbda"),lt(e,"position","relative")},m(u,f){S(u,e,f),_(e,t),_(t,r),_(e,n),_(e,i),_(i,l),_(l,a),o||(c=N(r,"click",s[1]),o=!0)},p(u,[f]){f&1&&Te(a,u[0])},i:B,o:B,d(u){u&&O(e),o=!1,c()}}}function ku(s,e,t){let{text:r}=e;const n=async()=>{try{await navigator.clipboard.writeText(r)}catch(i){console.error("Error copying text: ",i)}};return s.$$set=i=>{"text"in i&&t(0,r=i.text)},[r,n]}class Ou extends W{constructor(e){super(),Z(this,e,ku,yu,K,{text:0})}}function Su(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("em"),n&&n.c(),p(e,"class","svelte-djznuz")},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Au(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class $u extends W{constructor(e){super(),Z(this,e,Au,Su,K,{})}}function Eu(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ul"),n&&n.c(),p(e,"class","svelte-1dicnom")},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Tu(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ol"),n&&n.c(),p(e,"start",s[1]),p(e,"class","svelte-1dicnom")},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"start",i[1])},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Pu(s){let e,t,r,n;const i=[Tu,Eu],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ye()},m(o,c){l[e].m(o,c),S(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(se(),$(l[u],1,1,()=>{l[u]=null}),ie(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),v(t,1),t.m(r.parentNode,r))},i(o){n||(v(t),n=!0)},o(o){$(t),n=!1},d(o){l[e].d(o),o&&O(r)}}}function Cu(s,e,t){let{$$slots:r={},$$scope:n}=e,{ordered:i}=e,{start:l}=e;return s.$$set=a=>{"ordered"in a&&t(0,i=a.ordered),"start"in a&&t(1,l=a.start),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class Ru extends W{constructor(e){super(),Z(this,e,Cu,Pu,K,{ordered:0,start:1})}}function xu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("li"),n&&n.c(),p(e,"class","svelte-fm7yqp")},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Iu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class ju extends W{constructor(e){super(),Z(this,e,Iu,xu,K,{})}}function Mu(s){let e,t=s[0].replace(/`/g,"")+"",r;return{c(){e=b("code"),r=ce(t),p(e,"class","svelte-we39e")},m(n,i){S(n,e,i),_(e,r)},p(n,[i]){i&1&&t!==(t=n[0].replace(/`/g,"")+"")&&Te(r,t)},i:B,o:B,d(n){n&&O(e)}}}function Fu(s,e,t){let{raw:r}=e;return s.$$set=n=>{"raw"in n&&t(0,r=n.raw)},[r]}class Uu extends W{constructor(e){super(),Z(this,e,Fu,Mu,K,{raw:0})}}function Vu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("p"),n&&n.c(),p(e,"class","svelte-jw73bw")},m(i,l){S(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(v(n,i),t=!0)},o(i){$(n,i),t=!1},d(i){i&&O(e),n&&n.d(i)}}}function Bu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Lu extends W{constructor(e){super(),Z(this,e,Bu,Vu,K,{})}}function Du(s){let e;return{c(){e=ce(s[0])},m(t,r){S(t,e,r)},p(t,[r]){r&1&&Te(e,t[0])},i:B,o:B,d(t){t&&O(e)}}}function qu(s,e,t){let{text:r}=e;return s.$$set=n=>{"text"in n&&t(0,r=n.text)},[r]}class Nu extends W{constructor(e){super(),Z(this,e,qu,Du,K,{text:0})}}const zu="/assets/delete-f3f148b5.svg",Hu="/assets/CopyIcon-6270aedf.svg",Vs="/assets/UserIcon-57b535eb.svg",Bs="/assets/RobotIcon-76293781.svg",Gu="/assets/send-8e88dbd9.svg",Ju="/assets/wait-8f30b8f8.svg",Qu="/assets/upload-icon-8c25e619.svg";function Ls(s,e,t){const r=s.slice();return r[43]=e[t],r[45]=t,r}function Yu(s){let e;return{c(){e=ce("SmoothGPT")},m(t,r){S(t,e,r)},p:B,d(t){t&&O(e)}}}function Ku(s){let e=(s[2][s[1]].title||"SmoothGPT")+"",t;return{c(){t=ce(e)},m(r,n){S(r,t,n)},p(r,n){n[0]&6&&e!==(e=(r[2][r[1]].title||"SmoothGPT")+"")&&Te(t,e)},d(r){r&&O(t)}}}function Ds(s){let e,t;return e=new aa({}),e.$on("settings-changed",Uo),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},p:B,i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function qs(s){let e,t;return e=new fa({}),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function Zu(s){let e;return{c(){e=b("div"),e.innerHTML="

    No conversation selected. Start a new conversation.

    ",p(e,"class","flex justify-center items-center h-full")},m(t,r){S(t,e,r)},p:B,i:B,o:B,d(t){t&&O(e)}}}function Wu(s){let e,t,r,n=s[2][s[1]].history,i=[];for(let a=0;a$(i[a],1,1,()=>{i[a]=null});return{c(){e=b("div"),t=b("div");for(let a=0;a{u[y]=null}),ie(),n=u[r],n?n.p(m,g):(n=u[r]=c[r](m),n.c()),v(n,1),n.m(e,null)),m[43].role==="assistant"?d?d.p(m,g):(d=Ns(m),d.c(),d.m(l,a)):d&&(d.d(1),d=null),m[43].role==="user"?h?h.p(m,g):(h=Hs(m),h.c(),h.m(l,null)):h&&(h.d(1),h=null)},i(m){o||(v(n),o=!0)},o(m){$(n),o=!1},d(m){m&&O(e),u[r].d(),m&&O(i),m&&O(l),d&&d.d(),h&&h.d()}}}function nf(s){let e,t,r,n,i,l,a,o,c,u;function f(){return s[27](s[45])}return{c(){e=b("textarea"),t=C(),r=b("div"),n=b("button"),i=ce("Submit"),a=C(),o=b("button"),o.textContent="Cancel",p(e,"class","message-edit-textarea mt-2 bg-gray-700 p-3 mx-10 resize-none focus:outline-none rounded-lg"),lt(e,"height","96px"),lt(e,"overflow-y","auto"),p(n,"class",l="submit-edit rounded-lg p-2 mr-2 "+(s[15]?"bg-gray-500 cursor-not-allowed hover:bg-gray-500":"hover:bg-green-500 bg-green-700")),n.disabled=s[15],p(o,"class","cancel-edit bg-gray-700 hover:bg-gray-500 rounded-lg p-2 mr-2"),p(r,"class","flex place-content-center mt-4")},m(d,h){S(d,e,h),s[25](e),He(e,s[9]),S(d,t,h),S(d,r,h),_(r,n),_(n,i),_(r,a),_(r,o),c||(u=[N(e,"input",s[26]),N(e,"input",Ri),N(n,"click",f),N(o,"click",s[28])],c=!0)},p(d,h){s=d,h[0]&512&&He(e,s[9]),h[0]&32768&&l!==(l="submit-edit rounded-lg p-2 mr-2 "+(s[15]?"bg-gray-500 cursor-not-allowed hover:bg-gray-500":"hover:bg-green-500 bg-green-700"))&&p(n,"class",l),h[0]&32768&&(n.disabled=s[15])},i:B,o:B,d(d){d&&O(e),s[25](null),d&&O(t),d&&O(r),c=!1,De(u)}}}function rf(s){let e,t;return e=new wu({props:{renderers:{code:Ou,em:$u,list:Ru,listitem:ju,codespan:Uu,paragraph:Lu,html:Nu},source:os(s[43].content.toString())}}),{c(){Y(e.$$.fragment)},m(r,n){J(e,r,n),t=!0},p(r,n){const i={};n[0]&6&&(i.source=os(r[43].content.toString())),e.$set(i)},i(r){t||(v(e.$$.fragment,r),t=!0)},o(r){$(e.$$.fragment,r),t=!1},d(r){Q(e,r)}}}function sf(s){let e,t,r;return t=new Go({props:{audioUrl:s[43].audioUrl}}),{c(){e=b("div"),Y(t.$$.fragment),p(e,"class","pb-3")},m(n,i){S(n,e,i),J(t,e,null),r=!0},p(n,i){const l={};i[0]&6&&(l.audioUrl=n[43].audioUrl),t.$set(l)},i(n){r||(v(t.$$.fragment,n),r=!0)},o(n){$(t.$$.fragment,n),r=!1},d(n){n&&O(e),Q(t)}}}function Ns(s){let e=!Kn(s[43]),t,r,n,i,l,a,o=e&&zs(s);function c(){return s[30](s[45])}return{c(){o&&o.c(),t=C(),r=b("button"),n=b("img"),p(n,"class","delete-icon"),p(n,"alt","Delete"),Pe(n.src,i=zu)||p(n,"src",i),p(r,"class","deleteButton w-5")},m(u,f){o&&o.m(u,f),S(u,t,f),S(u,r,f),_(r,n),l||(a=N(r,"click",c),l=!0)},p(u,f){s=u,f[0]&6&&(e=!Kn(s[43])),e?o?o.p(s,f):(o=zs(s),o.c(),o.m(t.parentNode,t)):o&&(o.d(1),o=null)},d(u){o&&o.d(u),u&&O(t),u&&O(r),l=!1,a()}}}function zs(s){let e,t,r,n,i;function l(){return s[29](s[43])}return{c(){e=b("button"),t=b("img"),p(t,"class","copy-icon"),p(t,"alt","Copy"),Pe(t.src,r=Hu)||p(t,"src",r),p(e,"class","copyButton w-5")},m(a,o){S(a,e,o),_(e,t),n||(i=N(e,"click",l),n=!0)},p(a,o){s=a},d(a){a&&O(e),n=!1,i()}}}function Hs(s){let e,t,r,n,i;function l(){return s[31](s[45])}return{c(){e=b("button"),t=b("img"),p(t,"class","edit-icon"),p(t,"alt","edit"),Pe(t.src,r=Oi)||p(t,"src",r),p(e,"class","editButton w-5")},m(a,o){S(a,e,o),_(e,t),n||(i=N(e,"click",l),n=!0)},p(a,o){s=a},d(a){a&&O(e),n=!1,i()}}}function Gs(s){let e,t,r,n,i,l,a,o,c,u,f,d;function h(E,w){return E[43].role==="assistant"?ef:Xu}let m=h(s),g=m(s);const y=[nf,tf],k=[];function A(E,w){return E[8]===E[45]?0:1}return c=A(s),u=k[c]=y[c](s),{c(){e=b("div"),t=b("div"),r=b("div"),n=b("img"),l=C(),a=b("div"),g.c(),o=C(),u.c(),f=C(),Pe(n.src,i=s[43].role==="user"?Vs:Bs)||p(n,"src",i),p(n,"alt","Profile"),p(n,"class","w-6 h-6 ml-10"),p(a,"class","relative ml-3 font-bold"),p(t,"class","profile-picture flex"),p(e,"class","message relative inline-block bg-primary px-2 pb-5 flex flex-col")},m(E,w){S(E,e,w),_(e,t),_(t,r),_(r,n),_(t,l),_(t,a),g.m(a,null),_(e,o),k[c].m(e,null),_(e,f),d=!0},p(E,w){(!d||w[0]&6&&!Pe(n.src,i=E[43].role==="user"?Vs:Bs))&&p(n,"src",i),m!==(m=h(E))&&(g.d(1),g=m(E),g&&(g.c(),g.m(a,null)));let j=c;c=A(E),c===j?k[c].p(E,w):(se(),$(k[j],1,1,()=>{k[j]=null}),ie(),u=k[c],u?u.p(E,w):(u=k[c]=y[c](E),u.c()),v(u,1),u.m(e,f))},i(E){d||(v(u),d=!0)},o(E){$(u),d=!1},d(E){E&&O(e),g.d(),k[c].d()}}}function Js(s){let e,t,r,n,i;function l(c,u){return c[10]===0?of:lf}let a=l(s),o=a(s);return{c(){e=b("input"),t=C(),r=b("label"),o.c(),p(e,"type","file"),p(e,"id","imageUpload"),e.multiple=!0,p(e,"accept","image/*"),p(e,"class","file-input"),p(r,"for","imageUpload"),p(r,"class","file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors")},m(c,u){S(c,e,u),s[33](e),S(c,t,u),S(c,r,u),o.m(r,null),n||(i=N(e,"change",jo),n=!0)},p(c,u){a===(a=l(c))&&o?o.p(c,u):(o.d(1),o=a(c),o&&(o.c(),o.m(r,null)))},d(c){c&&O(e),s[33](null),c&&O(t),c&&O(r),o.d(),n=!1,i()}}}function lf(s){let e,t;return{c(){e=b("span"),t=ce(s[10]),p(e,"class","fileCount")},m(r,n){S(r,e,n),_(e,t)},p(r,n){n[0]&1024&&Te(t,r[10])},d(r){r&&O(e)}}}function of(s){let e,t;return{c(){e=b("img"),Pe(e.src,t=Qu)||p(e,"src",t),p(e,"alt","Upload"),p(e,"class","upload-icon icon-white")},m(r,n){S(r,e,n)},p:B,d(r){r&&O(e)}}}function af(s){let e,t;return{c(){e=b("img"),p(e,"class","icon-white min-w-[24px] w-[24px]"),p(e,"alt","Send"),Pe(e.src,t=Gu)||p(e,"src",t)},m(r,n){S(r,e,n)},p:B,d(r){r&&O(e)}}}function cf(s){let e,t;return{c(){e=b("img"),p(e,"class","icon-white min-w-[24px] w-[24px]"),p(e,"alt","Wait"),Pe(e.src,t=Ju)||p(e,"src",t)},m(r,n){S(r,e,n)},p:B,d(r){r&&O(e)}}}function uf(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,m,g,y,k,A,E,w,j,I,H,ee,X,re,te,ae,$e,be,Ae,xe,T;function G(x,oe){return x[2].length>0&&x[2][x[1]]?Ku:Yu}let z=G(s),M=z(s),D=s[12]&&Ds(),q=s[13]&&qs();l=new ia({}),l.$on("new-chat",s[23]);function F(x){s[24](x)}let ve={};s[7]!==void 0&&(ve.conversation_title=s[7]),c=new Zo({props:ve}),st.push(()=>Gi(c,"conversation_title",F)),c.$on("new-chat",pi);const Ie=[Wu,Zu],fe=[];function je(x,oe){return x[2].length>0&&x[2][x[1]]?0:1}E=je(s),w=fe[E]=Ie[E](s);let we=s[11]&&Js(s);function Ge(x,oe){return x[15]?cf:af}let P=Ge(s),le=P(s);return{c(){e=b("title"),M.c(),t=C(),D&&D.c(),r=C(),q&&q.c(),n=C(),i=b("main"),Y(l.$$.fragment),a=C(),o=b("div"),Y(c.$$.fragment),f=C(),d=b("div"),h=b("div"),m=ce("Current Model: "),g=b("span"),y=ce(s[14]),k=C(),A=b("div"),w.c(),j=C(),I=b("div"),H=b("div"),we&&we.c(),ee=C(),X=b("textarea"),re=C(),te=b("button"),le.c(),$e=C(),be=b("div"),be.innerHTML='
    ',p(g,"class","font-normal"),p(h,"class","font-bold text-l"),p(d,"class","py-5 bg-primary px-5 flex flex-row justify-between flex-wrap-reverse"),p(A,"class","flex bg-primary overflow-y-auto overflow-x-hidden justify-center grow"),p(X,"class","w-full min-h-[96px] h-24 rounded-lg p-2 mx-1 mr-0 border-t-2 border-b-2 border-l-2 rounded-r-none bg-primary border-gray-500 resize-none focus:outline-none"),p(X,"placeholder","Type your message..."),lt(X,"height","96px"),lt(X,"overflow-y","auto"),p(te,"class","bg-chat rounded-lg py-2 px-4 mx-1 ml-0 border-t-2 border-b-2 border-r-2 border-gray-500 rounded-l-none cursor-pointer "),te.disabled=ae=!s[15]&&!s[3].trim().length,p(H,"class","inputbox flex flex-1 bg-primary mt-auto mx-auto max-w-3xl mb-3"),p(I,"class","inputbox-container w-full flex justify-center items-center bg-primary"),p(be,"class","flex justify-center bg-primary px-4"),p(o,"class","h-screen flex justify-stretch flex-col md:ml-[260px] bg-secondary text-white/80 height-manager"),p(i,"class","bg-primary overflow-hidden")},m(x,oe){S(x,e,oe),M.m(e,null),S(x,t,oe),D&&D.m(x,oe),S(x,r,oe),q&&q.m(x,oe),S(x,n,oe),S(x,i,oe),J(l,i,null),_(i,a),_(i,o),J(c,o,null),_(o,f),_(o,d),_(d,h),_(h,m),_(h,g),_(g,y),_(o,k),_(o,A),fe[E].m(A,null),s[32](A),_(o,j),_(o,I),_(I,H),we&&we.m(H,null),_(H,ee),_(H,X),s[34](X),He(X,s[3]),_(H,re),_(H,te),le.m(te,null),_(o,$e),_(o,be),Ae=!0,xe||(T=[N(X,"input",s[35]),N(X,"input",Ri),N(X,"keydown",s[36]),N(te,"click",s[37])],xe=!0)},p(x,oe){z===(z=G(x))&&M?M.p(x,oe):(M.d(1),M=z(x),M&&(M.c(),M.m(e,null))),x[12]?D?(D.p(x,oe),oe[0]&4096&&v(D,1)):(D=Ds(),D.c(),v(D,1),D.m(r.parentNode,r)):D&&(se(),$(D,1,1,()=>{D=null}),ie()),x[13]?q?oe[0]&8192&&v(q,1):(q=qs(),q.c(),v(q,1),q.m(n.parentNode,n)):q&&(se(),$(q,1,1,()=>{q=null}),ie());const Me={};!u&&oe[0]&128&&(u=!0,Me.conversation_title=x[7],zi(()=>u=!1)),c.$set(Me),(!Ae||oe[0]&16384)&&Te(y,x[14]);let We=E;E=je(x),E===We?fe[E].p(x,oe):(se(),$(fe[We],1,1,()=>{fe[We]=null}),ie(),w=fe[E],w?w.p(x,oe):(w=fe[E]=Ie[E](x),w.c()),v(w,1),w.m(A,null)),x[11]?we?we.p(x,oe):(we=Js(x),we.c(),we.m(H,ee)):we&&(we.d(1),we=null),oe[0]&8&&He(X,x[3]),P===(P=Ge(x))&&le?le.p(x,oe):(le.d(1),le=P(x),le&&(le.c(),le.m(te,null))),(!Ae||oe[0]&32776&&ae!==(ae=!x[15]&&!x[3].trim().length))&&(te.disabled=ae)},i(x){Ae||(v(D),v(q),v(l.$$.fragment,x),v(c.$$.fragment,x),v(w),Ae=!0)},o(x){$(D),$(q),$(l.$$.fragment,x),$(c.$$.fragment,x),$(w),Ae=!1},d(x){x&&O(e),M.d(),x&&O(t),D&&D.d(x),x&&O(r),q&&q.d(x),x&&O(n),x&&O(i),Q(l),Q(c),fe[E].d(),s[32](null),we&&we.d(),s[34](null),le.d(),xe=!1,De(T)}}}const ff=300;function Ri(s){s.target.style.height="inherit";const e=window.getComputedStyle(s.target),t=parseInt(e.getPropertyValue("border-top-width"),10)+s.target.scrollHeight+parseInt(e.getPropertyValue("border-bottom-width"),10);s.target.style.height=`${Math.min(t,ff)}px`}function df(s,e,t){let r,n,i,l,a,o,c,u,f,d;_e(s,Ee,P=>t(1,n=P)),_e(s,ue,P=>t(2,i=P)),_e(s,Ut,P=>t(20,l=P)),_e(s,At,P=>t(21,a=P)),_e(s,Yn,P=>t(22,o=P)),_e(s,en,P=>t(12,c=P)),_e(s,tn,P=>t(13,u=P)),_e(s,Ve,P=>t(14,f=P)),_e(s,Qe,P=>t(15,d=P));let h,m="",g,y,k,A="",E=null,w="",j=null;function I(){if(!k)return;const P={childList:!0,subtree:!0,characterData:!0};j=new MutationObserver((le,x)=>{H()}),j.observe(k,P)}an(async()=>{await qo(),I()}),Bi(()=>{j&&(j.disconnect(),j=null),No()});function H(){k&&k.scrollHeight-k.scrollTop-150<=k.clientHeight&&t(6,k.scrollTop=k.scrollHeight,k)}function ee(){ls(m,n),t(3,m=""),t(4,g.style.height="96px",g)}function X(){k&&t(6,k.scrollTop=k.scrollHeight,k)}let re=0;Vi(()=>{var le;const P=((le=i[n])==null?void 0:le.history.length)||0;P>re&&X(),re=P});let te=0;function ae(P){t(8,E=P),t(9,w=i[n].history[P].content)}function $e(){t(8,E=null),t(9,w=""),t(5,y.style.height="96px",y)}function be(P){const le=w,x=i[n].history.length-P;for(let Me=0;Mepi();function xe(P){A=P,t(7,A),t(1,n),t(2,i)}function T(P){st[P?"unshift":"push"](()=>{y=P,t(5,y)})}function G(){w=this.value,t(9,w)}const z=P=>be(P),M=()=>$e(),D=P=>bo(P.content),q=P=>is(P),F=P=>ae(P);function ve(P){st[P?"unshift":"push"](()=>{k=P,t(6,k)})}function Ie(P){st[P?"unshift":"push"](()=>{h=P,t(0,h),t(22,o)})}function fe(P){st[P?"unshift":"push"](()=>{g=P,t(4,g)})}function je(){m=this.value,t(3,m)}const we=P=>{const le=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);!d&&P.key==="Enter"&&!P.shiftKey&&!P.ctrlKey&&!P.metaKey&&!le?(P.preventDefault(),ee()):!d&&P.key},Ge=()=>{d?Mo():ee()};return s.$$.update=()=>{if(s.$$.dirty[0]&4194305&&o&&h&&(t(0,h.value="",h),Yn.set(!1)),s.$$.dirty[0]&6){const P=n,le=i,x=i.length;P!==void 0&&le[P]&&t(7,A=le[P].title||"New Conversation"),(P==null||P<0||P>=x)&&(console.log("changing conversation from ID",n),Ee.set(x>0?x-1:null),console.log("to ID",n))}s.$$.dirty[0]&2097152&&t(11,r=a.includes("Vision")),s.$$.dirty[0]&6&&t(7,A=i[n]?i[n].title:"ChatGPT"),s.$$.dirty[0]&1048576&&t(10,te=l.length)},[h,n,i,m,g,y,k,A,E,w,te,r,c,u,f,d,ee,ae,$e,be,l,a,o,Ae,xe,T,G,z,M,D,q,F,ve,Ie,fe,je,we,Ge]}class hf extends W{constructor(e){super(),Z(this,e,df,uf,K,{},null,[-1,-1])}}const pf="/assets/chat-431b71cc.svg";new hf({target:document.getElementById("app")});window.addEventListener("load",()=>{const s=document.querySelector('link[rel="icon"]');s&&s.setAttribute("href",pf)}); diff --git a/dist/assets/index-4a068af4.js b/dist/assets/index-4a068af4.js new file mode 100644 index 0000000..2b90da7 --- /dev/null +++ b/dist/assets/index-4a068af4.js @@ -0,0 +1,68 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function t(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(n){if(n.ep)return;n.ep=!0;const i=t(n);fetch(n.href,i)}})();function U(){}function dt(s,e){for(const t in e)s[t]=e[t];return s}function fi(s){return s()}function Dr(){return Object.create(null)}function Ne(s){s.forEach(fi)}function di(s){return typeof s=="function"}function Z(s,e){return s!=s?e==e:s!==e||s&&typeof s=="object"||typeof s=="function"}let tn;function Ae(s,e){return tn||(tn=document.createElement("a")),tn.href=e,s===tn.href}function Ki(s){return Object.keys(s).length===0}function hi(s,...e){if(s==null)return U;const t=s.subscribe(...e);return t.unsubscribe?()=>t.unsubscribe():t}function I(s){let e;return hi(s,t=>e=t)(),e}function fe(s,e,t){s.$$.on_destroy.push(hi(e,t))}function de(s,e,t,r){if(s){const n=pi(s,e,t,r);return s[0](n)}}function pi(s,e,t,r){return s[1]&&r?dt(t.ctx.slice(),s[1](r(e))):t.ctx}function he(s,e,t,r){if(s[2]&&r){const n=s[2](r(t));if(e.dirty===void 0)return n;if(typeof n=="object"){const i=[],l=Math.max(e.dirty.length,n.length);for(let a=0;a32){const e=[],t=s.ctx.length/32;for(let r=0;rs.removeEventListener(e,t,r)}function cn(s){return function(e){return e.stopPropagation(),s.call(this,e)}}function p(s,e,t){t==null?s.removeAttribute(e):s.getAttribute(e)!==t&&s.setAttribute(e,t)}function el(s){return Array.from(s.childNodes)}function Pe(s,e){e=""+e,s.wholeText!==e&&(s.data=e)}function Xe(s,e){s.value=e??""}function rt(s,e,t,r){t===null?s.style.removeProperty(e):s.style.setProperty(e,t,r?"important":"")}function Ze(s,e){for(let t=0;t{const n=s.$$.callbacks[e];if(n){const i=tl(e,t,{cancelable:r});return n.slice().forEach(l=>{l.call(s,i)}),!i.defaultPrevented}return!0}}function il(s,e){return Mt().$$.context.set(s,e),e}function ll(s){return Mt().$$.context.get(s)}const jt=[],ut=[],rn=[],er=[],ol=Promise.resolve();let tr=!1;function al(){tr||(tr=!0,ol.then(mi))}function ft(s){rn.push(s)}function cl(s){er.push(s)}const In=new Set;let Ct=0;function mi(){if(Ct!==0)return;const s=Ht;do{try{for(;Ct{sn.delete(s),r&&(t&&s.d(1),r())}),s.o(e)}else r&&r()}function Ut(s,e){const t={},r={},n={$$scope:1};let i=s.length;for(;i--;){const l=s[i],a=e[i];if(a){for(const o in l)o in a||(r[o]=1);for(const o in a)n[o]||(t[o]=a[o],n[o]=1);s[i]=a}else for(const o in l)n[o]=1}for(const l in r)l in t||(t[l]=void 0);return t}function Bt(s){return typeof s=="object"&&s!==null?s:{}}function fl(s,e,t){const r=s.$$.props[e];r!==void 0&&(s.$$.bound[r]=t,t(s.$$.ctx[r]))}function K(s){s&&s.c()}function Y(s,e,t,r){const{fragment:n,after_update:i}=s.$$;n&&n.m(e,t),r||ft(()=>{const l=s.$$.on_mount.map(fi).filter(di);s.$$.on_destroy?s.$$.on_destroy.push(...l):Ne(l),s.$$.on_mount=[]}),i.forEach(ft)}function W(s,e){const t=s.$$;t.fragment!==null&&(Ne(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function dl(s,e){s.$$.dirty[0]===-1&&(jt.push(s),al(),s.$$.dirty.fill(0)),s.$$.dirty[e/31|0]|=1<{const _=h.length?h[0]:d;return c.ctx&&n(c.ctx[f],c.ctx[f]=_)&&(!c.skip_bound&&c.bound[f]&&c.bound[f](_),u&&dl(s,f)),d}):[],c.update(),u=!0,Ne(c.before_update),c.fragment=r?r(c.ctx):!1,e.target){if(e.hydrate){const f=el(e.target);c.fragment&&c.fragment.l(f),f.forEach(y)}else c.fragment&&c.fragment.c();e.intro&&S(s.$$.fragment),Y(s,e.target,e.anchor,e.customElement),mi()}Nt(o)}class ee{$destroy(){W(this,1),this.$destroy=U}$on(e,t){if(!di(t))return U;const r=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return r.push(t),()=>{const n=r.indexOf(t);n!==-1&&r.splice(n,1)}}$set(e){this.$$set&&!Ki(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Rt=[];function ye(s,e=U){let t;const r=new Set;function n(a){if(Z(s,a)&&(s=a,t)){const o=!Rt.length;for(const c of r)c[1](),Rt.push(c,s);if(o){for(let c=0;c{r.delete(c),r.size===0&&(t(),t=null)}}return{set:n,update:i,subscribe:l}}var gt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},nr={},gi={},un={},hl={get exports(){return un},set exports(s){un=s}},fn={},pl={get exports(){return fn},set exports(s){fn=s}},_i=function(e,t){return function(){for(var n=new Array(arguments.length),i=0;i"u"}function gl(s){return s!==null&&!rr(s)&&s.constructor!==null&&!rr(s.constructor)&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function bi(s){return _t.call(s)==="[object ArrayBuffer]"}function _l(s){return _t.call(s)==="[object FormData]"}function bl(s){var e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&bi(s.buffer),e}function vl(s){return typeof s=="string"}function wl(s){return typeof s=="number"}function vi(s){return s!==null&&typeof s=="object"}function ln(s){if(_t.call(s)!=="[object Object]")return!1;var e=Object.getPrototypeOf(s);return e===null||e===Object.prototype}function yl(s){return _t.call(s)==="[object Date]"}function kl(s){return _t.call(s)==="[object File]"}function Ol(s){return _t.call(s)==="[object Blob]"}function wi(s){return _t.call(s)==="[object Function]"}function Sl(s){return vi(s)&&wi(s.pipe)}function Al(s){return _t.call(s)==="[object URLSearchParams]"}function El(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function Pl(){return typeof navigator<"u"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window<"u"&&typeof document<"u"}function br(s,e){if(!(s===null||typeof s>"u"))if(typeof s!="object"&&(s=[s]),_r(s))for(var t=0,r=s.length;t"u"||(xt.isArray(o)?c=c+"[]":o=[o],xt.forEach(o,function(f){xt.isDate(f)?f=f.toISOString():xt.isObject(f)&&(f=JSON.stringify(f)),i.push(Nr(c)+"="+Nr(f))}))}),n=i.join("&")}if(n){var l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+n}return e},Cl=Ge;function yn(){this.handlers=[]}yn.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1};yn.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)};yn.prototype.forEach=function(e){Cl.forEach(this.handlers,function(r){r!==null&&e(r)})};var Rl=yn,xl=Ge,Il=function(e,t){xl.forEach(e,function(n,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[i])})},ki=function(e,t,r,n,i){return e.config=t,r&&(e.code=r),e.request=n,e.response=i,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},e},Oi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},jn,qr;function Si(){if(qr)return jn;qr=1;var s=ki;return jn=function(t,r,n,i,l){var a=new Error(t);return s(a,r,n,i,l)},jn}var Fn,zr;function jl(){if(zr)return Fn;zr=1;var s=Si();return Fn=function(t,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?t(n):r(s("Request failed with status code "+n.status,n.config,null,n.request,n))},Fn}var Mn,Hr;function Fl(){if(Hr)return Mn;Hr=1;var s=Ge;return Mn=s.isStandardBrowserEnv()?function(){return{write:function(r,n,i,l,a,o){var c=[];c.push(r+"="+encodeURIComponent(n)),s.isNumber(i)&&c.push("expires="+new Date(i).toGMTString()),s.isString(l)&&c.push("path="+l),s.isString(a)&&c.push("domain="+a),o===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(r){var n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Mn}var Un,Jr;function Ml(){return Jr||(Jr=1,Un=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}),Un}var Bn,Gr;function Ul(){return Gr||(Gr=1,Bn=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}),Bn}var Vn,Qr;function Bl(){if(Qr)return Vn;Qr=1;var s=Ml(),e=Ul();return Vn=function(r,n){return r&&!s(n)?e(r,n):n},Vn}var Dn,Yr;function Vl(){if(Yr)return Dn;Yr=1;var s=Ge,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return Dn=function(r){var n={},i,l,a;return r&&s.forEach(r.split(` +`),function(c){if(a=c.indexOf(":"),i=s.trim(c.substr(0,a)).toLowerCase(),l=s.trim(c.substr(a+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([l]):n[i]=n[i]?n[i]+", "+l:l}}),n},Dn}var Ln,Wr;function Dl(){if(Wr)return Ln;Wr=1;var s=Ge;return Ln=s.isStandardBrowserEnv()?function(){var t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(l){var a=l;return t&&(r.setAttribute("href",a),a=r.href),r.setAttribute("href",a),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(a){var o=s.isString(a)?i(a):a;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),Ln}var Nn,Kr;function kn(){if(Kr)return Nn;Kr=1;function s(e){this.message=e}return s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,Nn=s,Nn}var qn,Zr;function Xr(){if(Zr)return qn;Zr=1;var s=Ge,e=jl(),t=Fl(),r=yi,n=Bl(),i=Vl(),l=Dl(),a=Si(),o=Oi,c=kn();return qn=function(f){return new Promise(function(h,_){var m=f.data,w=f.headers,v=f.responseType,E;function P(){f.cancelToken&&f.cancelToken.unsubscribe(E),f.signal&&f.signal.removeEventListener("abort",E)}s.isFormData(m)&&delete w["Content-Type"];var O=new XMLHttpRequest;if(f.auth){var F=f.auth.username||"",C=f.auth.password?unescape(encodeURIComponent(f.auth.password)):"";w.Authorization="Basic "+btoa(F+":"+C)}var N=n(f.baseURL,f.url);O.open(f.method.toUpperCase(),r(N,f.params,f.paramsSerializer),!0),O.timeout=f.timeout;function ce(){if(O){var ne="getAllResponseHeaders"in O?i(O.getAllResponseHeaders()):null,oe=!v||v==="text"||v==="json"?O.responseText:O.response,se={data:oe,status:O.status,statusText:O.statusText,headers:ne,config:f,request:O};e(function(Te){h(Te),P()},function(Te){_(Te),P()},se),O=null}}if("onloadend"in O?O.onloadend=ce:O.onreadystatechange=function(){!O||O.readyState!==4||O.status===0&&!(O.responseURL&&O.responseURL.indexOf("file:")===0)||setTimeout(ce)},O.onabort=function(){O&&(_(a("Request aborted",f,"ECONNABORTED",O)),O=null)},O.onerror=function(){_(a("Network Error",f,null,O)),O=null},O.ontimeout=function(){var oe=f.timeout?"timeout of "+f.timeout+"ms exceeded":"timeout exceeded",se=f.transitional||o;f.timeoutErrorMessage&&(oe=f.timeoutErrorMessage),_(a(oe,f,se.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",O)),O=null},s.isStandardBrowserEnv()){var G=(f.withCredentials||l(N))&&f.xsrfCookieName?t.read(f.xsrfCookieName):void 0;G&&(w[f.xsrfHeaderName]=G)}"setRequestHeader"in O&&s.forEach(w,function(oe,se){typeof m>"u"&&se.toLowerCase()==="content-type"?delete w[se]:O.setRequestHeader(se,oe)}),s.isUndefined(f.withCredentials)||(O.withCredentials=!!f.withCredentials),v&&v!=="json"&&(O.responseType=f.responseType),typeof f.onDownloadProgress=="function"&&O.addEventListener("progress",f.onDownloadProgress),typeof f.onUploadProgress=="function"&&O.upload&&O.upload.addEventListener("progress",f.onUploadProgress),(f.cancelToken||f.signal)&&(E=function(ne){O&&(_(!ne||ne&&ne.type?new c("canceled"):ne),O.abort(),O=null)},f.cancelToken&&f.cancelToken.subscribe(E),f.signal&&(f.signal.aborted?E():f.signal.addEventListener("abort",E))),m||(m=null),O.send(m)})},qn}var Ie=Ge,es=Il,Ll=ki,Nl=Oi,ql={"Content-Type":"application/x-www-form-urlencoded"};function ts(s,e){!Ie.isUndefined(s)&&Ie.isUndefined(s["Content-Type"])&&(s["Content-Type"]=e)}function zl(){var s;return(typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(s=Xr()),s}function Hl(s,e,t){if(Ie.isString(s))try{return(e||JSON.parse)(s),Ie.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(t||JSON.stringify)(s)}var On={transitional:Nl,adapter:zl(),transformRequest:[function(e,t){return es(t,"Accept"),es(t,"Content-Type"),Ie.isFormData(e)||Ie.isArrayBuffer(e)||Ie.isBuffer(e)||Ie.isStream(e)||Ie.isFile(e)||Ie.isBlob(e)?e:Ie.isArrayBufferView(e)?e.buffer:Ie.isURLSearchParams(e)?(ts(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):Ie.isObject(e)||t&&t["Content-Type"]==="application/json"?(ts(t,"application/json"),Hl(e)):e}],transformResponse:[function(e){var t=this.transitional||On.transitional,r=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,i=!r&&this.responseType==="json";if(i||n&&Ie.isString(e)&&e.length)try{return JSON.parse(e)}catch(l){if(i)throw l.name==="SyntaxError"?Ll(l,this,"E_JSON_PARSE"):l}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Ie.forEach(["delete","get","head"],function(e){On.headers[e]={}});Ie.forEach(["post","put","patch"],function(e){On.headers[e]=Ie.merge(ql)});var vr=On,Jl=Ge,Gl=vr,Ql=function(e,t,r){var n=this||Gl;return Jl.forEach(r,function(l){e=l.call(n,e,t)}),e},zn,ns;function Ai(){return ns||(ns=1,zn=function(e){return!!(e&&e.__CANCEL__)}),zn}var rs=Ge,Hn=Ql,Yl=Ai(),Wl=vr,Kl=kn();function Jn(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Kl("canceled")}var Zl=function(e){Jn(e),e.headers=e.headers||{},e.data=Hn.call(e,e.data,e.headers,e.transformRequest),e.headers=rs.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),rs.forEach(["delete","get","head","post","put","patch","common"],function(n){delete e.headers[n]});var t=e.adapter||Wl.adapter;return t(e).then(function(n){return Jn(e),n.data=Hn.call(e,n.data,n.headers,e.transformResponse),n},function(n){return Yl(n)||(Jn(e),n&&n.response&&(n.response.data=Hn.call(e,n.response.data,n.response.headers,e.transformResponse))),Promise.reject(n)})},We=Ge,Ei=function(e,t){t=t||{};var r={};function n(u,f){return We.isPlainObject(u)&&We.isPlainObject(f)?We.merge(u,f):We.isPlainObject(f)?We.merge({},f):We.isArray(f)?f.slice():f}function i(u){if(We.isUndefined(t[u])){if(!We.isUndefined(e[u]))return n(void 0,e[u])}else return n(e[u],t[u])}function l(u){if(!We.isUndefined(t[u]))return n(void 0,t[u])}function a(u){if(We.isUndefined(t[u])){if(!We.isUndefined(e[u]))return n(void 0,e[u])}else return n(void 0,t[u])}function o(u){if(u in t)return n(e[u],t[u]);if(u in e)return n(void 0,e[u])}var c={url:l,method:l,data:l,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o};return We.forEach(Object.keys(e).concat(Object.keys(t)),function(f){var d=c[f]||i,h=d(f);We.isUndefined(h)&&d!==o||(r[f]=h)}),r},Gn,ss;function Pi(){return ss||(ss=1,Gn={version:"0.26.1"}),Gn}var Xl=Pi().version,wr={};["object","boolean","number","function","string","symbol"].forEach(function(s,e){wr[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});var is={};wr.transitional=function(e,t,r){function n(i,l){return"[Axios v"+Xl+"] Transitional option '"+i+"'"+l+(r?". "+r:"")}return function(i,l,a){if(e===!1)throw new Error(n(l," has been removed"+(t?" in "+t:"")));return t&&!is[l]&&(is[l]=!0,console.warn(n(l," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,l,a):!0}};function eo(s,e,t){if(typeof s!="object")throw new TypeError("options must be an object");for(var r=Object.keys(s),n=r.length;n-- >0;){var i=r[n],l=e[i];if(l){var a=s[i],o=a===void 0||l(a,i,s);if(o!==!0)throw new TypeError("option "+i+" must be "+o);continue}if(t!==!0)throw Error("Unknown option "+i)}}var to={assertOptions:eo,validators:wr},Ti=Ge,no=yi,ls=Rl,os=Zl,Sn=Ei,$i=to,It=$i.validators;function Yt(s){this.defaults=s,this.interceptors={request:new ls,response:new ls}}Yt.prototype.request=function(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Sn(this.defaults,t),t.method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var r=t.transitional;r!==void 0&&$i.assertOptions(r,{silentJSONParsing:It.transitional(It.boolean),forcedJSONParsing:It.transitional(It.boolean),clarifyTimeoutError:It.transitional(It.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(t)===!1||(i=i&&h.synchronous,n.unshift(h.fulfilled,h.rejected))});var l=[];this.interceptors.response.forEach(function(h){l.push(h.fulfilled,h.rejected)});var a;if(!i){var o=[os,void 0];for(Array.prototype.unshift.apply(o,n),o=o.concat(l),a=Promise.resolve(t);o.length;)a=a.then(o.shift(),o.shift());return a}for(var c=t;n.length;){var u=n.shift(),f=n.shift();try{c=u(c)}catch(d){f(d);break}}try{a=os(c)}catch(d){return Promise.reject(d)}for(;l.length;)a=a.then(l.shift(),l.shift());return a};Yt.prototype.getUri=function(e){return e=Sn(this.defaults,e),no(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")};Ti.forEach(["delete","get","head","options"],function(e){Yt.prototype[e]=function(t,r){return this.request(Sn(r||{},{method:e,url:t,data:(r||{}).data}))}});Ti.forEach(["post","put","patch"],function(e){Yt.prototype[e]=function(t,r,n){return this.request(Sn(n||{},{method:e,url:t,data:r}))}});var ro=Yt,Qn,as;function so(){if(as)return Qn;as=1;var s=kn();function e(t){if(typeof t!="function")throw new TypeError("executor must be a function.");var r;this.promise=new Promise(function(l){r=l});var n=this;this.promise.then(function(i){if(n._listeners){var l,a=n._listeners.length;for(l=0;lir(s,r,t)):Object.keys(e).forEach(r=>ir(s,e[r],`${t}${t!==""?".":""}${r}`)):s.has(t)?s.append(t,e):s.set(t,e))}ke.setSearchParams=function(s,...e){const t=new URLSearchParams(s.search);ir(t,e),s.search=t.toString()};ke.serializeDataIfNeeded=function(s,e,t){const r=typeof s!="string";return(r&&t&&t.isJsonMime?t.isJsonMime(e.headers["Content-Type"]):r)?JSON.stringify(s!==void 0?s:{}):s||""};ke.toPathString=function(s){return s.pathname+s.search+s.hash};ke.createRequestFunction=function(s,e,t,r){return(n=e,i=t)=>{const l=Object.assign(Object.assign({},s.options),{url:(r?.basePath||i)+s.url});return n.request(l)}};(function(s){var e=gt&>.__awaiter||function(l,a,o,c){function u(f){return f instanceof o?f:new o(function(d){d(f)})}return new(o||(o=Promise))(function(f,d){function h(w){try{m(c.next(w))}catch(v){d(v)}}function _(w){try{m(c.throw(w))}catch(v){d(v)}}function m(w){w.done?f(w.value):u(w.value).then(h,_)}m((c=c.apply(l,a||[])).next())})};Object.defineProperty(s,"__esModule",{value:!0}),s.OpenAIApi=s.OpenAIApiFactory=s.OpenAIApiFp=s.OpenAIApiAxiosParamCreator=s.CreateImageRequestResponseFormatEnum=s.CreateImageRequestSizeEnum=s.ChatCompletionResponseMessageRoleEnum=s.ChatCompletionRequestMessageRoleEnum=void 0;const t=un,r=ke,n=yr;s.ChatCompletionRequestMessageRoleEnum={System:"system",User:"user",Assistant:"assistant"},s.ChatCompletionResponseMessageRoleEnum={System:"system",User:"user",Assistant:"assistant"},s.CreateImageRequestSizeEnum={_256x256:"256x256",_512x512:"512x512",_1024x1024:"1024x1024"},s.CreateImageRequestResponseFormatEnum={Url:"url",B64Json:"b64_json"},s.OpenAIApiAxiosParamCreator=function(l){return{cancelFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("cancelFineTune","fineTuneId",a);const c="/fine-tunes/{fine_tune_id}/cancel".replace("{fine_tune_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),createAnswer:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createAnswer","createAnswerRequest",a);const c="/answers",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createChatCompletion:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createChatCompletion","createChatCompletionRequest",a);const c="/chat/completions",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createClassification:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createClassification","createClassificationRequest",a);const c="/classifications",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createCompletion:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createCompletion","createCompletionRequest",a);const c="/completions",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createEdit:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createEdit","createEditRequest",a);const c="/edits",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createEmbedding:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createEmbedding","createEmbeddingRequest",a);const c="/embeddings",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createFile:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createFile","file",a),r.assertParamExists("createFile","purpose",o);const u="/files",f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"POST"},d),c),_={},m={},w=new(l&&l.formDataCtor||FormData);a!==void 0&&w.append("file",a),o!==void 0&&w.append("purpose",o),_["Content-Type"]="multipart/form-data",r.setSearchParams(f,m);let v=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign(Object.assign({},_),w.getHeaders()),v),c.headers),h.data=w,{url:r.toPathString(f),options:h}}),createFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createFineTune","createFineTuneRequest",a);const c="/fine-tunes",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createImage:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImage","createImageRequest",a);const c="/images/generations",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createImageEdit:(a,o,c,u,f,d,h,_={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImageEdit","image",a),r.assertParamExists("createImageEdit","prompt",o);const m="/images/edits",w=new URL(m,r.DUMMY_BASE_URL);let v;l&&(v=l.baseOptions);const E=Object.assign(Object.assign({method:"POST"},v),_),P={},O={},F=new(l&&l.formDataCtor||FormData);a!==void 0&&F.append("image",a),c!==void 0&&F.append("mask",c),o!==void 0&&F.append("prompt",o),u!==void 0&&F.append("n",u),f!==void 0&&F.append("size",f),d!==void 0&&F.append("response_format",d),h!==void 0&&F.append("user",h),P["Content-Type"]="multipart/form-data",r.setSearchParams(w,O);let C=v&&v.headers?v.headers:{};return E.headers=Object.assign(Object.assign(Object.assign(Object.assign({},P),F.getHeaders()),C),_.headers),E.data=F,{url:r.toPathString(w),options:E}}),createImageVariation:(a,o,c,u,f,d={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createImageVariation","image",a);const h="/images/variations",_=new URL(h,r.DUMMY_BASE_URL);let m;l&&(m=l.baseOptions);const w=Object.assign(Object.assign({method:"POST"},m),d),v={},E={},P=new(l&&l.formDataCtor||FormData);a!==void 0&&P.append("image",a),o!==void 0&&P.append("n",o),c!==void 0&&P.append("size",c),u!==void 0&&P.append("response_format",u),f!==void 0&&P.append("user",f),v["Content-Type"]="multipart/form-data",r.setSearchParams(_,E);let O=m&&m.headers?m.headers:{};return w.headers=Object.assign(Object.assign(Object.assign(Object.assign({},v),P.getHeaders()),O),d.headers),w.data=P,{url:r.toPathString(_),options:w}}),createModeration:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createModeration","createModerationRequest",a);const c="/moderations",u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"POST"},f),o),h={},_={};h["Content-Type"]="application/json",r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),d.data=r.serializeDataIfNeeded(a,d,l),{url:r.toPathString(u),options:d}}),createSearch:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createSearch","engineId",a),r.assertParamExists("createSearch","createSearchRequest",o);const u="/engines/{engine_id}/search".replace("{engine_id}",encodeURIComponent(String(a))),f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"POST"},d),c),_={},m={};_["Content-Type"]="application/json",r.setSearchParams(f,m);let w=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign({},_),w),c.headers),h.data=r.serializeDataIfNeeded(o,h,l),{url:r.toPathString(f),options:h}}),createTranscription:(a,o,c,u,f,d,h={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createTranscription","file",a),r.assertParamExists("createTranscription","model",o);const _="/audio/transcriptions",m=new URL(_,r.DUMMY_BASE_URL);let w;l&&(w=l.baseOptions);const v=Object.assign(Object.assign({method:"POST"},w),h),E={},P={},O=new(l&&l.formDataCtor||FormData);a!==void 0&&O.append("file",a),o!==void 0&&O.append("model",o),c!==void 0&&O.append("prompt",c),u!==void 0&&O.append("response_format",u),f!==void 0&&O.append("temperature",f),d!==void 0&&O.append("language",d),E["Content-Type"]="multipart/form-data",r.setSearchParams(m,P);let F=w&&w.headers?w.headers:{};return v.headers=Object.assign(Object.assign(Object.assign(Object.assign({},E),O.getHeaders()),F),h.headers),v.data=O,{url:r.toPathString(m),options:v}}),createTranslation:(a,o,c,u,f,d={})=>e(this,void 0,void 0,function*(){r.assertParamExists("createTranslation","file",a),r.assertParamExists("createTranslation","model",o);const h="/audio/translations",_=new URL(h,r.DUMMY_BASE_URL);let m;l&&(m=l.baseOptions);const w=Object.assign(Object.assign({method:"POST"},m),d),v={},E={},P=new(l&&l.formDataCtor||FormData);a!==void 0&&P.append("file",a),o!==void 0&&P.append("model",o),c!==void 0&&P.append("prompt",c),u!==void 0&&P.append("response_format",u),f!==void 0&&P.append("temperature",f),v["Content-Type"]="multipart/form-data",r.setSearchParams(_,E);let O=m&&m.headers?m.headers:{};return w.headers=Object.assign(Object.assign(Object.assign(Object.assign({},v),P.getHeaders()),O),d.headers),w.data=P,{url:r.toPathString(_),options:w}}),deleteFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("deleteFile","fileId",a);const c="/files/{file_id}".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"DELETE"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),deleteModel:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("deleteModel","model",a);const c="/models/{model}".replace("{model}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"DELETE"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),downloadFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("downloadFile","fileId",a);const c="/files/{file_id}/content".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),listEngines:(a={})=>e(this,void 0,void 0,function*(){const o="/engines",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let _=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),_),a.headers),{url:r.toPathString(c),options:f}}),listFiles:(a={})=>e(this,void 0,void 0,function*(){const o="/files",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let _=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),_),a.headers),{url:r.toPathString(c),options:f}}),listFineTuneEvents:(a,o,c={})=>e(this,void 0,void 0,function*(){r.assertParamExists("listFineTuneEvents","fineTuneId",a);const u="/fine-tunes/{fine_tune_id}/events".replace("{fine_tune_id}",encodeURIComponent(String(a))),f=new URL(u,r.DUMMY_BASE_URL);let d;l&&(d=l.baseOptions);const h=Object.assign(Object.assign({method:"GET"},d),c),_={},m={};o!==void 0&&(m.stream=o),r.setSearchParams(f,m);let w=d&&d.headers?d.headers:{};return h.headers=Object.assign(Object.assign(Object.assign({},_),w),c.headers),{url:r.toPathString(f),options:h}}),listFineTunes:(a={})=>e(this,void 0,void 0,function*(){const o="/fine-tunes",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let _=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),_),a.headers),{url:r.toPathString(c),options:f}}),listModels:(a={})=>e(this,void 0,void 0,function*(){const o="/models",c=new URL(o,r.DUMMY_BASE_URL);let u;l&&(u=l.baseOptions);const f=Object.assign(Object.assign({method:"GET"},u),a),d={},h={};r.setSearchParams(c,h);let _=u&&u.headers?u.headers:{};return f.headers=Object.assign(Object.assign(Object.assign({},d),_),a.headers),{url:r.toPathString(c),options:f}}),retrieveEngine:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveEngine","engineId",a);const c="/engines/{engine_id}".replace("{engine_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),retrieveFile:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveFile","fileId",a);const c="/files/{file_id}".replace("{file_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),retrieveFineTune:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveFineTune","fineTuneId",a);const c="/fine-tunes/{fine_tune_id}".replace("{fine_tune_id}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}}),retrieveModel:(a,o={})=>e(this,void 0,void 0,function*(){r.assertParamExists("retrieveModel","model",a);const c="/models/{model}".replace("{model}",encodeURIComponent(String(a))),u=new URL(c,r.DUMMY_BASE_URL);let f;l&&(f=l.baseOptions);const d=Object.assign(Object.assign({method:"GET"},f),o),h={},_={};r.setSearchParams(u,_);let m=f&&f.headers?f.headers:{};return d.headers=Object.assign(Object.assign(Object.assign({},h),m),o.headers),{url:r.toPathString(u),options:d}})}},s.OpenAIApiFp=function(l){const a=s.OpenAIApiAxiosParamCreator(l);return{cancelFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.cancelFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createAnswer(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createAnswer(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createChatCompletion(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createChatCompletion(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createClassification(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createClassification(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createCompletion(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createCompletion(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createEdit(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createEdit(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createEmbedding(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createEmbedding(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createFile(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.createFile(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},createFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createImage(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createImage(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createImageEdit(o,c,u,f,d,h,_,m){return e(this,void 0,void 0,function*(){const w=yield a.createImageEdit(o,c,u,f,d,h,_,m);return r.createRequestFunction(w,t.default,n.BASE_PATH,l)})},createImageVariation(o,c,u,f,d,h){return e(this,void 0,void 0,function*(){const _=yield a.createImageVariation(o,c,u,f,d,h);return r.createRequestFunction(_,t.default,n.BASE_PATH,l)})},createModeration(o,c){return e(this,void 0,void 0,function*(){const u=yield a.createModeration(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},createSearch(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.createSearch(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},createTranscription(o,c,u,f,d,h,_){return e(this,void 0,void 0,function*(){const m=yield a.createTranscription(o,c,u,f,d,h,_);return r.createRequestFunction(m,t.default,n.BASE_PATH,l)})},createTranslation(o,c,u,f,d,h){return e(this,void 0,void 0,function*(){const _=yield a.createTranslation(o,c,u,f,d,h);return r.createRequestFunction(_,t.default,n.BASE_PATH,l)})},deleteFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.deleteFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},deleteModel(o,c){return e(this,void 0,void 0,function*(){const u=yield a.deleteModel(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},downloadFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.downloadFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},listEngines(o){return e(this,void 0,void 0,function*(){const c=yield a.listEngines(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listFiles(o){return e(this,void 0,void 0,function*(){const c=yield a.listFiles(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listFineTuneEvents(o,c,u){return e(this,void 0,void 0,function*(){const f=yield a.listFineTuneEvents(o,c,u);return r.createRequestFunction(f,t.default,n.BASE_PATH,l)})},listFineTunes(o){return e(this,void 0,void 0,function*(){const c=yield a.listFineTunes(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},listModels(o){return e(this,void 0,void 0,function*(){const c=yield a.listModels(o);return r.createRequestFunction(c,t.default,n.BASE_PATH,l)})},retrieveEngine(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveEngine(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveFile(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveFile(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveFineTune(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveFineTune(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})},retrieveModel(o,c){return e(this,void 0,void 0,function*(){const u=yield a.retrieveModel(o,c);return r.createRequestFunction(u,t.default,n.BASE_PATH,l)})}}},s.OpenAIApiFactory=function(l,a,o){const c=s.OpenAIApiFp(l);return{cancelFineTune(u,f){return c.cancelFineTune(u,f).then(d=>d(o,a))},createAnswer(u,f){return c.createAnswer(u,f).then(d=>d(o,a))},createChatCompletion(u,f){return c.createChatCompletion(u,f).then(d=>d(o,a))},createClassification(u,f){return c.createClassification(u,f).then(d=>d(o,a))},createCompletion(u,f){return c.createCompletion(u,f).then(d=>d(o,a))},createEdit(u,f){return c.createEdit(u,f).then(d=>d(o,a))},createEmbedding(u,f){return c.createEmbedding(u,f).then(d=>d(o,a))},createFile(u,f,d){return c.createFile(u,f,d).then(h=>h(o,a))},createFineTune(u,f){return c.createFineTune(u,f).then(d=>d(o,a))},createImage(u,f){return c.createImage(u,f).then(d=>d(o,a))},createImageEdit(u,f,d,h,_,m,w,v){return c.createImageEdit(u,f,d,h,_,m,w,v).then(E=>E(o,a))},createImageVariation(u,f,d,h,_,m){return c.createImageVariation(u,f,d,h,_,m).then(w=>w(o,a))},createModeration(u,f){return c.createModeration(u,f).then(d=>d(o,a))},createSearch(u,f,d){return c.createSearch(u,f,d).then(h=>h(o,a))},createTranscription(u,f,d,h,_,m,w){return c.createTranscription(u,f,d,h,_,m,w).then(v=>v(o,a))},createTranslation(u,f,d,h,_,m){return c.createTranslation(u,f,d,h,_,m).then(w=>w(o,a))},deleteFile(u,f){return c.deleteFile(u,f).then(d=>d(o,a))},deleteModel(u,f){return c.deleteModel(u,f).then(d=>d(o,a))},downloadFile(u,f){return c.downloadFile(u,f).then(d=>d(o,a))},listEngines(u){return c.listEngines(u).then(f=>f(o,a))},listFiles(u){return c.listFiles(u).then(f=>f(o,a))},listFineTuneEvents(u,f,d){return c.listFineTuneEvents(u,f,d).then(h=>h(o,a))},listFineTunes(u){return c.listFineTunes(u).then(f=>f(o,a))},listModels(u){return c.listModels(u).then(f=>f(o,a))},retrieveEngine(u,f){return c.retrieveEngine(u,f).then(d=>d(o,a))},retrieveFile(u,f){return c.retrieveFile(u,f).then(d=>d(o,a))},retrieveFineTune(u,f){return c.retrieveFineTune(u,f).then(d=>d(o,a))},retrieveModel(u,f){return c.retrieveModel(u,f).then(d=>d(o,a))}}};class i extends n.BaseAPI{cancelFineTune(a,o){return s.OpenAIApiFp(this.configuration).cancelFineTune(a,o).then(c=>c(this.axios,this.basePath))}createAnswer(a,o){return s.OpenAIApiFp(this.configuration).createAnswer(a,o).then(c=>c(this.axios,this.basePath))}createChatCompletion(a,o){return s.OpenAIApiFp(this.configuration).createChatCompletion(a,o).then(c=>c(this.axios,this.basePath))}createClassification(a,o){return s.OpenAIApiFp(this.configuration).createClassification(a,o).then(c=>c(this.axios,this.basePath))}createCompletion(a,o){return s.OpenAIApiFp(this.configuration).createCompletion(a,o).then(c=>c(this.axios,this.basePath))}createEdit(a,o){return s.OpenAIApiFp(this.configuration).createEdit(a,o).then(c=>c(this.axios,this.basePath))}createEmbedding(a,o){return s.OpenAIApiFp(this.configuration).createEmbedding(a,o).then(c=>c(this.axios,this.basePath))}createFile(a,o,c){return s.OpenAIApiFp(this.configuration).createFile(a,o,c).then(u=>u(this.axios,this.basePath))}createFineTune(a,o){return s.OpenAIApiFp(this.configuration).createFineTune(a,o).then(c=>c(this.axios,this.basePath))}createImage(a,o){return s.OpenAIApiFp(this.configuration).createImage(a,o).then(c=>c(this.axios,this.basePath))}createImageEdit(a,o,c,u,f,d,h,_){return s.OpenAIApiFp(this.configuration).createImageEdit(a,o,c,u,f,d,h,_).then(m=>m(this.axios,this.basePath))}createImageVariation(a,o,c,u,f,d){return s.OpenAIApiFp(this.configuration).createImageVariation(a,o,c,u,f,d).then(h=>h(this.axios,this.basePath))}createModeration(a,o){return s.OpenAIApiFp(this.configuration).createModeration(a,o).then(c=>c(this.axios,this.basePath))}createSearch(a,o,c){return s.OpenAIApiFp(this.configuration).createSearch(a,o,c).then(u=>u(this.axios,this.basePath))}createTranscription(a,o,c,u,f,d,h){return s.OpenAIApiFp(this.configuration).createTranscription(a,o,c,u,f,d,h).then(_=>_(this.axios,this.basePath))}createTranslation(a,o,c,u,f,d){return s.OpenAIApiFp(this.configuration).createTranslation(a,o,c,u,f,d).then(h=>h(this.axios,this.basePath))}deleteFile(a,o){return s.OpenAIApiFp(this.configuration).deleteFile(a,o).then(c=>c(this.axios,this.basePath))}deleteModel(a,o){return s.OpenAIApiFp(this.configuration).deleteModel(a,o).then(c=>c(this.axios,this.basePath))}downloadFile(a,o){return s.OpenAIApiFp(this.configuration).downloadFile(a,o).then(c=>c(this.axios,this.basePath))}listEngines(a){return s.OpenAIApiFp(this.configuration).listEngines(a).then(o=>o(this.axios,this.basePath))}listFiles(a){return s.OpenAIApiFp(this.configuration).listFiles(a).then(o=>o(this.axios,this.basePath))}listFineTuneEvents(a,o,c){return s.OpenAIApiFp(this.configuration).listFineTuneEvents(a,o,c).then(u=>u(this.axios,this.basePath))}listFineTunes(a){return s.OpenAIApiFp(this.configuration).listFineTunes(a).then(o=>o(this.axios,this.basePath))}listModels(a){return s.OpenAIApiFp(this.configuration).listModels(a).then(o=>o(this.axios,this.basePath))}retrieveEngine(a,o){return s.OpenAIApiFp(this.configuration).retrieveEngine(a,o).then(c=>c(this.axios,this.basePath))}retrieveFile(a,o){return s.OpenAIApiFp(this.configuration).retrieveFile(a,o).then(c=>c(this.axios,this.basePath))}retrieveFineTune(a,o){return s.OpenAIApiFp(this.configuration).retrieveFineTune(a,o).then(c=>c(this.axios,this.basePath))}retrieveModel(a,o){return s.OpenAIApiFp(this.configuration).retrieveModel(a,o).then(c=>c(this.axios,this.basePath))}}s.OpenAIApi=i})(gi);var An={};const fo="openai",ho="3.2.1",po="Node.js library for the OpenAI API",mo={type:"git",url:"git@github.com:openai/openai-node.git"},go=["openai","open","ai","gpt-3","gpt3"],_o="OpenAI",bo="MIT",vo="./dist/index.js",wo="./dist/index.d.ts",yo={build:"tsc --outDir dist/"},ko={axios:"^0.26.0","form-data":"^4.0.0"},Oo={"@types/node":"^12.11.5",typescript:"^3.6.4"},So={name:fo,version:ho,description:po,repository:mo,keywords:go,author:_o,license:bo,main:vo,types:wo,scripts:yo,dependencies:ko,devDependencies:Oo};var Kn,ds;function Ao(){return ds||(ds=1,Kn=typeof self=="object"?self.FormData:window.FormData),Kn}Object.defineProperty(An,"__esModule",{value:!0});An.Configuration=void 0;const Eo=So;class Po{constructor(e={}){this.apiKey=e.apiKey,this.organization=e.organization,this.username=e.username,this.password=e.password,this.accessToken=e.accessToken,this.basePath=e.basePath,this.baseOptions=e.baseOptions,this.formDataCtor=e.formDataCtor,this.baseOptions||(this.baseOptions={}),this.baseOptions.headers=Object.assign({"User-Agent":`OpenAI/NodeJS/${Eo.version}`,Authorization:`Bearer ${this.apiKey}`},this.baseOptions.headers),this.organization&&(this.baseOptions.headers["OpenAI-Organization"]=this.organization),this.formDataCtor||(this.formDataCtor=Ao())}isJsonMime(e){const t=new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$","i");return e!==null&&(t.test(e)||e.toLowerCase()==="application/json-patch+json")}}An.Configuration=Po;(function(s){var e=gt&>.__createBinding||(Object.create?function(r,n,i,l){l===void 0&&(l=i),Object.defineProperty(r,l,{enumerable:!0,get:function(){return n[i]}})}:function(r,n,i,l){l===void 0&&(l=i),r[l]=n[i]}),t=gt&>.__exportStar||function(r,n){for(var i in r)i!=="default"&&!n.hasOwnProperty(i)&&e(n,r,i)};Object.defineProperty(s,"__esModule",{value:!0}),t(gi,s),t(An,s)})(nr);const dn=ye(!1),hn=ye(!1),lr=ye(!1);let hs=localStorage.getItem("api_key"),To=hs!==null?JSON.parse(hs):null;const Je=ye(To);Je.subscribe(s=>localStorage.setItem("api_key",JSON.stringify(s)));let ps=localStorage.getItem("combined_tokens"),$o=ps!==null?JSON.parse(ps):0;const Ot=ye($o);Ot.subscribe(s=>localStorage.setItem("combined_tokens",JSON.stringify(s)));let ms=localStorage.getItem("default_assistant_role"),Co=ms!==null?JSON.parse(ms):0;const ht=ye(Co||{role:"You are a helpful assistant.",type:"system"});ht.subscribe(s=>localStorage.setItem("default_assistant_role",JSON.stringify(s)));const xe=ye(0);let gs=localStorage.getItem("conversations"),Ro=gs!==null?JSON.parse(gs):null;const re=ye(Ro||[{history:[],conversationTokens:0,assistantRole:"You are a helpful assistant.",title:""}]);re.subscribe(s=>{localStorage.setItem("conversations",JSON.stringify(s))});const $e=ye(localStorage.getItem("selectedModel")||"gpt-3.5-turbo"),qt=ye(localStorage.getItem("selectedVoice")||"alloy"),wt=ye(localStorage.getItem("selectedMode")||"GPT"),pn=ye(localStorage.getItem("selectedSize")||"1024x1024"),mn=ye(localStorage.getItem("selectedQuality")||"standard");$e.subscribe(s=>{localStorage.setItem("selectedModel",s)});qt.subscribe(s=>{localStorage.setItem("selectedVoice",s)});pn.subscribe(s=>{localStorage.setItem("selectedSize",s)});mn.subscribe(s=>{localStorage.setItem("selectedQuality",s)});wt.subscribe(s=>{localStorage.setItem("selectedMode",s)});const Ft=ye([]),or=ye(!1),_s=ye(!1),Ue=ye(!1),st=ye(!1),Jt=ye({streamText:"",convId:null});let bs=localStorage.getItem("show_tokens"),xo=bs!==null?JSON.parse(bs):!1;const Gt=ye(xo);Gt.subscribe(s=>{localStorage.setItem("show_tokens",JSON.stringify(s))});let Io="";function tt(s,e=I(xe)){return new Promise((t,r)=>{try{let n=I(re);n[e].history=s,re.set(n),t()}catch(n){console.error("Failed to update history",n),r(n)}})}function vs(s){const e=I(xe),t=I(re),r=t[e].history.filter((n,i)=>i!==s);t[e].history=r,re.set(t)}function Ri(){const s=I(re);if(s.length>0&&s[s.length-1].history.length===0){console.log("Jumping to recent conversation."),xe.set(s.length-1);return}const e={history:[],conversationTokens:0,assistantRole:I(ht).role,title:""};re.update(t=>[...t,e]),xe.set(I(re).length-1)}function En(s){const e=["role","content"];let t=Object.keys(s).filter(r=>e.includes(r)).reduce((r,n)=>(r[n]=s[n],r),{});return Array.isArray(t.content)||(t.content=t.content.toString()),t}async function ws(s,e,t){let r=I(re)[e].history,n=r;r=[...r,{role:"user",content:s}],tt(r);const i="gpt-3.5-turbo",l="alloy",a=I($e)||i,o=I(qt)||l;let c;if(c=[...n,{role:"user",content:s}],a.includes("tts"))await ia(s,a,o);else if(a.includes("vision")){const u=I(Ft);await la(c,u,e)}else a.includes("dall-e")?await ca(c,e):t?await aa(c,e,t):await oa(c,e);(I(re)[e].history.length===1||I(re)[e].title==="")&&await Fo(s)}function jo(s){let e=I(re);e[I(xe)].title=s,re.set(e)}async function Fo(s){let t=await sa([{role:"user",content:s},{role:"user",content:"Generate a title for this conversation, so I can easily reference it later. Maximum 6 words. Don't provide anything other than the title. Don't use quotes."}],"gpt-4-turbo-preview");if(t){let r=t.data.choices[0].message.content;jo(r.toString())}}function Mo(s){const e={role:"assistant",content:"Audio file generated.",audioUrl:s,isAudio:!0};tt([...I(re)[I(xe)].history,e])}function Uo(s){let e=I(re);e[I(xe)].conversationTokens=e[I(xe)].conversationTokens+s.total_tokens,re.set(e),Ot.set(I(Ot)+s.total_tokens),console.log("Counted tokens: "+s.total_tokens)}function Or(s,e){let t=0;s.map(i=>{t+=i.content.length}),t+=Io.length;let r=t/4,n=I(re);n[e].conversationTokens=n[e].conversationTokens+r,re.set(n),Ot.set(I(Ot)+r)}var Pn={};(function(s){var e=function(t,r){if(!(this instanceof e))return new e(t,r);this.INITIALIZING=-1,this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this.url=t,r=r||{},this.headers=r.headers||{},this.payload=r.payload!==void 0?r.payload:"",this.method=r.method||this.payload&&"POST"||"GET",this.withCredentials=!!r.withCredentials,this.FIELD_SEPARATOR=":",this.listeners={},this.xhr=null,this.readyState=this.INITIALIZING,this.progress=0,this.chunk="",this.addEventListener=function(n,i){this.listeners[n]===void 0&&(this.listeners[n]=[]),this.listeners[n].indexOf(i)===-1&&this.listeners[n].push(i)},this.removeEventListener=function(n,i){if(this.listeners[n]!==void 0){var l=[];this.listeners[n].forEach(function(a){a!==i&&l.push(a)}),l.length===0?delete this.listeners[n]:this.listeners[n]=l}},this.dispatchEvent=function(n){if(!n)return!0;n.source=this;var i="on"+n.type;return this.hasOwnProperty(i)&&(this[i].call(this,n),n.defaultPrevented)?!1:this.listeners[n.type]?this.listeners[n.type].every(function(l){return l(n),!n.defaultPrevented}):!0},this._setReadyState=function(n){var i=new CustomEvent("readystatechange");i.readyState=n,this.readyState=n,this.dispatchEvent(i)},this._onStreamFailure=function(n){var i=new CustomEvent("error");i.data=n.currentTarget.response,this.dispatchEvent(i),this.close()},this._onStreamAbort=function(n){this.dispatchEvent(new CustomEvent("abort")),this.close()},this._onStreamProgress=function(n){if(this.xhr){if(this.xhr.status!==200){this._onStreamFailure(n);return}this.readyState==this.CONNECTING&&(this.dispatchEvent(new CustomEvent("open")),this._setReadyState(this.OPEN));var i=this.xhr.responseText.substring(this.progress);this.progress+=i.length,i.split(/(\r\n|\r|\n){2}/g).forEach(function(l){l.trim().length===0?(this.dispatchEvent(this._parseEventChunk(this.chunk.trim())),this.chunk=""):this.chunk+=l}.bind(this))}},this._onStreamLoaded=function(n){this._onStreamProgress(n),this.dispatchEvent(this._parseEventChunk(this.chunk)),this.chunk=""},this._parseEventChunk=function(n){if(!n||n.length===0)return null;var i={id:null,retry:null,data:"",event:"message"};n.split(/\n|\r\n|\r/).forEach(function(a){a=a.trimRight();var o=a.indexOf(this.FIELD_SEPARATOR);if(!(o<=0)){var c=a.substring(0,o);if(c in i){var u=a.substring(o+1).trimLeft();c==="data"?i[c]+=u:i[c]=u}}}.bind(this));var l=new CustomEvent(i.event);return l.data=i.data,l.id=i.id,l},this._checkStreamClosed=function(){this.xhr&&this.xhr.readyState===XMLHttpRequest.DONE&&this._setReadyState(this.CLOSED)},this.stream=function(){this._setReadyState(this.CONNECTING),this.xhr=new XMLHttpRequest,this.xhr.addEventListener("progress",this._onStreamProgress.bind(this)),this.xhr.addEventListener("load",this._onStreamLoaded.bind(this)),this.xhr.addEventListener("readystatechange",this._checkStreamClosed.bind(this)),this.xhr.addEventListener("error",this._onStreamFailure.bind(this)),this.xhr.addEventListener("abort",this._onStreamAbort.bind(this)),this.xhr.open(this.method,this.url);for(var n in this.headers)this.xhr.setRequestHeader(n,this.headers[n]);this.xhr.withCredentials=this.withCredentials,this.xhr.send(this.payload)},this.close=function(){this.readyState!==this.CLOSED&&(this.xhr.abort(),this.xhr=null,this._setReadyState(this.CLOSED))}};s.SSE=e})(Pn);function gn(s){return s.replace(/\n/g,` +`)}async function Bo(s){try{return await navigator.clipboard.writeText(s),console.log("Text successfully copied to clipboard"),!0}catch(e){return console.error("Failed to copy text to clipboard: ",e),!1}}function ar(s){return s.isAudio===!0}function Sr(s){return s.split("").filter(t=>t==="`").length}const cr=(s,e)=>e.some(t=>s instanceof t);let ys,ks;function Vo(){return ys||(ys=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Do(){return ks||(ks=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const ur=new WeakMap,Zn=new WeakMap,Tn=new WeakMap;function Lo(s){const e=new Promise((t,r)=>{const n=()=>{s.removeEventListener("success",i),s.removeEventListener("error",l)},i=()=>{t(kt(s.result)),n()},l=()=>{r(s.error),n()};s.addEventListener("success",i),s.addEventListener("error",l)});return Tn.set(e,s),e}function No(s){if(ur.has(s))return;const e=new Promise((t,r)=>{const n=()=>{s.removeEventListener("complete",i),s.removeEventListener("error",l),s.removeEventListener("abort",l)},i=()=>{t(),n()},l=()=>{r(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",i),s.addEventListener("error",l),s.addEventListener("abort",l)});ur.set(s,e)}let fr={get(s,e,t){if(s instanceof IDBTransaction){if(e==="done")return ur.get(s);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return kt(s[e])},set(s,e,t){return s[e]=t,!0},has(s,e){return s instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in s}};function xi(s){fr=s(fr)}function qo(s){return Do().includes(s)?function(...e){return s.apply(dr(this),e),kt(this.request)}:function(...e){return kt(s.apply(dr(this),e))}}function zo(s){return typeof s=="function"?qo(s):(s instanceof IDBTransaction&&No(s),cr(s,Vo())?new Proxy(s,fr):s)}function kt(s){if(s instanceof IDBRequest)return Lo(s);if(Zn.has(s))return Zn.get(s);const e=zo(s);return e!==s&&(Zn.set(s,e),Tn.set(e,s)),e}const dr=s=>Tn.get(s);function Ho(s,e,{blocked:t,upgrade:r,blocking:n,terminated:i}={}){const l=indexedDB.open(s,e),a=kt(l);return r&&l.addEventListener("upgradeneeded",o=>{r(kt(l.result),o.oldVersion,o.newVersion,kt(l.transaction),o)}),t&&l.addEventListener("blocked",o=>t(o.oldVersion,o.newVersion,o)),a.then(o=>{i&&o.addEventListener("close",()=>i()),n&&o.addEventListener("versionchange",c=>n(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}const Jo=["get","getKey","getAll","getAllKeys","count"],Go=["put","add","delete","clear"],Xn=new Map;function Os(s,e){if(!(s instanceof IDBDatabase&&!(e in s)&&typeof e=="string"))return;if(Xn.get(e))return Xn.get(e);const t=e.replace(/FromIndex$/,""),r=e!==t,n=Go.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(n||Jo.includes(t)))return;const i=async function(l,...a){const o=this.transaction(l,n?"readwrite":"readonly");let c=o.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[t](...a),n&&o.done]))[0]};return Xn.set(e,i),i}xi(s=>({...s,get:(e,t,r)=>Os(e,t)||s.get(e,t,r),has:(e,t)=>!!Os(e,t)||s.has(e,t)}));const Qo=["continue","continuePrimaryKey","advance"],Ss={},hr=new WeakMap,Ii=new WeakMap,Yo={get(s,e){if(!Qo.includes(e))return s[e];let t=Ss[e];return t||(t=Ss[e]=function(...r){hr.set(this,Ii.get(this)[e](...r))}),t}};async function*Wo(...s){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...s)),!e)return;e=e;const t=new Proxy(e,Yo);for(Ii.set(t,e),Tn.set(t,dr(e));e;)yield t,e=await(hr.get(t)||e.continue()),hr.delete(t)}function As(s,e){return e===Symbol.asyncIterator&&cr(s,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&cr(s,[IDBIndex,IDBObjectStore])}xi(s=>({...s,get(e,t,r){return As(e,t)?Wo:s.get(e,t,r)},has(e,t){return As(e,t)||s.has(e,t)}}));const Ar=Ho("audio-store",1,{upgrade(s){s.createObjectStore("audios",{keyPath:"id"})}});async function Ko(s,e,t){const n=(await Ar).transaction("audios","readwrite");return n.objectStore("audios").put({id:s,blob:e,conversationId:t}),n.done}async function Zo(s){return(await(await Ar).transaction("audios","readonly").objectStore("audios").get(s))?.blob}async function Xo(){const e=(await Ar).transaction("audios","readwrite");return await e.objectStore("audios").clear(),e.done}function ea(s){zt();const e=s.target.files;for(let t of e){const r=new FileReader;r.onloadend=()=>{Ft.update(n=>[...n,r.result])},r.readAsDataURL(t)}}function zt(){Ft.set([]),or.set(!0)}let pr=null,ji=null,Qt=null;const ta=async()=>{if(Qt){Qt.close(),console.log("Stream closed by user."),Ue.set(!1);const{streamText:s,convId:e}=I(Jt);if(s&&e!==null){const t=s.replace(/█+$/,""),r=I(re)[e].history;let n=r.length?r[r.length-1]:null;n&&n.content.endsWith("█")?r[r.length-1]={...n,content:t}:r.push({role:"assistant",content:t}),await tt(r,e),Jt.set({streamText:"",convId:null})}st.set(!0),zt()}},na=[{role:"assistant",content:"There was an error. Maybe the API key is wrong? Or the servers could be down?"}];function Fi(){const s=I(Je);s?(pr=new nr.Configuration({apiKey:s}),ji=new nr.OpenAIApi(pr),console.log("OpenAI API initialized.")):console.warn("API key is not set. Please set the API key before initializing.")}function ra(){Fi(),console.log("Configuration reloaded.")}async function sa(s,e=I($e)){try{s=[{role:"system",content:I(re)[I(xe)].assistantRole},...s];const t=await ji.createChatCompletion({model:e,messages:s});if(t)return Uo(t.data.usage),t}catch(t){throw console.error("Error in sendRequest:",t),pr=null,await tt(na),t}}function Er(s){try{const e=/\{"id".*?\]\}/g;return(s.match(e)||[]).map(JSON.parse)}catch(e){return console.error("Error parsing JSON chunk:",e),null}}async function ia(s,e,t,r){console.log("Sending TTS message.");const n={model:e,voice:t,input:s};try{const i=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I(Je)}`},body:JSON.stringify(n)});if(!i.ok)throw new Error(`Failed to generate audio, response status: ${i.status}`);const l=await i.blob(),a=`audio-${Date.now()}-${Math.floor(Math.random()*1e4)}`;Ko(a,l).then(()=>{console.log("Audio blob saved to IndexedDB with ID:",a)}).catch(console.error),Zo(a).then(o=>{if(console.log(a),console.log(o),o instanceof Blob)if(o){const c=URL.createObjectURL(o);Mo(c)}else console.error("Blob is null or undefined");else console.error("Retrieved object is not a Blob:",o)}).catch(o=>console.error("Error retrieving audio blob:",o))}catch(i){console.error("TTS request error:",i)}}async function la(s,e,t){console.log("Sending vision message."),st.set(!1);let r=!1,n=0,i=!1,l=I(re)[t].history,a=l.map(v=>({role:v.role,content:typeof v.content=="string"?[{type:"text",text:v.content}]:v.content})),o=[...s].reverse().find(v=>v.role==="user")?.content||"",c=e.map(v=>({type:"image_url",image_url:{url:v}})),f={role:"user",content:o?[{type:"text",text:o},...c]:[...c]},h=[...a.map(En),f],_=!1,m="";l=[...l],Ue.set(!0);let w=new Pn.SSE("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${I(Je)}`},method:"POST",payload:JSON.stringify({model:I($e),messages:h,stream:!0})});console.log("payload",JSON.stringify({model:I($e),messages:h,stream:!0})),w.addEventListener("message",async v=>{if(v.data!=="[DONE]")try{r||Er(v.data).forEach(P=>{let O=P.choices[0]?.delta?.content;if(O){let F=Sr(O);n+=F,F===0&&(n=0),n===3&&(i=!i,n=0),m+=O,Jt.set({streamText:m,convId:t}),tt([...l,{role:"assistant",content:m+"█"+(i?"\n```":"")}],t)}})}catch(E){console.error("Error parsing JSON:",E),r=!0,w.close(),zt(),console.log("Stream closed due to parsing error."),Ue.set(!1);return}else _=!0,I(st)&&(m=m.replace(/█+$/,""),st.set(!1)),await tt([...l,{role:"assistant",content:m}],t),Or(s,t),m="",_=!0,console.log("Stream closed"),w.close(),zt(),Ue.set(!1)}),w.addEventListener("error",v=>{try{if(_)return;console.error("Stream error:",v)}finally{w.close(),zt(),Ue.set(!1)}}),w.stream(),Qt=w}async function oa(s,e){st.set(!1);let t=!1,r=0,n=!1,i=I(re)[e].history;s=[{role:I(ht).type,content:I(re)[e].assistantRole},...s];const a=s.map(En);let o=!1,c="";i=[...i],Ue.set(!0);let u=new Pn.SSE("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${I(Je)}`},method:"POST",payload:JSON.stringify({model:I($e),messages:a,stream:!0})});console.log("payload",JSON.stringify({model:I($e),messages:a,stream:!0})),u.addEventListener("message",async f=>{if(f.data!=="[DONE]")try{t||Er(f.data).forEach(h=>{let _=h.choices[0]?.delta?.content;if(_){let m=Sr(_);r+=m,m===0&&(r=0),r===3&&(n=!n,r=0),c+=_,Jt.set({streamText:c,convId:e}),tt([...i,{role:"assistant",content:c+"█"+(n?"\n```":"")}],e)}})}catch(d){console.error("Error parsing JSON:",d),t=!0,u.close(),console.log("Stream closed due to parsing error."),Ue.set(!1);return}else o=!0,I(st)&&(c=c.replace(/█+$/,""),st.set(!1)),await tt([...i,{role:"assistant",content:c}],e),Or(s,e),c="",o=!0,console.log("Stream closed"),u.close(),Ue.set(!1)}),u.addEventListener("error",f=>{try{if(o)return;console.error("Stream error:",f)}finally{u.close(),Ue.set(!1)}}),u.stream(),Qt=u}async function aa(s,e,t){st.set(!1);let r=!1,n=0,i=!1,l=I(re)[e].history,a={role:I(ht).type,content:I(re)[e].assistantRole},o={role:"system",content:t};l.push(o),s=[a,o,...s],console.log(s);const c=s.map(En);let u=!1,f="";l=[...l],Ue.set(!0);let d=new Pn.SSE("https://api.openai.com/v1/chat/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${I(Je)}`},method:"POST",payload:JSON.stringify({model:I($e),messages:c,stream:!0})});console.log("payload",JSON.stringify({model:I($e),messages:c,stream:!0})),d.addEventListener("message",async h=>{if(h.data!=="[DONE]")try{r||Er(h.data).forEach(m=>{let w=m.choices[0]?.delta?.content;if(w){let v=Sr(w);n+=v,v===0&&(n=0),n===3&&(i=!i,n=0),f+=w,Jt.set({streamText:f,convId:e}),tt([...l,{role:"assistant",content:f+"█"+(i?"\n```":"")}],e)}})}catch(_){console.error("Error parsing JSON:",_),r=!0,d.close(),console.log("Stream closed due to parsing error."),Ue.set(!1);return}else u=!0,I(st)&&(f=f.replace(/█+$/,""),st.set(!1)),await tt([...l,{role:"assistant",content:f}],e),Or(s,e),f="",u=!0,console.log("Stream closed"),d.close(),Ue.set(!1)}),d.addEventListener("error",h=>{try{if(u)return;console.error("Stream error:",h)}finally{d.close(),Ue.set(!1)}}),d.stream(),Qt=d}async function ca(s,e){Ue.set(!0);let t=I(re)[e].history;s=[{role:I(ht).type,content:I(re)[e].assistantRole},...s];const n=s.map(En),i=n[n.length-1].content;try{let l=await fetch("https://api.openai.com/v1/images/generations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I(Je)}`},body:JSON.stringify({model:I($e),prompt:i,size:I(pn),quality:I(mn),n:1})});if(!l.ok)throw new Error("HTTP error, status = "+l.status);let o=(await l.json()).data[0].url;tt([...t,{role:"assistant",content:o,type:"image"}],e)}catch(l){console.error("Error generating image:",l)}finally{Ue.set(!1)}}function mr(){const s=window.innerHeight*.01;document.documentElement.style.setProperty("--app-height",`${s}px`)}async function ua(){I(re).length>0&&xe.set(I(re).length-1),mr(),window.addEventListener("resize",mr);try{await Xo()}catch(s){console.error("Failed to clear audio blobs:",s)}Ft.set([]),Je.subscribe(s=>{s&&Fi()})}function fa(){window.removeEventListener("resize",mr)}function da(s){let e,t,r,n,i,l,a,o,c,u,f,d,h;return{c(){e=b("div"),t=b("div"),t.textContent="Your audio file is ready:",r=$(),n=b("button"),n.innerHTML='▶ Play',i=ae(`\r + | `),l=b("span"),a=b("a"),o=ae("⇓ Download"),c=b("div"),c.textContent="(unavailable after refresh!)",u=$(),f=b("audio"),p(t,"class","mb-2"),p(a,"href",s[0]),p(a,"download","response.mp3"),p(l,"class","downloadbutton svelte-2tsp55"),p(c,"class","notice svelte-2tsp55"),rt(f,"display","none")},m(_,m){k(_,e,m),g(e,t),g(e,r),g(e,n),g(e,i),g(e,l),g(l,a),g(a,o),g(e,c),g(e,u),g(e,f),s[3](f),d||(h=L(n,"click",s[2]),d=!0)},p(_,[m]){m&1&&p(a,"href",_[0])},i:U,o:U,d(_){_&&y(e),s[3](null),d=!1,h()}}}function ha(s,e,t){let{audioUrl:r=""}=e,n;function i(){n&&n.paused?n.play():n&&(n.pause(),t(1,n.currentTime=0,n))}function l(a){ut[a?"unshift":"push"](()=>{n=a,t(1,n),t(0,r)})}return s.$$set=a=>{"audioUrl"in a&&t(0,r=a.audioUrl)},s.$$.update=()=>{s.$$.dirty&3&&n&&r&&(t(1,n.src=r,n),n.load())},[r,n,i,l]}class pa extends ee{constructor(e){super(),X(this,e,ha,da,Z,{audioUrl:0})}}const ma="/assets/menu-fd7c077d.svg",ga="/assets/add-1d344fcd.svg";function _a(s){let e,t,r,n,i,l,a=(s[0]===""?"New Conversation":s[0])+"",o,c,u,f,d,h,_;return{c(){e=b("div"),t=b("button"),r=b("img"),i=$(),l=b("div"),o=ae(a),c=$(),u=b("button"),f=b("img"),p(r,"class","icon-white w-8"),p(r,"alt","Menu"),Ae(r.src,n=ma)||p(r,"src",n),p(t,"class","text-lg font-medium"),p(l,"class","text-lg font-medium pt-[3px] text-center overflow-hidden h-8"),p(f,"class","icon-white w-8"),p(f,"alt","+"),Ae(f.src,d=ga)||p(f,"src",d),p(u,"class","text-lg font-medium"),p(e,"class","bg-secondary text-white/90 py-2 px-4 flex justify-between md:hidden shrink grow-0 max-h-16")},m(m,w){k(m,e,w),g(e,t),g(t,r),g(e,i),g(e,l),g(l,o),g(e,c),g(e,u),g(u,f),h||(_=[L(t,"click",s[2]),L(u,"click",s[1])],h=!0)},p(m,[w]){w&1&&a!==(a=(m[0]===""?"New Conversation":m[0])+"")&&Pe(o,a)},i:U,o:U,d(m){m&&y(e),h=!1,Ne(_)}}}function ba(s,e,t){const r=wn();function n(){r("new-chat")}let{conversation_title:i}=e;const l=()=>{lr.set(!0)};return s.$$set=a=>{"conversation_title"in a&&t(0,i=a.conversation_title)},[i,n,l]}class va extends ee{constructor(e){super(),X(this,e,ba,_a,Z,{conversation_title:0})}}const _n="/assets/close-301080ff.svg",wa="/assets/NewChat-bf9b0f55.svg",Mi="/assets/edit-91842bde.svg";function Es(s,e,t){const r=s.slice();return r[30]=e[t],r[32]=t,r}function ya(s){let e;return{c(){e=b("textarea"),p(e,"placeholder","Select a conversation or start a new one..."),p(e,"class","bg-primary px-2 pt-1 pb-3 resize-none rounded focus:outline-none focus:outline-primary z-20")},m(t,r){k(t,e,r)},p:U,d(t){t&&y(e)}}}function ka(s){let e,t,r;return{c(){e=b("textarea"),p(e,"placeholder",s[7]),p(e,"class","bg-primary px-2 pt-1 pb-3 resize-none rounded focus:outline-none focus:outline-primary z-20")},m(n,i){k(n,e,i),Xe(e,s[4][s[3]].assistantRole),t||(r=L(e,"input",s[17]),t=!0)},p(n,i){i[0]&24&&Xe(e,n[4][n[3]].assistantRole)},d(n){n&&y(e),t=!1,r()}}}function Oa(s){let e,t=(s[30].title===""?"New conversation":s[30].title)+"",r,n;return{c(){e=b("p"),r=ae(t),p(e,"class",n="text-left text-sm flex-grow title-text "+(s[2],"")+" svelte-2c65x7")},m(i,l){k(i,e,l),g(e,r)},p(i,l){l[0]&16&&t!==(t=(i[30].title===""?"New conversation":i[30].title)+"")&&Pe(r,t),l[0]&4&&n!==(n="text-left text-sm flex-grow title-text "+(i[2],"")+" svelte-2c65x7")&&p(e,"class",n)},d(i){i&&y(e)}}}function Sa(s){let e,t,r;function n(){return s[19](s[32])}function i(...l){return s[20](s[32],...l)}return{c(){e=b("input"),p(e,"type","text"),p(e,"class","edit-input svelte-2c65x7")},m(l,a){k(l,e,a),Xe(e,s[1]),t||(r=[L(e,"input",s[18]),L(e,"blur",n),L(e,"keydown",i)],t=!0)},p(l,a){s=l,a[0]&2&&e.value!==s[1]&&Xe(e,s[1])},d(l){l&&y(e),t=!1,Ne(r)}}}function Ps(s){let e,t,r,n,i;function l(...o){return s[23](s[32],...o)}function a(...o){return s[24](s[32],...o)}return{c(){e=b("button"),t=b("img"),Ae(t.src,r=_n)||p(t,"src",r),p(t,"alt","Delete"),p(t,"class","icon-white min-w-5 w-5 h-5"),p(e,"tabindex","0"),p(e,"class","delete hidden rounded w-7 h-7 font-bold flex justify-center items-center hover:bg-warning svelte-2c65x7")},m(o,c){k(o,e,c),g(e,t),n||(i=[L(e,"click",cn(l)),L(e,"keydown",cn(a))],n=!0)},p(o,c){s=o},d(o){o&&y(e),n=!1,Ne(i)}}}function Ts(s){let e,t=s[30].conversationTokens.toFixed(0)+"",r;return{c(){e=b("p"),r=ae(t),p(e,"class","text-blue-200 tokens z-20 ml-5 svelte-2c65x7")},m(n,i){k(n,e,i),g(e,r)},p(n,i){i[0]&16&&t!==(t=n[30].conversationTokens.toFixed(0)+"")&&Pe(r,t)},d(n){n&&y(e)}}}function $s(s){let e,t,r,n,i,l,a,o,c,u,f,d;function h(C,N){return C[0]===C[4].length-C[32]-1?Sa:Oa}let _=h(s),m=_(s);function w(...C){return s[21](s[32],s[30],...C)}function v(...C){return s[22](s[32],s[30],...C)}let E=s[4].length>=2&&Ps(s),P=s[2]===!0&&Ts(s);function O(){return s[25](s[32])}function F(...C){return s[26](s[32],...C)}return{c(){e=b("div"),m.c(),t=$(),r=b("div"),n=b("button"),i=b("img"),a=$(),E&&E.c(),o=$(),P&&P.c(),c=$(),Ae(i.src,l=Mi)||p(i,"src",l),p(i,"alt","Edit"),p(i,"class","icon-white min-w-4 w-4 h-4"),p(n,"tabindex","0"),p(n,"class","edit hidden rounded w-7 h-7 font-bold flex justify-center items-center hover:bg-blue-600 svelte-2c65x7"),p(r,"class","flex items-center gap-2"),p(e,"class",u=(s[3]===s[4].length-s[32]-1?"bg-hover2 hover:bg-hover2":"")+" title-container conversation flex justify-between min-h-[50px] py-1 pl-3 items-center rounded-md hover:bg-hover cursor-pointer text-sm transition-colors duration-200 svelte-2c65x7"),p(e,"tabindex","-1")},m(C,N){k(C,e,N),m.m(e,null),g(e,t),g(e,r),g(r,n),g(n,i),g(r,a),E&&E.m(r,null),g(e,o),P&&P.m(e,null),g(e,c),f||(d=[L(n,"click",cn(w)),L(n,"keydown",cn(v)),L(e,"click",O),L(e,"keydown",F)],f=!0)},p(C,N){s=C,_===(_=h(s))&&m?m.p(s,N):(m.d(1),m=_(s),m&&(m.c(),m.m(e,t))),s[4].length>=2?E?E.p(s,N):(E=Ps(s),E.c(),E.m(r,null)):E&&(E.d(1),E=null),s[2]===!0?P?P.p(s,N):(P=Ts(s),P.c(),P.m(e,c)):P&&(P.d(1),P=null),N[0]&24&&u!==(u=(s[3]===s[4].length-s[32]-1?"bg-hover2 hover:bg-hover2":"")+" title-container conversation flex justify-between min-h-[50px] py-1 pl-3 items-center rounded-md hover:bg-hover cursor-pointer text-sm transition-colors duration-200 svelte-2c65x7")&&p(e,"class",u)},d(C){C&&y(e),m.d(),E&&E.d(),P&&P.d(),f=!1,Ne(d)}}}function Aa(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,_,m,w,v,E,P,O,F,C,N,ce,G,ne=s[6]===null?"(Insert API key)":"",oe,se,Oe,Te;function ve(B,J){return B[4][B[3]]?ka:ya}let Ee=ve(s),R=Ee(s),D=s[4].slice().reverse(),z=[];for(let B=0;BSystem Role:

    ',h=$(),R.c(),_=$(),m=b("div");for(let B=0;Bt(2,r=R)),fe(s,$e,R=>t(27,n=R)),fe(s,ht,R=>t(28,i=R)),fe(s,xe,R=>t(3,l=R)),fe(s,re,R=>t(4,a=R)),fe(s,lr,R=>t(5,o=R)),fe(s,Je,R=>t(6,c=R));const u=wn();let f="You are a helpful assistant.";function d(){u("new-chat")}function h(){hn.set(!1),dn.set(!0)}function _(){dn.set(!1),hn.set(!0)}async function m(R){if(console.log("Attempting to delete conversation at index:",R),a.length<=1){console.log("Deletion aborted: Cannot delete the last conversation.");return}let D=a.filter((z,B)=>B!==R);console.log("Updated conversations list after deletion attempt:",D),R===l?(xe.set(R>0?R-1:0),console.log("Selected conversation index adjusted to:",R>0?R-1:0)):R{let z=[...D];return z[R].title=v,z}),t(0,w=null)}function O(){let D=JSON.stringify({conversations:a,chosenConversationId:l,defaultAssistantRole:i,selectedModel:n,showTokens:r}),z=new Blob([D],{type:"application/json"}),B=URL.createObjectURL(z),J=document.createElement("a");J.href=B,J.download="smoothgpt-session.json",J.click(),URL.revokeObjectURL(B)}function F(){let R=document.createElement("input");R.type="file",R.accept=".json",R.onchange=async D=>{let z=R.files[0],B=new FileReader;B.onload=async J=>{let H=J.target.result,Ce=JSON.parse(H);re.set(Ce.conversations),xe.set(Ce.chosenConversationId),ht.set(Ce.defaultAssistantRole),$e.set(Ce.selectedModel),Gt.set(Ce.showTokens)},B.readAsText(z)},R.click()}const C=()=>{lr.set(!1)};function N(){a[l].assistantRole=this.value,re.set(a)}function ce(){v=this.value,t(1,v)}return[w,v,r,l,a,o,c,f,d,h,_,m,E,P,O,F,C,N,ce,R=>P(a.length-R-1),(R,D)=>{D.key==="Enter"&&(P(a.length-R-1),D.preventDefault())},(R,D,z)=>{let B=a.length-R-1;E(B,D.title)},(R,D,z)=>{if(z.key==="Enter"){z.preventDefault();let B=a.length-R-1;E(B,D.title)}},(R,D)=>{let z=a.length-R-1;m(z)},(R,D)=>{if(D.key==="Enter"){D.preventDefault();let z=a.length-R-1;m(z)}},R=>{let D=a.length-R-1;xe.set(D)},(R,D)=>{if(D.key==="Enter"){D.preventDefault();let z=a.length-R-1;xe.set(z)}}]}class Pa extends ee{constructor(e){super(),X(this,e,Ea,Aa,Z,{},null,[-1,-1])}}function Cs(s,e,t){const r=s.slice();return r[40]=e[t],r}function Rs(s){let e,t=s[40].id+"",r,n;return{c(){e=b("option"),r=ae(t),e.__value=n=s[40].id,e.value=e.__value},m(i,l){k(i,e,l),g(e,r)},p(i,l){l[0]&256&&t!==(t=i[40].id+"")&&Pe(r,t),l[0]&256&&n!==(n=i[40].id)&&(e.__value=n,e.value=e.__value)},d(i){i&&y(e)}}}function xs(s){let e,t,r,n,i,l,a,o,c,u,f,d;return{c(){e=b("div"),t=b("label"),t.textContent="Voice Selection",r=$(),n=b("select"),i=b("option"),i.textContent="Alloy",l=b("option"),l.textContent="Echo",a=b("option"),a.textContent="Fable",o=b("option"),o.textContent="Onyx",c=b("option"),c.textContent="Nova",u=b("option"),u.textContent="Shimmer",p(t,"for","voice-selection"),p(t,"class","block font-medium mb-2"),i.__value="alloy",i.value=i.__value,l.__value="echo",l.value=l.__value,a.__value="fable",a.value=a.__value,o.__value="onyx",o.value=o.__value,c.__value="nova",c.value=c.__value,u.__value="shimmer",u.value=u.__value,p(n,"class","border text-black border-gray-300 p-2 rounded w-full"),p(n,"id","voice-selection"),s[9]===void 0&&ft(()=>s[27].call(n)),p(e,"class","mb-4")},m(h,_){k(h,e,_),g(e,t),g(e,r),g(e,n),g(n,i),g(n,l),g(n,a),g(n,o),g(n,c),g(n,u),Ze(n,s[9]),f||(d=L(n,"change",s[27]),f=!0)},p(h,_){_[0]&512&&Ze(n,h[9])},d(h){h&&y(e),f=!1,d()}}}function Is(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,_,m,w;return{c(){e=b("div"),t=b("label"),t.textContent="Image Size",r=$(),n=b("select"),i=b("option"),i.textContent="1024x1024",l=b("option"),l.textContent="1024x1792",a=b("option"),a.textContent="1792x1024",o=$(),c=b("div"),u=b("label"),u.textContent="Image Quality",f=$(),d=b("select"),h=b("option"),h.textContent="standard",_=b("option"),_.textContent="hd",p(t,"for","size-selection"),p(t,"class","block font-medium mb-2"),i.__value="1024x1024",i.value=i.__value,l.__value="1024x1792",l.value=l.__value,a.__value="1792x1024",a.value=a.__value,p(n,"class","border text-black border-gray-300 p-2 rounded w-full"),p(n,"id","size-selection"),s[10]===void 0&&ft(()=>s[28].call(n)),p(e,"class","mb-4"),p(u,"for","quality-selection"),p(u,"class","block font-medium mb-2"),h.__value="standard",h.value=h.__value,_.__value="hd",_.value=_.__value,p(d,"class","border text-black border-gray-300 p-2 rounded w-full"),p(d,"id","quality-selection"),s[11]===void 0&&ft(()=>s[29].call(d)),p(c,"class","mb-4")},m(v,E){k(v,e,E),g(e,t),g(e,r),g(e,n),g(n,i),g(n,l),g(n,a),Ze(n,s[10]),k(v,o,E),k(v,c,E),g(c,u),g(c,f),g(c,d),g(d,h),g(d,_),Ze(d,s[11]),m||(w=[L(n,"change",s[28]),L(d,"change",s[29])],m=!0)},p(v,E){E[0]&1024&&Ze(n,v[10]),E[0]&2048&&Ze(d,v[11])},d(v){v&&y(e),v&&y(o),v&&y(c),m=!1,Ne(w)}}}function Ta(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,_,m,w,v,E,P,O,F,C,N,ce,G,ne,oe,se,Oe,Te,ve,Ee,R,D,z,B=s[7].startsWith("tts"),J,H=s[7].startsWith("dall-e"),Ce,Be,Ke,Ve,M,Se,be,Q,Qe,De,Le,x,ue,et,Fe,bt,Wt,T=s[12].toFixed(0)+"",Ye,at,At,Dt,Kt=(s[12]/1e3*.02).toFixed(2)+"",$n,Cr,Zt,Rr,Xt,vt,mt,ct,xr,Cn,Ir,Rn,jr,en,Fr,Et,Pt,Mr,Ur,Lt,xn,Br,Tt=s[8],qe=[];for(let te=0;teSee all API pricing',Rr=$(),Xt=b("div"),vt=b("label"),mt=b("div"),ct=b("input"),xr=$(),Cn=b("div"),Ir=$(),Rn=b("div"),jr=$(),en=b("div"),en.textContent="Show estimated tokens in sidebar",Fr=$(),Et=b("button"),Pt=b("img"),Ur=$(),Lt=b("button"),Lt.textContent="Save",p(i,"class","icon-white w-8"),p(i,"alt","Close"),Ae(i.src,l=_n)||p(i,"src",l),p(n,"class","absolute top-0 right-0 mt-2 mr-2 text-gray-500 hover:text-gray-600"),p(o,"class","text-xl font-bold mb-4"),p(f,"for","api-key"),p(f,"class","block font-medium mb-2"),p(_,"type","password"),p(_,"id","api-key"),p(_,"name","api-key"),p(_,"class","border text-black border-gray-300 p-2 rounded w-full"),p(w,"class","ml-2 bg-blue-600 hover:bg-blue-400 transition-colors duration-800 text-white p-2 rounded text-xs"),p(h,"class","flex items-center"),p(E,"class",O="mt-2 text-white rounded-lg p-2 "+(s[5]==="yellow"?"bg-yellow-600":"")+" "+(s[5]==="red"?"bg-red-600":"")+" "+(s[5]==="green"?"bg-green-600":"")),rt(E,"display",s[14]?"block":"none"),p(u,"class","mb-4"),p(N,"for","mode-selection"),p(N,"class","block font-medium mb-2"),ne.__value="GPT",ne.value=ne.__value,oe.__value="GPT + Vision",oe.value=oe.__value,se.__value="Dall-E",se.value=se.__value,Oe.__value="TTS",Oe.value=Oe.__value,p(G,"class","border text-black border-gray-300 p-2 rounded w-full"),p(G,"id","mode-selection"),s[0]===void 0&&ft(()=>s[25].call(G)),p(C,"class","mb-4"),p(Ee,"for","model-selection"),p(Ee,"class","block font-medium mb-2"),p(D,"class","border text-black border-gray-300 p-2 rounded w-full"),p(D,"id","model-selection"),s[7]===void 0&&ft(()=>s[26].call(D)),p(ve,"class","mb-4"),p(Ke,"for","api-key"),p(Ke,"class","block font-medium mb-2"),p(M,"class","border text-black border-gray-300 p-2 rounded w-full"),Qe.__value="system",Qe.value=Qe.__value,De.__value="user",De.value=De.__value,p(Q,"class","text-black p-2 rounded focus:outline-none focus:bg-white max-w-24"),s[3]===void 0&&ft(()=>s[31].call(Q)),p(x,"href","https://platform.openai.com/docs/guides/prompt-engineering/tactic-ask-the-model-to-adopt-a-persona"),p(x,"target","_blank"),p(x,"rel","noreferrer"),p(x,"class","text-blue-300 transition underline text-xs hover:text-blue-500"),p(be,"class","flex items-center my-2 space-x-2"),p(Be,"class","mb-4"),p(bt,"class","font-bold mb-2"),p(At,"class",""),p(Zt,"class","text-blue-300 transition underline text-xs hover:text-blue-500 mt-2"),p(ct,"type","checkbox"),p(ct,"id","show-tokens-toggle"),p(ct,"class","sr-only"),p(Cn,"class","block bg-gray-600 w-14 h-8 rounded-full"),p(Rn,"class","dot absolute left-1 top-1 bg-gray-100 w-6 h-6 rounded-full transition"),p(mt,"class","relative"),p(en,"class","ml-3 text-gray-200"),p(vt,"for","show-tokens-toggle"),p(vt,"class","flex items-center cursor-pointer"),p(Xt,"class","mt-4"),p(Fe,"class","flex flex-col"),p(Pt,"class","icon-white w-3"),p(Pt,"alt","Close"),Ae(Pt.src,Mr=_n)||p(Pt,"src",Mr),p(Et,"class","bg-warning hover:bg-warningHover transition-colors duration-200 text-white ml-10 px-4 py-2 flex align-middle justify-center rounded"),rt(Et,"font-size","1rem"),p(et,"class","flex justify-between items-start"),p(Lt,"class","bg-good hover:bg-good2 transition-colors duration-200 text-white py-2 px-4 mt-8 rounded"),p(r,"class","bg-primary text-white rounded-lg shadow-xl p-8 relative"),p(t,"class","flex items-center justify-center min-h-screen"),p(e,"class","fixed z-50 inset-0 overflow-y-auto animate-fade-in")},m(te,Re){k(te,e,Re),g(e,t),g(t,r),g(r,n),g(n,i),g(r,a),g(r,o),g(r,c),g(r,u),g(u,f),g(u,d),g(u,h),g(h,_),Xe(_,s[1]),g(h,m),g(h,w),g(u,v),g(u,E),g(E,P),g(r,F),g(r,C),g(C,N),g(C,ce),g(C,G),g(G,ne),g(G,oe),g(G,se),g(G,Oe),Ze(G,s[0]),g(r,Te),g(r,ve),g(ve,Ee),g(ve,R),g(ve,D);for(let Me=0;Met(34,r=M)),fe(s,Je,M=>t(22,n=M)),fe(s,wt,M=>t(0,l=M)),fe(s,$e,M=>t(7,c=M)),fe(s,qt,M=>t(9,f=M)),fe(s,pn,M=>t(10,d=M)),fe(s,mn,M=>t(11,h=M)),fe(s,Ot,M=>t(12,_=M));const m=wn();let w=ye("");fe(s,w,M=>t(6,o=M));let v=ye("");fe(s,v,M=>t(5,a=M));let E=ye([]);fe(s,E,M=>t(23,i=M));let P=ye([]);fe(s,P,M=>t(8,u=M));let O=I(Je)||"",F="";Je.subscribe(M=>{F=M||"",t(1,O=F)});let C=r.role,N=r.type;Je.subscribe(M=>{localStorage.setItem("api_key",JSON.stringify(M))});let ce=!1;Gt.subscribe(M=>{t(4,ce=M)}),vn(async()=>{await oe()});function G(){Gt.set(ce)}function ne(){let M=I(wt),Se=I(E),be=[];M==="GPT"?be=Se.filter(Q=>Q.id.includes("gpt")&&!Q.id.includes("vision")):M==="GPT + Vision"?be=Se.filter(Q=>Q.id.includes("vision")):M==="Dall-E"?be=Se.filter(Q=>Q.id.includes("dall-e")):M==="TTS"&&(be=Se.filter(Q=>Q.id.includes("tts"))),P.set(be),be.length>0&&(!I($e)||!be.some(Q=>Q.id===I($e)))&&$e.set(be[0].id)}async function oe(){const M=localStorage.getItem("selectedMode");if(wt.set(M||"GPT"),F)await Oe(F);else{const Se=localStorage.getItem("models");Se&&E.set(JSON.parse(Se))}ne()}async function se(){if(!O){v.set("yellow"),w.set("API key is missing.");return}try{const M=await fetch("https://api.openai.com/v1/models",{method:"GET",headers:{Authorization:`Bearer ${O}`,"Content-Type":"application/json"}});if(M.ok)v.set("green"),w.set("API connection succeeded."),ve(),await Oe(F),ne();else throw new Error(`HTTP error! status: ${M.status}`)}catch(M){console.error("API connection failed:",M),v.set("red"),w.set("API connection failed.")}}async function Oe(M){if(!M){v.set("yellow"),console.log("showMessage",v),console.error("API key is missing.");return}try{const Se=await fetch("https://api.openai.com/v1/models",{method:"GET",headers:{Authorization:`Bearer ${M}`,"Content-Type":"application/json"}});if(!Se.ok)throw new Error(`HTTP error! status: ${Se.status}`);const Q=(await Se.json()).data.sort((Qe,De)=>Qe.id.localeCompare(De.id));E.set(Q),localStorage.setItem("models",JSON.stringify(Q))}catch(Se){console.error("Failed to fetch models:",Se)}}function Te(){Ot.set(0)}function ve(){ht.set({role:C,type:N}),Je.set(O),localStorage.setItem("selectedModel",I($e)),localStorage.setItem("selectedVoice",I(qt)),localStorage.setItem("selectedMode",I(wt)),m("settings-changed"),console.log("Settings saved.")}function Ee(){dn.set(!1)}function R(){ve(),Ee()}function D(){O=this.value,t(1,O),t(22,n)}function z(){l=$t(this),wt.set(l)}function B(){c=$t(this),$e.set(c)}function J(){f=$t(this),qt.set(f)}function H(){d=$t(this),pn.set(d)}function Ce(){h=$t(this),mn.set(h)}function Be(){C=this.value,t(2,C)}function Ke(){N=$t(this),t(3,N)}function Ve(){ce=this.checked,t(4,ce)}return s.$$.update=()=>{s.$$.dirty[0]&1&&ne(),s.$$.dirty[0]&8388608&&ne(),s.$$.dirty[0]&4194304&&t(1,O=n||"")},[l,O,C,N,ce,a,o,c,u,f,d,h,_,w,v,E,P,G,se,Te,Ee,R,n,i,D,z,B,J,H,Ce,Be,Ke,Ve]}class Ca extends ee{constructor(e){super(),X(this,e,$a,Ta,Z,{},null,[-1,-1])}}function Ra(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,_;return{c(){e=b("div"),t=b("div"),r=b("div"),n=b("button"),i=b("img"),a=$(),o=b("h2"),o.textContent="Help & FAQ",c=$(),u=b("div"),u.innerHTML=`

    What is SmoothGPT?

    +

    OpenAI offers ChatGPT Plus for a monthly subscription, which allows you to use their UI to converse with ChatGPT. However, this comes with usage limits, and the $20/mo fee is expensive. Alternatively, you can use the OpenAI API, which is much more affordable with a pay-as-you-go rate. But, the API is not end-user friendly! It's designed for developers who can build apps around it.

    +

    That's where SmoothGPT comes in! SmoothGPT provides a UI that is extremely similar to the ChatGPT official site.

    + +

    Key Features:

    +
    • Your API calls are safely made directly in the browser, not server-side. All data is stored in your browser cache or session.
    • +
    • Switch between GPT, Vision, Dall-E, and TTS models with shared conversation context.
    • +
    • Upload PDFs or images and ask the AI questions about their contents.
    • +
    • Copy or delete messages easily.
    • +
    • Edit messages to change the conversation.
    • +
    • Safely stop incoming messages.
    • +
    • Edit conversation titles.
    • +
    • It's absolutely free.
    + + + + + +

    Note on data storage: If you browse away while a response is streaming in, you will miss that data. If you refresh your page, TTS MP3 files are lost, but conversations are maintained. Images generated by Dall-E are only available for 60 minutes. If you wipe your browser cache, ALL content is lost. You can download your session locally and restore it anytime.

    `,f=$(),d=b("button"),d.textContent="Got it!",p(i,"class","icon-white w-8"),p(i,"alt","Close"),Ae(i.src,l=_n)||p(i,"src",l),p(n,"class","absolute top-0 right-0 mt-2 mr-2 text-gray-500 hover:text-gray-600"),p(o,"class","text-xl font-bold mb-4"),p(u,"class","text-left"),p(d,"class","bg-good hover:bg-good2 transition-colors duration-200 text-white py-2 px-4 mt-4 rounded"),p(r,"class","bg-primary text-white rounded-lg shadow-xl p-8 relative max-w-lg mx-4"),p(t,"class","flex items-center justify-center min-h-screen"),p(e,"class","fixed z-50 inset-0 overflow-y-auto animate-fade-in")},m(m,w){k(m,e,w),g(e,t),g(t,r),g(r,n),g(n,i),g(r,a),g(r,o),g(r,c),g(r,u),g(r,f),g(r,d),h||(_=[L(n,"click",s[0]),L(d,"click",s[0])],h=!0)},p:U,i:U,o:U,d(m){m&&y(e),h=!1,Ne(_)}}}function xa(s){function e(){hn.set(!1)}return[e]}class Ia extends ee{constructor(e){super(),X(this,e,xa,Ra,Z,{})}}function ja(){const s=console.warn;console.warn=e=>{e.includes("unknown prop")||e.includes("unexpected slot")||s(e)},vn(()=>{console.warn=s})}function js(s,e,t){const r=s.slice();return r[18]=e[t],r}function Fs(s,e,t){const r=s.slice();return r[18]=e[t],r}function Ms(s,e,t){const r=s.slice();return r[10]=e[t],r}function Us(s,e,t){const r=s.slice();return r[13]=e[t],r[15]=t,r}function Bs(s,e,t){const r=s.slice();return r[16]=e[t],r[15]=t,r}function Vs(s,e,t){const r=s.slice();return r[7]=e[t],r}function Fa(s){let e,t,r,n;const i=[Va,Ba,Ua],l=[];function a(o,c){return o[0]==="table"?0:o[0]==="list"?1:2}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function Ma(s){let e,t,r=s[1],n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(u,1)}),le()}i?(e=we(i,l(a)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&S(e.$$.fragment,a),r=!0)},o(a){e&&A(e.$$.fragment,a),r=!1},d(a){a&&y(t),e&&W(e,a)}}}function Ba(s){let e,t,r,n;const i=[za,qa],l=[];function a(o,c){return o[4]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function Va(s){let e,t,r;var n=s[5].table;function i(l){return{props:{$$slots:{default:[tc]},$$scope:{ctx:l}}}}return n&&(e=we(n,i(s))),{c(){e&&K(e.$$.fragment),t=ge()},m(l,a){e&&Y(e,l,a),k(l,t,a),r=!0},p(l,a){const o={};if(a&8388716&&(o.$$scope={dirty:a,ctx:l}),n!==(n=l[5].table)){if(e){ie();const c=e;A(c.$$.fragment,1,0,()=>{W(c,1)}),le()}n?(e=we(n,i(l)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&S(e.$$.fragment,l),r=!0)},o(l){e&&A(e.$$.fragment,l),r=!1},d(l){l&&y(t),e&&W(e,l)}}}function Da(s){let e=s[6].raw+"",t;return{c(){t=ae(e)},m(r,n){k(r,t,n)},p(r,n){n&64&&e!==(e=r[6].raw+"")&&Pe(t,e)},i:U,o:U,d(r){r&&y(t)}}}function La(s){let e,t;return e=new St({props:{tokens:s[1],renderers:s[5]}}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p(r,n){const i={};n&2&&(i.tokens=r[1]),n&32&&(i.renderers=r[5]),e.$set(i)},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function Na(s){let e,t,r,n;const i=[La,Da],l=[];function a(o,c){return o[1]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,c){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function qa(s){let e,t,r;const n=[{ordered:s[4]},s[6]];var i=s[5].list;function l(a){let o={$$slots:{default:[Ja]},$$scope:{ctx:a}};for(let c=0;c{W(u,1)}),le()}i?(e=we(i,l(a)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&S(e.$$.fragment,a),r=!0)},o(a){e&&A(e.$$.fragment,a),r=!1},d(a){a&&y(t),e&&W(e,a)}}}function za(s){let e,t,r;const n=[{ordered:s[4]},s[6]];var i=s[5].list;function l(a){let o={$$slots:{default:[Qa]},$$scope:{ctx:a}};for(let c=0;c{W(u,1)}),le()}i?(e=we(i,l(a)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&S(e.$$.fragment,a),r=!0)},o(a){e&&A(e.$$.fragment,a),r=!1},d(a){a&&y(t),e&&W(e,a)}}}function Ha(s){let e,t,r;return e=new St({props:{tokens:s[18].tokens,renderers:s[5]}}),{c(){K(e.$$.fragment),t=$()},m(n,i){Y(e,n,i),k(n,t,i),r=!0},p(n,i){const l={};i&64&&(l.tokens=n[18].tokens),i&32&&(l.renderers=n[5]),e.$set(l)},i(n){r||(S(e.$$.fragment,n),r=!0)},o(n){A(e.$$.fragment,n),r=!1},d(n){W(e,n),n&&y(t)}}}function Ds(s){let e,t,r;const n=[s[18]];var i=s[5].unorderedlistitem||s[5].listitem;function l(a){let o={$$slots:{default:[Ha]},$$scope:{ctx:a}};for(let c=0;c{W(u,1)}),le()}i?(e=we(i,l(a)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&S(e.$$.fragment,a),r=!0)},o(a){e&&A(e.$$.fragment,a),r=!1},d(a){a&&y(t),e&&W(e,a)}}}function Ja(s){let e,t,r=s[6].items,n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(u,1)}),le()}i?(e=we(i,l(a)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else i&&e.$set(c)},i(a){r||(e&&S(e.$$.fragment,a),r=!0)},o(a){e&&A(e.$$.fragment,a),r=!1},d(a){a&&y(t),e&&W(e,a)}}}function Qa(s){let e,t,r=s[6].items,n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(c,1)}),le()}n?(e=we(n,i(l)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&S(e.$$.fragment,l),r=!0)},o(l){e&&A(e.$$.fragment,l),r=!1},d(l){l&&y(t),e&&W(e,l)}}}function Wa(s){let e,t,r=s[2],n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(c,1)}),le()}n?(e=we(n,i(l)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&S(e.$$.fragment,l),r=!0)},o(l){e&&A(e.$$.fragment,l),r=!1},d(l){l&&y(t),e&&W(e,l)}}}function Za(s){let e,t;return e=new St({props:{tokens:s[13].tokens,renderers:s[5]}}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p(r,n){const i={};n&8&&(i.tokens=r[13].tokens),n&32&&(i.renderers=r[5]),e.$set(i)},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function qs(s){let e,t,r;var n=s[5].tablecell;function i(l){return{props:{header:!1,align:l[6].align[l[15]]||"center",$$slots:{default:[Za]},$$scope:{ctx:l}}}}return n&&(e=we(n,i(s))),{c(){e&&K(e.$$.fragment),t=ge()},m(l,a){e&&Y(e,l,a),k(l,t,a),r=!0},p(l,a){const o={};if(a&64&&(o.align=l[6].align[l[15]]||"center"),a&8388648&&(o.$$scope={dirty:a,ctx:l}),n!==(n=l[5].tablecell)){if(e){ie();const c=e;A(c.$$.fragment,1,0,()=>{W(c,1)}),le()}n?(e=we(n,i(l)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&S(e.$$.fragment,l),r=!0)},o(l){e&&A(e.$$.fragment,l),r=!1},d(l){l&&y(t),e&&W(e,l)}}}function Xa(s){let e,t,r=s[10],n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(c,1)}),le()}n?(e=we(n,i(l)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else n&&e.$set(o)},i(l){r||(e&&S(e.$$.fragment,l),r=!0)},o(l){e&&A(e.$$.fragment,l),r=!1},d(l){l&&y(t),e&&W(e,l)}}}function ec(s){let e,t,r=s[3],n=[];for(let l=0;lA(n[l],1,1,()=>{n[l]=null});return{c(){for(let l=0;l{W(_,1)}),le()}l?(e=we(l,a(u)),K(e.$$.fragment),S(e.$$.fragment,1),Y(e,t.parentNode,t)):e=null}else l&&e.$set(d);const h={};if(f&8388712&&(h.$$scope={dirty:f,ctx:u}),o!==(o=u[5].tablebody)){if(r){ie();const _=r;A(_.$$.fragment,1,0,()=>{W(_,1)}),le()}o?(r=we(o,c(u)),K(r.$$.fragment),S(r.$$.fragment,1),Y(r,n.parentNode,n)):r=null}else o&&r.$set(h)},i(u){i||(e&&S(e.$$.fragment,u),r&&S(r.$$.fragment,u),i=!0)},o(u){e&&A(e.$$.fragment,u),r&&A(r.$$.fragment,u),i=!1},d(u){e&&W(e,u),u&&y(t),u&&y(n),r&&W(r,u)}}}function Hs(s){let e,t;const r=[s[7],{renderers:s[5]}];let n={};for(let i=0;i{l[u]=null}),le()),~e?(t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r)):t=null)},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){~e&&l[e].d(o),o&&y(r)}}}function rc(s,e,t){const r=["type","tokens","header","rows","ordered","renderers"];let n=Lr(e,r),{type:i=void 0}=e,{tokens:l=void 0}=e,{header:a=void 0}=e,{rows:o=void 0}=e,{ordered:c=!1}=e,{renderers:u}=e;return ja(),s.$$set=f=>{e=dt(dt({},e),Zi(f)),t(6,n=Lr(e,r)),"type"in f&&t(0,i=f.type),"tokens"in f&&t(1,l=f.tokens),"header"in f&&t(2,a=f.header),"rows"in f&&t(3,o=f.rows),"ordered"in f&&t(4,c=f.ordered),"renderers"in f&&t(5,u=f.renderers)},[i,l,a,o,c,u,n]}let St=class extends ee{constructor(e){super(),X(this,e,rc,nc,Z,{type:0,tokens:1,header:2,rows:3,ordered:4,renderers:5})}};function Ui(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let Vt=Ui();function sc(s){Vt=s}const Bi=/[&<>"']/,ic=new RegExp(Bi.source,"g"),Vi=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,lc=new RegExp(Vi.source,"g"),oc={"&":"&","<":"<",">":">",'"':""","'":"'"},Js=s=>oc[s];function je(s,e){if(e){if(Bi.test(s))return s.replace(ic,Js)}else if(Vi.test(s))return s.replace(lc,Js);return s}const ac=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Di(s){return s.replace(ac,(e,t)=>(t=t.toLowerCase(),t==="colon"?":":t.charAt(0)==="#"?t.charAt(1)==="x"?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const cc=/(^|[^\[])\^/g;function _e(s,e){s=typeof s=="string"?s:s.source,e=e||"";const t={replace:(r,n)=>(n=n.source||n,n=n.replace(cc,"$1"),s=s.replace(r,n),t),getRegex:()=>new RegExp(s,e)};return t}const uc=/[^\w:]/g,fc=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Gs(s,e,t){if(s){let r;try{r=decodeURIComponent(Di(t)).replace(uc,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}e&&!fc.test(t)&&(t=mc(e,t));try{t=encodeURI(t).replace(/%25/g,"%")}catch{return null}return t}const nn={},dc=/^[^:]+:\/*[^/]*$/,hc=/^([^:]+:)[\s\S]*$/,pc=/^([^:]+:\/*[^/]*)[\s\S]*$/;function mc(s,e){nn[" "+s]||(dc.test(s)?nn[" "+s]=s+"/":nn[" "+s]=an(s,"/",!0)),s=nn[" "+s];const t=s.indexOf(":")===-1;return e.substring(0,2)==="//"?t?e:s.replace(hc,"$1")+e:e.charAt(0)==="/"?t?e:s.replace(pc,"$1")+e:s+e}const bn={exec:function(){}};function nt(s){let e=1,t,r;for(;e{let o=!1,c=l;for(;--c>=0&&a[c]==="\\";)o=!o;return o?"|":" |"}),r=t.split(/ \|/);let n=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>e)r.splice(e);else for(;r.length1;)e&1&&(t+=s),e>>=1,s+=s;return t+s}function Ws(s,e,t,r){const n=e.href,i=e.title?je(e.title):null,l=s[1].replace(/\\([\[\]])/g,"$1");if(s[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:t,href:n,title:i,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}return{type:"image",raw:t,href:n,title:i,text:je(l)}}function _c(s,e){const t=s.match(/^(\s+)(?:```)/);if(t===null)return e;const r=t[1];return e.split(` +`).map(n=>{const i=n.match(/^\s+/);if(i===null)return n;const[l]=i;return l.length>=r.length?n.slice(r.length):n}).join(` +`)}class Pr{constructor(e){this.options=e||Vt}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const r=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?r:an(r,` +`)}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const r=t[0],n=_c(r,t[3]||"");return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline._escapes,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(/#$/.test(r)){const n=an(r,"#");(this.options.pedantic||!n||/ $/.test(n))&&(r=n.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const r=t[0].replace(/^ *>[ \t]?/gm,""),n=this.lexer.state.top;this.lexer.state.top=!0;const i=this.lexer.blockTokens(r);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r,n,i,l,a,o,c,u,f,d,h,_,m=t[1].trim();const w=m.length>1,v={type:"list",raw:"",ordered:w,start:w?+m.slice(0,-1):"",loose:!1,items:[]};m=w?`\\d{1,9}\\${m.slice(-1)}`:`\\${m}`,this.options.pedantic&&(m=w?m:"[*+-]");const E=new RegExp(`^( {0,3}${m})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;e&&(_=!1,!(!(t=E.exec(e))||this.rules.block.hr.test(e)));){if(r=t[0],e=e.substring(r.length),u=t[2].split(` +`,1)[0].replace(/^\t+/,O=>" ".repeat(3*O.length)),f=e.split(` +`,1)[0],this.options.pedantic?(l=2,h=u.trimLeft()):(l=t[2].search(/[^ ]/),l=l>4?1:l,h=u.slice(l),l+=t[1].length),o=!1,!u&&/^ *$/.test(f)&&(r+=f+` +`,e=e.substring(f.length+1),_=!0),!_){const O=new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),F=new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),C=new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),N=new RegExp(`^ {0,${Math.min(3,l-1)}}#`);for(;e&&(d=e.split(` +`,1)[0],f=d,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(C.test(f)||N.test(f)||O.test(f)||F.test(e)));){if(f.search(/[^ ]/)>=l||!f.trim())h+=` +`+f.slice(l);else{if(o||u.search(/[^ ]/)>=4||C.test(u)||N.test(u)||F.test(u))break;h+=` +`+f}!o&&!f.trim()&&(o=!0),r+=d+` +`,e=e.substring(d.length+1),u=f.slice(l)}}v.loose||(c?v.loose=!0:/\n *\n *$/.test(r)&&(c=!0)),this.options.gfm&&(n=/^\[[ xX]\] /.exec(h),n&&(i=n[0]!=="[ ] ",h=h.replace(/^\[[ xX]\] +/,""))),v.items.push({type:"list_item",raw:r,task:!!n,checked:i,loose:!1,text:h}),v.raw+=r}v.items[v.items.length-1].raw=r.trimRight(),v.items[v.items.length-1].text=h.trimRight(),v.raw=v.raw.trimRight();const P=v.items.length;for(a=0;aC.type==="space"),F=O.length>0&&O.some(C=>/\n.*\n/.test(C.raw));v.loose=F}if(v.loose)for(a=0;a$/,"$1").replace(this.rules.inline._escapes,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline._escapes,"$1"):t[3];return{type:"def",tag:r,raw:t[0],href:n,title:i}}}table(e){const t=this.rules.block.table.exec(e);if(t){const r={type:"table",header:Qs(t[1]).map(n=>({text:n})),align:t[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split(` +`):[]};if(r.header.length===r.align.length){r.raw=t[0];let n=r.align.length,i,l,a,o;for(i=0;i({text:c}));for(n=r.header.length,l=0;l/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(t[0]):je(t[0]):t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const r=t[2].trim();if(!this.options.pedantic&&/^$/.test(r))return;const l=an(r.slice(0,-1),"\\");if((r.length-l.length)%2===0)return}else{const l=gc(t[2],"()");if(l>-1){const o=(t[0].indexOf("!")===0?5:4)+t[1].length+l;t[2]=t[2].substring(0,l),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){const l=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);l&&(n=l[1],i=l[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^$/.test(r)?n=n.slice(1):n=n.slice(1,-1)),Ws(t,{href:n&&n.replace(this.rules.inline._escapes,"$1"),title:i&&i.replace(this.rules.inline._escapes,"$1")},t[0],this.lexer)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(/\s+/g," ");if(n=t[n.toLowerCase()],!n){const i=r[0].charAt(0);return{type:"text",raw:i,text:i}}return Ws(r,n,r[0],this.lexer)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrong.lDelim.exec(e);if(!n||n[3]&&r.match(/[\p{L}\p{N}]/u))return;const i=n[1]||n[2]||"";if(!i||i&&(r===""||this.rules.inline.punctuation.exec(r))){const l=n[0].length-1;let a,o,c=l,u=0;const f=n[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+l);(n=f.exec(t))!=null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a)continue;if(o=a.length,n[3]||n[4]){c+=o;continue}else if((n[5]||n[6])&&l%3&&!((l+o)%3)){u+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c+u);const d=e.slice(0,l+n.index+(n[0].length-a.length)+o);if(Math.min(l,o)%2){const _=d.slice(1,-1);return{type:"em",raw:d,text:_,tokens:this.lexer.inlineTokens(_)}}const h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(/\n/g," ");const n=/[^ ]/.test(r),i=/^ /.test(r)&&/ $/.test(r);return n&&i&&(r=r.substring(1,r.length-1)),r=je(r,!0),{type:"codespan",raw:t[0],text:r}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e,t){const r=this.rules.inline.autolink.exec(e);if(r){let n,i;return r[2]==="@"?(n=je(this.options.mangle?t(r[1]):r[1]),i="mailto:"+n):(n=je(r[1]),i=n),{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(e,t){let r;if(r=this.rules.inline.url.exec(e)){let n,i;if(r[2]==="@")n=je(this.options.mangle?t(r[0]):r[0]),i="mailto:"+n;else{let l;do l=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(l!==r[0]);n=je(r[0]),r[1]==="www."?i="http://"+r[0]:i=r[0]}return{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e,t){const r=this.rules.inline.text.exec(e);if(r){let n;return this.lexer.state.inRawBlock?n=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):je(r[0]):r[0]:n=je(this.options.smartypants?t(r[0]):r[0]),{type:"text",raw:r[0],text:n}}}}const V={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:bn,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};V._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/;V._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;V.def=_e(V.def).replace("label",V._label).replace("title",V._title).getRegex();V.bullet=/(?:[*+-]|\d{1,9}[.)])/;V.listItemStart=_e(/^( *)(bull) */).replace("bull",V.bullet).getRegex();V.list=_e(V.list).replace(/bull/g,V.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+V.def.source+")").getRegex();V._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";V._comment=/|$)/;V.html=_e(V.html,"i").replace("comment",V._comment).replace("tag",V._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();V.paragraph=_e(V._paragraph).replace("hr",V.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",V._tag).getRegex();V.blockquote=_e(V.blockquote).replace("paragraph",V.paragraph).getRegex();V.normal=nt({},V);V.gfm=nt({},V.normal,{table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"});V.gfm.table=_e(V.gfm.table).replace("hr",V.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",V._tag).getRegex();V.gfm.paragraph=_e(V._paragraph).replace("hr",V.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",V.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",V._tag).getRegex();V.pedantic=nt({},V.normal,{html:_e(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",V._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:bn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:_e(V.normal._paragraph).replace("hr",V.hr).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",V.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()});const j={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:bn,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:bn,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~";j.punctuation=_e(j.punctuation).replace(/punctuation/g,j._punctuation).getRegex();j.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;j.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g;j._comment=_e(V._comment).replace("(?:-->|$)","-->").getRegex();j.emStrong.lDelim=_e(j.emStrong.lDelim).replace(/punct/g,j._punctuation).getRegex();j.emStrong.rDelimAst=_e(j.emStrong.rDelimAst,"g").replace(/punct/g,j._punctuation).getRegex();j.emStrong.rDelimUnd=_e(j.emStrong.rDelimUnd,"g").replace(/punct/g,j._punctuation).getRegex();j._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;j._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;j._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;j.autolink=_e(j.autolink).replace("scheme",j._scheme).replace("email",j._email).getRegex();j._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;j.tag=_e(j.tag).replace("comment",j._comment).replace("attribute",j._attribute).getRegex();j._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;j._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;j._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;j.link=_e(j.link).replace("label",j._label).replace("href",j._href).replace("title",j._title).getRegex();j.reflink=_e(j.reflink).replace("label",j._label).replace("ref",V._label).getRegex();j.nolink=_e(j.nolink).replace("ref",V._label).getRegex();j.reflinkSearch=_e(j.reflinkSearch,"g").replace("reflink",j.reflink).replace("nolink",j.nolink).getRegex();j.normal=nt({},j);j.pedantic=nt({},j.normal,{strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:_e(/^!?\[(label)\]\((.*?)\)/).replace("label",j._label).getRegex(),reflink:_e(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",j._label).getRegex()});j.gfm=nt({},j.normal,{escape:_e(j.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\.5&&(r="x"+r.toString(16)),e+="&#"+r+";";return e}class lt{constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Vt,this.options.tokenizer=this.options.tokenizer||new Pr,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={block:V.normal,inline:j.normal};this.options.pedantic?(t.block=V.pedantic,t.inline=j.pedantic):this.options.gfm&&(t.block=V.gfm,this.options.breaks?t.inline=j.breaks:t.inline=j.gfm),this.tokenizer.rules=t}static get rules(){return{block:V,inline:j}}static lex(e,t){return new lt(t).lex(e)}static lexInline(e,t){return new lt(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,` +`),this.blockTokens(e,this.tokens);let t;for(;t=this.inlineQueue.shift();)this.inlineTokens(t.src,t.tokens);return this.tokens}blockTokens(e,t=[]){this.options.pedantic?e=e.replace(/\t/g," ").replace(/^ +$/gm,""):e=e.replace(/^( *)(\t+)/gm,(a,o,c)=>o+" ".repeat(c.length));let r,n,i,l;for(;e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(r=a.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))){if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length),r.raw.length===1&&t.length>0?t[t.length-1].raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=` +`+r.raw,n.text+=` +`+r.text,this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&(n.type==="paragraph"||n.type==="text")?(n.raw+=` +`+r.raw,n.text+=` +`+r.raw,this.inlineQueue[this.inlineQueue.length-1].src=n.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title});continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(i=e,this.options.extensions&&this.options.extensions.startBlock){let a=1/0;const o=e.slice(1);let c;this.options.extensions.startBlock.forEach(function(u){c=u.call({lexer:this},o),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(i=e.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){n=t[t.length-1],l&&n.type==="paragraph"?(n.raw+=` +`+r.raw,n.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r),l=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&n.type==="text"?(n.raw+=` +`+r.raw,n.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=n.text):t.push(r);continue}if(e){const a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let r,n,i,l=e,a,o,c;if(this.tokens.links){const u=Object.keys(this.tokens.links);if(u.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(l))!=null;)u.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(l=l.slice(0,a.index)+"["+Ys("a",a[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(l))!=null;)l=l.slice(0,a.index)+"["+Ys("a",a[0].length-2)+"]"+l.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(l))!=null;)l=l.slice(0,a.index+a[0].length-2)+"++"+l.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;e;)if(o||(c=""),o=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(u=>(r=u.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))){if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),n=t[t.length-1],n&&r.type==="text"&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length),n=t[t.length-1],n&&r.type==="text"&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,l,c)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e,Ks)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e,Ks))){e=e.substring(r.raw.length),t.push(r);continue}if(i=e,this.options.extensions&&this.options.extensions.startInline){let u=1/0;const f=e.slice(1);let d;this.options.extensions.startInline.forEach(function(h){d=h.call({lexer:this},f),typeof d=="number"&&d>=0&&(u=Math.min(u,d))}),u<1/0&&u>=0&&(i=e.substring(0,u+1))}if(r=this.tokenizer.inlineText(i,bc)){e=e.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(c=r.raw.slice(-1)),o=!0,n=t[t.length-1],n&&n.type==="text"?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){const u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}}class Tr{constructor(e){this.options=e||Vt}code(e,t,r){const n=(t||"").match(/\S*/)[0];if(this.options.highlight){const i=this.options.highlight(e,n);i!=null&&i!==e&&(r=!0,e=i)}return e=e.replace(/\n$/,"")+` +`,n?'
    '+(r?e:je(e,!0))+`
    +`:"
    "+(r?e:je(e,!0))+`
    +`}blockquote(e){return`
    +${e}
    +`}html(e){return e}heading(e,t,r,n){if(this.options.headerIds){const i=this.options.headerPrefix+n.slug(r);return`${e} +`}return`${e} +`}hr(){return this.options.xhtml?`
    +`:`
    +`}list(e,t,r){const n=t?"ol":"ul",i=t&&r!==1?' start="'+r+'"':"";return"<"+n+i+`> +`+e+" +`}listitem(e){return`
  • ${e}
  • +`}checkbox(e){return" "}paragraph(e){return`

    ${e}

    +`}table(e,t){return t&&(t=`${t}`),` + +`+e+` +`+t+`
    +`}tablerow(e){return` +${e} +`}tablecell(e,t){const r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+` +`}strong(e){return`${e}`}em(e){return`${e}`}codespan(e){return`${e}`}br(){return this.options.xhtml?"
    ":"
    "}del(e){return`${e}`}link(e,t,r){if(e=Gs(this.options.sanitize,this.options.baseUrl,e),e===null)return r;let n='",n}image(e,t,r){if(e=Gs(this.options.sanitize,this.options.baseUrl,e),e===null)return r;let n=`${r}":">",n}text(e){return e}}class Ni{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,r){return""+r}image(e,t,r){return""+r}br(){return""}}class $r{constructor(){this.seen={}}serialize(e){return e.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(e,t){let r=e,n=0;if(this.seen.hasOwnProperty(r)){n=this.seen[e];do n++,r=e+"-"+n;while(this.seen.hasOwnProperty(r))}return t||(this.seen[e]=n,this.seen[r]=0),r}slug(e,t={}){const r=this.serialize(e);return this.getNextSafeSlug(r,t.dryrun)}}class it{constructor(e){this.options=e||Vt,this.options.renderer=this.options.renderer||new Tr,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ni,this.slugger=new $r}static parse(e,t){return new it(t).parse(e)}static parseInline(e,t){return new it(t).parseInline(e)}parse(e,t=!0){let r="",n,i,l,a,o,c,u,f,d,h,_,m,w,v,E,P,O,F,C;const N=e.length;for(n=0;n0&&E.tokens[0].type==="paragraph"?(E.tokens[0].text=F+" "+E.tokens[0].text,E.tokens[0].tokens&&E.tokens[0].tokens.length>0&&E.tokens[0].tokens[0].type==="text"&&(E.tokens[0].tokens[0].text=F+" "+E.tokens[0].tokens[0].text)):E.tokens.unshift({type:"text",text:F}):v+=F),v+=this.parse(E.tokens,w),d+=this.renderer.listitem(v,O,P);r+=this.renderer.list(d,_,m);continue}case"html":{r+=this.renderer.html(h.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(h.tokens));continue}case"text":{for(d=h.tokens?this.parseInline(h.tokens):h.text;n+1"u"||s===null)throw new Error("marked(): input parameter is undefined or null");if(typeof s!="string")throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(s)+", string expected");if(typeof e=="function"&&(t=e,e=null),e=nt({},q.defaults,e||{}),Li(e),t){const n=e.highlight;let i;try{i=lt.lex(s,e)}catch(o){return t(o)}const l=function(o){let c;if(!o)try{e.walkTokens&&q.walkTokens(i,e.walkTokens),c=it.parse(i,e)}catch(u){o=u}return e.highlight=n,o?t(o):t(null,c)};if(!n||n.length<3||(delete e.highlight,!i.length))return l();let a=0;q.walkTokens(i,function(o){o.type==="code"&&(a++,setTimeout(()=>{n(o.text,o.lang,function(c,u){if(c)return l(c);u!=null&&u!==o.text&&(o.text=u,o.escaped=!0),a--,a===0&&l()})},0))}),a===0&&l();return}function r(n){if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+je(n.message+"",!0)+"
    ";throw n}try{const n=lt.lex(s,e);if(e.walkTokens){if(e.async)return Promise.all(q.walkTokens(n,e.walkTokens)).then(()=>it.parse(n,e)).catch(r);q.walkTokens(n,e.walkTokens)}return it.parse(n,e)}catch(n){r(n)}}q.options=q.setOptions=function(s){return nt(q.defaults,s),sc(q.defaults),q};q.getDefaults=Ui;q.defaults=Vt;q.use=function(...s){const e=q.defaults.extensions||{renderers:{},childTokens:{}};s.forEach(t=>{const r=nt({},t);if(r.async=q.defaults.async||r.async,t.extensions&&(t.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if(n.renderer){const i=e.renderers[n.name];i?e.renderers[n.name]=function(...l){let a=n.renderer.apply(this,l);return a===!1&&(a=i.apply(this,l)),a}:e.renderers[n.name]=n.renderer}if(n.tokenizer){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");e[n.level]?e[n.level].unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),r.extensions=e),t.renderer){const n=q.defaults.renderer||new Tr;for(const i in t.renderer){const l=n[i];n[i]=(...a)=>{let o=t.renderer[i].apply(n,a);return o===!1&&(o=l.apply(n,a)),o}}r.renderer=n}if(t.tokenizer){const n=q.defaults.tokenizer||new Pr;for(const i in t.tokenizer){const l=n[i];n[i]=(...a)=>{let o=t.tokenizer[i].apply(n,a);return o===!1&&(o=l.apply(n,a)),o}}r.tokenizer=n}if(t.walkTokens){const n=q.defaults.walkTokens;r.walkTokens=function(i){let l=[];return l.push(t.walkTokens.call(this,i)),n&&(l=l.concat(n.call(this,i))),l}}q.setOptions(r)})};q.walkTokens=function(s,e){let t=[];for(const r of s)switch(t=t.concat(e.call(q,r)),r.type){case"table":{for(const n of r.header)t=t.concat(q.walkTokens(n.tokens,e));for(const n of r.rows)for(const i of n)t=t.concat(q.walkTokens(i.tokens,e));break}case"list":{t=t.concat(q.walkTokens(r.items,e));break}default:q.defaults.extensions&&q.defaults.extensions.childTokens&&q.defaults.extensions.childTokens[r.type]?q.defaults.extensions.childTokens[r.type].forEach(function(n){t=t.concat(q.walkTokens(r[n],e))}):r.tokens&&(t=t.concat(q.walkTokens(r.tokens,e)))}return t};q.parseInline=function(s,e){if(typeof s>"u"||s===null)throw new Error("marked.parseInline(): input parameter is undefined or null");if(typeof s!="string")throw new Error("marked.parseInline(): input parameter is of type "+Object.prototype.toString.call(s)+", string expected");e=nt({},q.defaults,e||{}),Li(e);try{const t=lt.lexInline(s,e);return e.walkTokens&&q.walkTokens(t,e.walkTokens),it.parseInline(t,e)}catch(t){if(t.message+=` +Please report this to https://github.com/markedjs/marked.`,e.silent)return"

    An error occurred:

    "+je(t.message+"",!0)+"
    ";throw t}};q.Parser=it;q.parser=it.parse;q.Renderer=Tr;q.TextRenderer=Ni;q.Lexer=lt;q.lexer=lt.lex;q.Tokenizer=Pr;q.Slugger=$r;q.parse=q;q.options;q.setOptions;q.use;q.walkTokens;q.parseInline;it.parse;lt.lex;const qi={};function vc(s){let e;return{c(){e=ae(s[1])},m(t,r){k(t,e,r)},p(t,r){r&2&&Pe(e,t[1])},i:U,o:U,d(t){t&&y(e)}}}function wc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h6"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function yc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h5"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function kc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h4"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Oc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h3"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Sc(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h2"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Ac(s){let e,t;const r=s[5].default,n=de(r,s,s[4],null);return{c(){e=b("h1"),n&&n.c(),p(e,"id",s[2])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&16)&&pe(n,r,i,i[4],t?he(r,i[4],l,null):me(i[4]),null),(!t||l&4)&&p(e,"id",i[2])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Ec(s){let e,t,r,n;const i=[Ac,Sc,Oc,kc,yc,wc,vc],l=[];function a(o,c){return o[0]===1?0:o[0]===2?1:o[0]===3?2:o[0]===4?3:o[0]===5?4:o[0]===6?5:6}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function Pc(s,e,t){let r,{$$slots:n={},$$scope:i}=e,{depth:l}=e,{raw:a}=e,{text:o}=e;const{slug:c,getOptions:u}=ll(qi),f=u();return s.$$set=d=>{"depth"in d&&t(0,l=d.depth),"raw"in d&&t(1,a=d.raw),"text"in d&&t(3,o=d.text),"$$scope"in d&&t(4,i=d.$$scope)},s.$$.update=()=>{s.$$.dirty&8&&t(2,r=f.headerIds?f.headerPrefix+c(o):void 0)},[l,a,r,o,i,n]}class Tc extends ee{constructor(e){super(),X(this,e,Pc,Ec,Z,{depth:0,raw:1,text:3})}}function $c(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("p"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Cc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let Rc=class extends ee{constructor(e){super(),X(this,e,Cc,$c,Z,{})}};function xc(s){let e;const t=s[3].default,r=de(t,s,s[2],null);return{c(){r&&r.c()},m(n,i){r&&r.m(n,i),e=!0},p(n,[i]){r&&r.p&&(!e||i&4)&&pe(r,t,n,n[2],e?he(t,n[2],i,null):me(n[2]),null)},i(n){e||(S(r,n),e=!0)},o(n){A(r,n),e=!1},d(n){r&&r.d(n)}}}function Ic(s,e,t){let{$$slots:r={},$$scope:n}=e,{text:i}=e,{raw:l}=e;return s.$$set=a=>{"text"in a&&t(0,i=a.text),"raw"in a&&t(1,l=a.raw),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class jc extends ee{constructor(e){super(),X(this,e,Ic,xc,Z,{text:0,raw:1})}}function Fc(s){let e,t;return{c(){e=b("img"),Ae(e.src,t=s[0])||p(e,"src",t),p(e,"title",s[1]),p(e,"alt",s[2])},m(r,n){k(r,e,n)},p(r,[n]){n&1&&!Ae(e.src,t=r[0])&&p(e,"src",t),n&2&&p(e,"title",r[1]),n&4&&p(e,"alt",r[2])},i:U,o:U,d(r){r&&y(e)}}}function Mc(s,e,t){let{href:r=""}=e,{title:n=void 0}=e,{text:i=""}=e;return s.$$set=l=>{"href"in l&&t(0,r=l.href),"title"in l&&t(1,n=l.title),"text"in l&&t(2,i=l.text)},[r,n,i]}class Uc extends ee{constructor(e){super(),X(this,e,Mc,Fc,Z,{href:0,title:1,text:2})}}function Bc(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("a"),n&&n.c(),p(e,"href",s[0]),p(e,"title",s[1])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&1)&&p(e,"href",i[0]),(!t||l&2)&&p(e,"title",i[1])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Vc(s,e,t){let{$$slots:r={},$$scope:n}=e,{href:i=""}=e,{title:l=void 0}=e;return s.$$set=a=>{"href"in a&&t(0,i=a.href),"title"in a&&t(1,l=a.title),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class Dc extends ee{constructor(e){super(),X(this,e,Vc,Bc,Z,{href:0,title:1})}}function Lc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("em"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Nc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let qc=class extends ee{constructor(e){super(),X(this,e,Nc,Lc,Z,{})}};function zc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("del"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Hc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Jc extends ee{constructor(e){super(),X(this,e,Hc,zc,Z,{})}}function Gc(s){let e,t=s[0].replace(/`/g,"")+"",r;return{c(){e=b("code"),r=ae(t)},m(n,i){k(n,e,i),g(e,r)},p(n,[i]){i&1&&t!==(t=n[0].replace(/`/g,"")+"")&&Pe(r,t)},i:U,o:U,d(n){n&&y(e)}}}function Qc(s,e,t){let{raw:r}=e;return s.$$set=n=>{"raw"in n&&t(0,r=n.raw)},[r]}class Yc extends ee{constructor(e){super(),X(this,e,Qc,Gc,Z,{raw:0})}}function Wc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("strong"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Kc(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Zc extends ee{constructor(e){super(),X(this,e,Kc,Wc,Z,{})}}function Xc(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("table"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function eu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class tu extends ee{constructor(e){super(),X(this,e,eu,Xc,Z,{})}}function nu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("thead"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function ru(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class su extends ee{constructor(e){super(),X(this,e,ru,nu,Z,{})}}function iu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("tbody"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function lu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class ou extends ee{constructor(e){super(),X(this,e,lu,iu,Z,{})}}function au(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("tr"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function cu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class uu extends ee{constructor(e){super(),X(this,e,cu,au,Z,{})}}function fu(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("td"),n&&n.c(),p(e,"align",s[1])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"align",i[1])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function du(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("th"),n&&n.c(),p(e,"align",s[1])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"align",i[1])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function hu(s){let e,t,r,n;const i=[du,fu],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function pu(s,e,t){let{$$slots:r={},$$scope:n}=e,{header:i}=e,{align:l}=e;return s.$$set=a=>{"header"in a&&t(0,i=a.header),"align"in a&&t(1,l=a.align),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class mu extends ee{constructor(e){super(),X(this,e,pu,hu,Z,{header:0,align:1})}}function gu(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ul"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function _u(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ol"),n&&n.c(),p(e,"start",s[1])},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"start",i[1])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function bu(s){let e,t,r,n;const i=[_u,gu],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function vu(s,e,t){let{$$slots:r={},$$scope:n}=e,{ordered:i}=e,{start:l}=e;return s.$$set=a=>{"ordered"in a&&t(0,i=a.ordered),"start"in a&&t(1,l=a.start),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class wu extends ee{constructor(e){super(),X(this,e,vu,bu,Z,{ordered:0,start:1})}}function yu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("li"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function ku(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}let Ou=class extends ee{constructor(e){super(),X(this,e,ku,yu,Z,{})}};function Su(s){let e;return{c(){e=b("hr")},m(t,r){k(t,e,r)},p:U,i:U,o:U,d(t){t&&y(e)}}}class Au extends ee{constructor(e){super(),X(this,e,null,Su,Z,{})}}function Eu(s){let e,t;return{c(){e=new nl(!1),t=ge(),e.a=t},m(r,n){e.m(s[0],r,n),k(r,t,n)},p(r,[n]){n&1&&e.p(r[0])},i:U,o:U,d(r){r&&y(t),r&&e.d()}}}function Pu(s,e,t){let{text:r}=e;return s.$$set=n=>{"text"in n&&t(0,r=n.text)},[r]}let Tu=class extends ee{constructor(e){super(),X(this,e,Pu,Eu,Z,{text:0})}};function $u(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("blockquote"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Cu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Ru extends ee{constructor(e){super(),X(this,e,Cu,$u,Z,{})}}function xu(s){let e,t,r;return{c(){e=b("pre"),t=b("code"),r=ae(s[1]),p(e,"class",s[0])},m(n,i){k(n,e,i),g(e,t),g(t,r)},p(n,[i]){i&2&&Pe(r,n[1]),i&1&&p(e,"class",n[0])},i:U,o:U,d(n){n&&y(e)}}}function Iu(s,e,t){let{lang:r}=e,{text:n}=e;return s.$$set=i=>{"lang"in i&&t(0,r=i.lang),"text"in i&&t(1,n=i.text)},[r,n]}let ju=class extends ee{constructor(e){super(),X(this,e,Iu,xu,Z,{lang:0,text:1})}};function Fu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("br"),n&&n.c()},m(i,l){k(i,e,l),n&&n.m(i,l),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Mu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Uu extends ee{constructor(e){super(),X(this,e,Mu,Fu,Z,{})}}const Bu={heading:Tc,paragraph:Rc,text:jc,image:Uc,link:Dc,em:qc,strong:Zc,codespan:Yc,del:Jc,table:tu,tablehead:su,tablebody:ou,tablerow:uu,tablecell:mu,list:wu,orderedlistitem:null,unorderedlistitem:null,listitem:Ou,hr:Au,html:Tu,blockquote:Ru,code:ju,br:Uu},Vu={baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tokenizer:null,xhtml:!1};function Du(s){let e,t;return e=new St({props:{tokens:s[0],renderers:s[1]}}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p(r,[n]){const i={};n&1&&(i.tokens=r[0]),n&2&&(i.renderers=r[1]),e.$set(i)},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function Lu(s,e,t){let r,n,i,l,{source:a=[]}=e,{renderers:o={}}=e,{options:c={}}=e,{isInline:u=!1}=e;const f=wn();let d,h,_;return il(qi,{slug:m=>n?n.slug(m):"",getOptions:()=>i}),vn(()=>{t(7,_=!0)}),s.$$set=m=>{"source"in m&&t(2,a=m.source),"renderers"in m&&t(3,o=m.renderers),"options"in m&&t(4,c=m.options),"isInline"in m&&t(5,u=m.isInline)},s.$$.update=()=>{s.$$.dirty&4&&t(8,r=Array.isArray(a)),s.$$.dirty&4&&(n=a?new $r:void 0),s.$$.dirty&16&&t(9,i={...Vu,...c}),s.$$.dirty&869&&(r?t(0,d=a):(t(6,h=new lt(i)),t(0,d=u?h.inlineTokens(a):h.lex(a)),f("parsed",{tokens:d}))),s.$$.dirty&8&&t(1,l={...Bu,...o}),s.$$.dirty&385&&_&&!r&&f("parsed",{tokens:d})},[d,l,a,o,c,u,h,_,r,i]}class zi extends ee{constructor(e){super(),X(this,e,Lu,Du,Z,{source:2,renderers:3,options:4,isInline:5})}}function Nu(s){let e,t,r,n,i,l,a,o,c;return{c(){e=b("div"),t=b("div"),r=b("button"),r.textContent="Copy code",n=$(),i=b("pre"),l=b("code"),a=ae(s[0]),p(r,"class","svelte-hssbda"),p(t,"class","copycode svelte-hssbda"),p(i,"class","svelte-hssbda"),rt(e,"position","relative")},m(u,f){k(u,e,f),g(e,t),g(t,r),g(e,n),g(e,i),g(i,l),g(l,a),o||(c=L(r,"click",s[1]),o=!0)},p(u,[f]){f&1&&Pe(a,u[0])},i:U,o:U,d(u){u&&y(e),o=!1,c()}}}function qu(s,e,t){let{text:r}=e;const n=async()=>{try{await navigator.clipboard.writeText(r)}catch(i){console.error("Error copying text: ",i)}};return s.$$set=i=>{"text"in i&&t(0,r=i.text)},[r,n]}class zu extends ee{constructor(e){super(),X(this,e,qu,Nu,Z,{text:0})}}function Hu(s){let e,t;return{c(){e=b("div"),t=ae(s[0]),rt(e,"position","relative")},m(r,n){k(r,e,n),g(e,t)},p(r,[n]){n&1&&Pe(t,r[0])},i:U,o:U,d(r){r&&y(e)}}}function Ju(s,e,t){let{text:r}=e;return s.$$set=n=>{"text"in n&&t(0,r=n.text)},[r]}class Gu extends ee{constructor(e){super(),X(this,e,Ju,Hu,Z,{text:0})}}function Qu(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("em"),n&&n.c(),p(e,"class","svelte-djznuz")},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Yu(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Hi extends ee{constructor(e){super(),X(this,e,Yu,Qu,Z,{})}}function Wu(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ul"),n&&n.c(),p(e,"class","svelte-1dicnom")},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Ku(s){let e,t;const r=s[3].default,n=de(r,s,s[2],null);return{c(){e=b("ol"),n&&n.c(),p(e,"start",s[1]),p(e,"class","svelte-1dicnom")},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,l){n&&n.p&&(!t||l&4)&&pe(n,r,i,i[2],t?he(r,i[2],l,null):me(i[2]),null),(!t||l&2)&&p(e,"start",i[1])},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function Zu(s){let e,t,r,n;const i=[Ku,Wu],l=[];function a(o,c){return o[0]?0:1}return e=a(s),t=l[e]=i[e](s),{c(){t.c(),r=ge()},m(o,c){l[e].m(o,c),k(o,r,c),n=!0},p(o,[c]){let u=e;e=a(o),e===u?l[e].p(o,c):(ie(),A(l[u],1,1,()=>{l[u]=null}),le(),t=l[e],t?t.p(o,c):(t=l[e]=i[e](o),t.c()),S(t,1),t.m(r.parentNode,r))},i(o){n||(S(t),n=!0)},o(o){A(t),n=!1},d(o){l[e].d(o),o&&y(r)}}}function Xu(s,e,t){let{$$slots:r={},$$scope:n}=e,{ordered:i}=e,{start:l}=e;return s.$$set=a=>{"ordered"in a&&t(0,i=a.ordered),"start"in a&&t(1,l=a.start),"$$scope"in a&&t(2,n=a.$$scope)},[i,l,n,r]}class Ji extends ee{constructor(e){super(),X(this,e,Xu,Zu,Z,{ordered:0,start:1})}}function ef(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("li"),n&&n.c(),p(e,"class","svelte-fm7yqp")},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function tf(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Gi extends ee{constructor(e){super(),X(this,e,tf,ef,Z,{})}}function nf(s){let e,t=s[0].replace(/`/g,"")+"",r;return{c(){e=b("code"),r=ae(t),p(e,"class","svelte-we39e")},m(n,i){k(n,e,i),g(e,r)},p(n,[i]){i&1&&t!==(t=n[0].replace(/`/g,"")+"")&&Pe(r,t)},i:U,o:U,d(n){n&&y(e)}}}function rf(s,e,t){let{raw:r}=e;return s.$$set=n=>{"raw"in n&&t(0,r=n.raw)},[r]}class sf extends ee{constructor(e){super(),X(this,e,rf,nf,Z,{raw:0})}}function lf(s){let e,t;const r=s[1].default,n=de(r,s,s[0],null);return{c(){e=b("p"),n&&n.c(),p(e,"class","svelte-jw73bw")},m(i,l){k(i,e,l),n&&n.m(e,null),t=!0},p(i,[l]){n&&n.p&&(!t||l&1)&&pe(n,r,i,i[0],t?he(r,i[0],l,null):me(i[0]),null)},i(i){t||(S(n,i),t=!0)},o(i){A(n,i),t=!1},d(i){i&&y(e),n&&n.d(i)}}}function of(s,e,t){let{$$slots:r={},$$scope:n}=e;return s.$$set=i=>{"$$scope"in i&&t(0,n=i.$$scope)},[n,r]}class Qi extends ee{constructor(e){super(),X(this,e,of,lf,Z,{})}}function af(s){let e;return{c(){e=ae(s[0])},m(t,r){k(t,e,r)},p(t,[r]){r&1&&Pe(e,t[0])},i:U,o:U,d(t){t&&y(e)}}}function cf(s,e,t){let{text:r}=e;return s.$$set=n=>{"text"in n&&t(0,r=n.text)},[r]}class Yi extends ee{constructor(e){super(),X(this,e,cf,af,Z,{text:0})}}const uf="/assets/delete-f3f148b5.svg",ff="/assets/CopyIcon-6270aedf.svg",Zs="/assets/UserIcon-57b535eb.svg",Xs="/assets/RobotIcon-76293781.svg",df="/assets/send-8e88dbd9.svg",hf="/assets/wait-8f30b8f8.svg",pf="/assets/upload-icon-8c25e619.svg",mf="/assets/pdf-icon-d4c18e5d.svg",gf="modulepreload",_f=function(s){return"/"+s},ei={},bf=function(e,t,r){if(!t||t.length===0)return e();const n=document.getElementsByTagName("link");return Promise.all(t.map(i=>{if(i=_f(i),i in ei)return;ei[i]=!0;const l=i.endsWith(".css"),a=l?'[rel="stylesheet"]':"";if(!!r)for(let u=n.length-1;u>=0;u--){const f=n[u];if(f.href===i&&(!l||f.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${i}"]${a}`))return;const c=document.createElement("link");if(c.rel=l?"stylesheet":gf,l||(c.as="script",c.crossOrigin=""),c.href=i,document.head.appendChild(c),l)return new Promise((u,f)=>{c.addEventListener("load",u),c.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${i}`)))})})).then(()=>e())};async function vf(){const s=await bf(()=>import("./pdf-ea9598b5.js"),[]);return s.GlobalWorkerOptions.workerSrc="/workers/pdf.worker.min.mjs",s}function wf(s){const t=/^D:(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(s);if(t){const r=parseInt(t[1],10),n=parseInt(t[2],10)-1,i=parseInt(t[3],10),l=parseInt(t[4],10),a=parseInt(t[5],10),o=parseInt(t[6],10);return new Date(r,n,i,l,a,o).toISOString().split("T")[0]}return"Unknown Date"}async function yf(s){try{const e=new FileReader,t=await vf();return new Promise((r,n)=>{e.onload=async i=>{const l=new Uint8Array(i.target.result),o=await t.getDocument({data:l}).promise,c=o.numPages;let u="";for(let E=1;E<=c;E++){const O=await(await o.getPage(E)).getTextContent();u+=O.items.map(F=>"str"in F?F.str:"").join(" ")}const f=u.split(/\s+/).length,h=(await o.getMetadata()).info,_=s.name,m=h.Title||"Untitled",w=h.Author||"Unknown Author",v=h.CreationDate?wf(h.CreationDate):"Unknown Date";r(`The user uploaded a PDF titled "${m}" with a file name of "${_}". It has ${c} pages and ${f} words. File metadata includes Author: "${w}" and creation date: ${v}. The extracted text is as follows: ${u}`)},e.onerror=n,e.readAsArrayBuffer(s)})}catch(e){return console.error("Error processing PDF:",e),Promise.reject("Failed to load the PDF file.")}}function ti(s,e,t){const r=s.slice();return r[53]=e[t],r[55]=t,r}function kf(s){let e;return{c(){e=ae("SmoothGPT")},m(t,r){k(t,e,r)},p:U,d(t){t&&y(e)}}}function Of(s){let e=(s[3][s[2]].title||"SmoothGPT")+"",t;return{c(){t=ae(e)},m(r,n){k(r,t,n)},p(r,n){n[0]&12&&e!==(e=(r[3][r[2]].title||"SmoothGPT")+"")&&Pe(t,e)},d(r){r&&y(t)}}}function ni(s){let e,t;return e=new Ca({}),e.$on("settings-changed",ra),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p:U,i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function ri(s){let e,t;return e=new Ia({}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function Sf(s){let e;return{c(){e=b("div"),e.innerHTML="

    No conversation selected. Start a new conversation.

    ",p(e,"class","flex justify-center items-center h-full")},m(t,r){k(t,e,r)},p:U,i:U,o:U,d(t){t&&y(e)}}}function Af(s){let e,t,r,n=s[3][s[2]].history,i=[];for(let a=0;aA(i[a],1,1,()=>{i[a]=null});return{c(){e=b("div"),t=b("div");for(let a=0;a{v[F]=null}),le(),u=v[c],u?u.p(P,O):(u=v[c]=w[c](P),u.c()),S(u,1),u.m(e,f))},i(P){d||(S(u),d=!0)},o(P){A(u),d=!1},d(P){P&&y(e),m.d(),v[c].d()}}}function Ef(s){let e;return{c(){e=ae("You")},m(t,r){k(t,e,r)},d(t){t&&y(e)}}}function Pf(s){let e;return{c(){e=ae("ChatGPT")},m(t,r){k(t,e,r)},d(t){t&&y(e)}}}function Tf(s){let e,t,r,n,i,l,a,o,c;const u=[If,xf,Rf,Cf],f=[];function d(m,w){return w[0]&12&&(t=null),w[0]&12&&(r=null),t==null&&(t=!!gr(m[53].content)),t?0:(r==null&&(r=!!ar(m[53])),r?1:m[53].role==="assistant"?2:3)}n=d(s,[-1,-1]),i=f[n]=u[n](s);let h=s[53].role==="assistant"&&ii(s),_=s[53].role==="user"&&oi(s);return{c(){e=b("div"),i.c(),l=$(),a=b("div"),h&&h.c(),o=$(),_&&_.c(),p(e,"class","message-display px-20 text-[1rem]"),p(a,"class","toolbelt flex space-x-2 pl-20 mb-2 tools")},m(m,w){k(m,e,w),f[n].m(e,null),k(m,l,w),k(m,a,w),h&&h.m(a,null),g(a,o),_&&_.m(a,null),c=!0},p(m,w){let v=n;n=d(m,w),n===v?f[n].p(m,w):(ie(),A(f[v],1,1,()=>{f[v]=null}),le(),i=f[n],i?i.p(m,w):(i=f[n]=u[n](m),i.c()),S(i,1),i.m(e,null)),m[53].role==="assistant"?h?h.p(m,w):(h=ii(m),h.c(),h.m(a,o)):h&&(h.d(1),h=null),m[53].role==="user"?_?_.p(m,w):(_=oi(m),_.c(),_.m(a,null)):_&&(_.d(1),_=null)},i(m){c||(S(i),c=!0)},o(m){A(i),c=!1},d(m){m&&y(e),f[n].d(),m&&y(l),m&&y(a),h&&h.d(),_&&_.d()}}}function $f(s){let e,t,r,n,i,l,a,o,c,u;function f(){return s[34](s[55])}return{c(){e=b("textarea"),t=$(),r=b("div"),n=b("button"),i=ae("Submit"),a=$(),o=b("button"),o.textContent="Cancel",p(e,"class","message-edit-textarea mt-2 bg-gray-700 p-3 mx-10 resize-none focus:outline-none rounded-lg"),rt(e,"height","96px"),rt(e,"overflow-y","auto"),p(n,"class",l="submit-edit rounded-lg p-2 mr-2 "+(s[18]?"bg-gray-500 cursor-not-allowed hover:bg-gray-500":"hover:bg-green-500 bg-green-700")),n.disabled=s[18],p(o,"class","cancel-edit bg-gray-700 hover:bg-gray-500 rounded-lg p-2 mr-2"),p(r,"class","flex place-content-center mt-4")},m(d,h){k(d,e,h),s[32](e),Xe(e,s[10]),k(d,t,h),k(d,r,h),g(r,n),g(n,i),g(r,a),g(r,o),c||(u=[L(e,"input",s[33]),L(e,"input",Wi),L(n,"click",f),L(o,"click",s[35])],c=!0)},p(d,h){s=d,h[0]&1024&&Xe(e,s[10]),h[0]&262144&&l!==(l="submit-edit rounded-lg p-2 mr-2 "+(s[18]?"bg-gray-500 cursor-not-allowed hover:bg-gray-500":"hover:bg-green-500 bg-green-700"))&&p(n,"class",l),h[0]&262144&&(n.disabled=s[18])},i:U,o:U,d(d){d&&y(e),s[32](null),d&&y(t),d&&y(r),c=!1,Ne(u)}}}function Cf(s){let e,t;return e=new zi({props:{renderers:{code:Gu,codespan:sf,em:Hi,list:Ji,listitem:Gi,paragraph:Qi,html:Yi},source:gn(s[53].content.toString())}}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p(r,n){const i={};n[0]&12&&(i.source=gn(r[53].content.toString())),e.$set(i)},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function Rf(s){let e,t;return e=new zi({props:{renderers:{code:zu,em:Hi,list:Ji,listitem:Gi,paragraph:Qi,html:Yi},source:gn(s[53].content.toString())}}),{c(){K(e.$$.fragment)},m(r,n){Y(e,r,n),t=!0},p(r,n){const i={};n[0]&12&&(i.source=gn(r[53].content.toString())),e.$set(i)},i(r){t||(S(e.$$.fragment,r),t=!0)},o(r){A(e.$$.fragment,r),t=!1},d(r){W(e,r)}}}function xf(s){let e,t,r;return t=new pa({props:{audioUrl:s[53].audioUrl}}),{c(){e=b("div"),K(t.$$.fragment),p(e,"class","pb-3")},m(n,i){k(n,e,i),Y(t,e,null),r=!0},p(n,i){const l={};i[0]&12&&(l.audioUrl=n[53].audioUrl),t.$set(l)},i(n){r||(S(t.$$.fragment,n),r=!0)},o(n){A(t.$$.fragment,n),r=!1},d(n){n&&y(e),W(t)}}}function If(s){let e,t,r,n;return{c(){e=b("img"),r=$(),n=b("div"),n.textContent="This image will be available for 60 minutes. Right click + save as!",Ae(e.src,t=s[53].content)||p(e,"src",t),p(e,"alt","Generated"),p(e,"class","max-w-full h-auto my-3"),p(n,"class","text-sm text-gray-500")},m(i,l){k(i,e,l),k(i,r,l),k(i,n,l)},p(i,l){l[0]&12&&!Ae(e.src,t=i[53].content)&&p(e,"src",t)},i:U,o:U,d(i){i&&y(e),i&&y(r),i&&y(n)}}}function ii(s){let e=!ar(s[53])&&!gr(s[53].content),t,r,n,i,l,a,o=e&&li(s);function c(){return s[37](s[55])}return{c(){o&&o.c(),t=$(),r=b("button"),n=b("img"),p(n,"class","delete-icon"),p(n,"alt","Delete"),Ae(n.src,i=uf)||p(n,"src",i),p(r,"class","deleteButton w-5")},m(u,f){o&&o.m(u,f),k(u,t,f),k(u,r,f),g(r,n),l||(a=L(r,"click",c),l=!0)},p(u,f){s=u,f[0]&12&&(e=!ar(s[53])&&!gr(s[53].content)),e?o?o.p(s,f):(o=li(s),o.c(),o.m(t.parentNode,t)):o&&(o.d(1),o=null)},d(u){o&&o.d(u),u&&y(t),u&&y(r),l=!1,a()}}}function li(s){let e,t,r,n,i;function l(){return s[36](s[53])}return{c(){e=b("button"),t=b("img"),p(t,"class","copy-icon"),p(t,"alt","Copy"),Ae(t.src,r=ff)||p(t,"src",r),p(e,"class","copyButton w-5")},m(a,o){k(a,e,o),g(e,t),n||(i=L(e,"click",l),n=!0)},p(a,o){s=a},d(a){a&&y(e),n=!1,i()}}}function oi(s){let e,t,r,n,i;function l(){return s[38](s[55])}return{c(){e=b("button"),t=b("img"),p(t,"class","edit-icon"),p(t,"alt","edit"),Ae(t.src,r=Mi)||p(t,"src",r),p(e,"class","editButton w-5")},m(a,o){k(a,e,o),g(e,t),n||(i=L(e,"click",l),n=!0)},p(a,o){s=a},d(a){a&&y(e),n=!1,i()}}}function ai(s){let e,t,r=s[53].role!=="system"&&si(s);return{c(){r&&r.c(),e=ge()},m(n,i){r&&r.m(n,i),k(n,e,i),t=!0},p(n,i){n[53].role!=="system"?r?(r.p(n,i),i[0]&12&&S(r,1)):(r=si(n),r.c(),S(r,1),r.m(e.parentNode,e)):r&&(ie(),A(r,1,1,()=>{r=null}),le())},i(n){t||(S(r),t=!0)},o(n){A(r),t=!1},d(n){r&&r.d(n),n&&y(e)}}}function jf(s){let e,t,r,n,i,l,a;function o(d,h){return d[12]===0?Uf:Mf}let c=o(s),u=c(s),f=s[12]>0&&ci(s);return{c(){e=b("input"),t=$(),r=b("label"),u.c(),n=$(),f&&f.c(),i=ge(),p(e,"type","file"),p(e,"id","pdfUpload"),p(e,"accept","application/pdf"),p(e,"class","file-input"),p(r,"for","pdfUpload"),p(r,"class","file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors")},m(d,h){k(d,e,h),s[42](e),k(d,t,h),k(d,r,h),u.m(r,null),k(d,n,h),f&&f.m(d,h),k(d,i,h),l||(a=L(e,"change",s[41]),l=!0)},p(d,h){c===(c=o(d))&&u?u.p(d,h):(u.d(1),u=c(d),u&&(u.c(),u.m(r,null))),d[12]>0?f?f.p(d,h):(f=ci(d),f.c(),f.m(i.parentNode,i)):f&&(f.d(1),f=null)},d(d){d&&y(e),s[42](null),d&&y(t),d&&y(r),u.d(),d&&y(n),f&&f.d(d),d&&y(i),l=!1,a()}}}function Ff(s){let e,t,r,n,i,l,a;function o(d,h){return d[11]>0?Vf:Bf}let c=o(s),u=c(s),f=s[11]>0&&ui(s);return{c(){e=b("input"),t=$(),r=b("label"),u.c(),n=$(),f&&f.c(),i=ge(),p(e,"type","file"),p(e,"id","imageUpload"),e.multiple=!0,p(e,"accept","image/*"),p(e,"class","file-input"),p(r,"for","imageUpload"),p(r,"class","file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors")},m(d,h){k(d,e,h),s[40](e),k(d,t,h),k(d,r,h),u.m(r,null),k(d,n,h),f&&f.m(d,h),k(d,i,h),l||(a=L(e,"change",ea),l=!0)},p(d,h){c===(c=o(d))&&u?u.p(d,h):(u.d(1),u=c(d),u&&(u.c(),u.m(r,null))),d[11]>0?f?f.p(d,h):(f=ui(d),f.c(),f.m(i.parentNode,i)):f&&(f.d(1),f=null)},d(d){d&&y(e),s[40](null),d&&y(t),d&&y(r),u.d(),d&&y(n),f&&f.d(d),d&&y(i),l=!1,a()}}}function Mf(s){let e,t;return{c(){e=b("span"),t=ae(s[12]),p(e,"class","fileCount")},m(r,n){k(r,e,n),g(e,t)},p(r,n){n[0]&4096&&Pe(t,r[12])},d(r){r&&y(e)}}}function Uf(s){let e,t;return{c(){e=b("img"),Ae(e.src,t=mf)||p(e,"src",t),p(e,"alt","PDF"),p(e,"class","pdf-icon icon-white")},m(r,n){k(r,e,n)},p:U,d(r){r&&y(e)}}}function ci(s){let e,t,r;return{c(){e=b("button"),e.textContent="X",p(e,"class","clear-btn px-4 rounded-lg bg-red-700 mx-2 hover:bg-red-500")},m(n,i){k(n,e,i),t||(r=L(e,"click",s[20]),t=!0)},p:U,d(n){n&&y(e),t=!1,r()}}}function Bf(s){let e,t;return{c(){e=b("img"),Ae(e.src,t=pf)||p(e,"src",t),p(e,"alt","Upload"),p(e,"class","upload-icon icon-white")},m(r,n){k(r,e,n)},p:U,d(r){r&&y(e)}}}function Vf(s){let e,t;return{c(){e=b("span"),t=ae(s[11]),p(e,"class","fileCount")},m(r,n){k(r,e,n),g(e,t)},p(r,n){n[0]&2048&&Pe(t,r[11])},d(r){r&&y(e)}}}function ui(s){let e,t,r;return{c(){e=b("button"),e.textContent="X",p(e,"class","clear-btn")},m(n,i){k(n,e,i),t||(r=L(e,"click",s[20]),t=!0)},p:U,d(n){n&&y(e),t=!1,r()}}}function Df(s){let e,t;return{c(){e=b("img"),p(e,"class","icon-white min-w-[24px] w-[24px]"),p(e,"alt","Send"),Ae(e.src,t=df)||p(e,"src",t)},m(r,n){k(r,e,n)},p:U,d(r){r&&y(e)}}}function Lf(s){let e,t;return{c(){e=b("img"),p(e,"class","icon-white min-w-[24px] w-[24px]"),p(e,"alt","Wait"),Ae(e.src,t=hf)||p(e,"src",t)},m(r,n){k(r,e,n)},p:U,d(r){r&&y(e)}}}function Nf(s){let e,t,r,n,i,l,a,o,c,u,f,d,h,_,m,w,v,E,P,O,F,C,N,ce,G,ne,oe,se,Oe,Te,ve,Ee,R;function D(x,ue){return x[3].length>0&&x[3][x[2]]?Of:kf}let z=D(s),B=z(s),J=s[15]&&ni(),H=s[16]&&ri();l=new Pa({}),l.$on("new-chat",s[30]);function Ce(x){s[31](x)}let Be={};s[8]!==void 0&&(Be.conversation_title=s[8]),c=new va({props:Be}),ut.push(()=>fl(c,"conversation_title",Ce)),c.$on("new-chat",Ri);const Ke=[Af,Sf],Ve=[];function M(x,ue){return x[3].length>0&&x[3][x[2]]?0:1}P=M(s),O=Ve[P]=Ke[P](s);function Se(x,ue){if(x[14])return Ff;if(x[13])return jf}let be=Se(s),Q=be&&be(s);function Qe(x,ue){return x[18]?Lf:Df}let De=Qe(s),Le=De(s);return{c(){e=b("title"),B.c(),t=$(),J&&J.c(),r=$(),H&&H.c(),n=$(),i=b("main"),K(l.$$.fragment),a=$(),o=b("div"),K(c.$$.fragment),f=$(),d=b("div"),h=b("div"),_=ae("Current Model: "),m=b("span"),w=ae(s[17]),v=$(),E=b("div"),O.c(),F=$(),C=b("div"),N=b("div"),Q&&Q.c(),ce=$(),G=b("textarea"),ne=$(),oe=b("button"),Le.c(),Oe=$(),Te=b("div"),Te.innerHTML='
    ',p(m,"class","font-normal"),p(h,"class","font-bold text-l"),p(d,"class","py-5 bg-primary px-5 flex flex-row justify-between flex-wrap-reverse"),p(E,"class","flex bg-primary overflow-y-auto overflow-x-hidden justify-center grow"),p(G,"class","w-full min-h-[96px] h-24 rounded-lg p-2 mx-1 mr-0 border-t-2 border-b-2 border-l-2 rounded-r-none bg-primary border-gray-500 resize-none focus:outline-none"),p(G,"placeholder","Type your message..."),rt(G,"height","96px"),rt(G,"overflow-y","auto"),rt(G,"overflow","visible",1),p(oe,"class","bg-chat rounded-lg py-2 px-4 mx-1 ml-0 border-t-2 border-b-2 border-r-2 border-gray-500 rounded-l-none cursor-pointer "),oe.disabled=se=!s[18]&&!s[4].trim().length,p(N,"class","inputbox flex flex-1 bg-primary mt-auto mx-auto max-w-3xl mb-3"),p(C,"class","inputbox-container w-full flex justify-center items-center bg-primary"),p(Te,"class","flex justify-center bg-primary px-4"),p(o,"class","h-screen flex justify-stretch flex-col md:ml-[260px] bg-secondary text-white/80 height-manager"),p(i,"class","bg-primary overflow-hidden")},m(x,ue){k(x,e,ue),B.m(e,null),k(x,t,ue),J&&J.m(x,ue),k(x,r,ue),H&&H.m(x,ue),k(x,n,ue),k(x,i,ue),Y(l,i,null),g(i,a),g(i,o),Y(c,o,null),g(o,f),g(o,d),g(d,h),g(h,_),g(h,m),g(m,w),g(o,v),g(o,E),Ve[P].m(E,null),s[39](E),g(o,F),g(o,C),g(C,N),Q&&Q.m(N,null),g(N,ce),g(N,G),s[43](G),Xe(G,s[4]),g(N,ne),g(N,oe),Le.m(oe,null),g(o,Oe),g(o,Te),ve=!0,Ee||(R=[L(G,"input",s[44]),L(G,"input",Wi),L(G,"keydown",s[45]),L(oe,"click",s[46])],Ee=!0)},p(x,ue){z===(z=D(x))&&B?B.p(x,ue):(B.d(1),B=z(x),B&&(B.c(),B.m(e,null))),x[15]?J?(J.p(x,ue),ue[0]&32768&&S(J,1)):(J=ni(),J.c(),S(J,1),J.m(r.parentNode,r)):J&&(ie(),A(J,1,1,()=>{J=null}),le()),x[16]?H?ue[0]&65536&&S(H,1):(H=ri(),H.c(),S(H,1),H.m(n.parentNode,n)):H&&(ie(),A(H,1,1,()=>{H=null}),le());const et={};!u&&ue[0]&256&&(u=!0,et.conversation_title=x[8],cl(()=>u=!1)),c.$set(et),(!ve||ue[0]&131072)&&Pe(w,x[17]);let Fe=P;P=M(x),P===Fe?Ve[P].p(x,ue):(ie(),A(Ve[Fe],1,1,()=>{Ve[Fe]=null}),le(),O=Ve[P],O?O.p(x,ue):(O=Ve[P]=Ke[P](x),O.c()),S(O,1),O.m(E,null)),be===(be=Se(x))&&Q?Q.p(x,ue):(Q&&Q.d(1),Q=be&&be(x),Q&&(Q.c(),Q.m(N,ce))),ue[0]&16&&Xe(G,x[4]),De===(De=Qe(x))&&Le?Le.p(x,ue):(Le.d(1),Le=De(x),Le&&(Le.c(),Le.m(oe,null))),(!ve||ue[0]&262160&&se!==(se=!x[18]&&!x[4].trim().length))&&(oe.disabled=se)},i(x){ve||(S(J),S(H),S(l.$$.fragment,x),S(c.$$.fragment,x),S(O),ve=!0)},o(x){A(J),A(H),A(l.$$.fragment,x),A(c.$$.fragment,x),A(O),ve=!1},d(x){x&&y(e),B.d(),x&&y(t),J&&J.d(x),x&&y(r),H&&H.d(x),x&&y(n),x&&y(i),W(l),W(c),Ve[P].d(),s[39](null),Q&&Q.d(),s[43](null),Le.d(),Ee=!1,Ne(R)}}}const qf=300;function Wi(s){s.target.style.height="inherit";const e=window.getComputedStyle(s.target),t=parseInt(e.getPropertyValue("border-top-width"),10)+s.target.scrollHeight+parseInt(e.getPropertyValue("border-bottom-width"),10);s.target.style.height=`${Math.min(t,qf)}px`}function gr(s){return!/\s/.test(s)&&s.includes("blob.core.windows.net")&&/rsct=image\/(jpeg|jpg|gif|png|bmp)/i.test(s)}function zf(s,e,t){let r,n,i,l,a,o,c,u,f,d,h,_;fe(s,xe,T=>t(2,i=T)),fe(s,re,T=>t(3,l=T)),fe(s,Ft,T=>t(26,a=T)),fe(s,wt,T=>t(27,o=T)),fe(s,_s,T=>t(28,c=T)),fe(s,or,T=>t(29,u=T)),fe(s,dn,T=>t(15,f=T)),fe(s,hn,T=>t(16,d=T)),fe(s,$e,T=>t(17,h=T)),fe(s,Ue,T=>t(18,_=T));let m,w,v="",E,P,O,F="",C,N="",ce=null,G="";async function ne(T){O=T.target.files[0],O&&(t(25,F=await yf(O)),console.log(F))}function oe(){Ft.set([]),O=null,t(25,F=""),t(1,w.value="",w)}let se=null;function Oe(){if(!C)return;const T={childList:!0,subtree:!0,characterData:!0};se=new MutationObserver((Ye,at)=>{Te()}),se.observe(C,T)}vn(async()=>{await ua(),Oe()}),sl(()=>{se&&(se.disconnect(),se=null),fa()});function Te(){C&&C.scrollHeight-C.scrollTop-150<=C.clientHeight&&t(7,C.scrollTop=C.scrollHeight,C)}function ve(){ws(v,i,F),t(4,v=""),oe(),t(5,E.style.height="96px",E)}function Ee(){C&&t(7,C.scrollTop=C.scrollHeight,C)}let R=0;rl(()=>{const T=l[i]?.history.length||0;T>R&&Ee(),R=T});let D=0,z=0;function B(T){t(9,ce=T),t(10,G=l[i].history[T].content)}function J(){t(9,ce=null),t(10,G=""),t(6,P.style.height="96px",P)}function H(T){const Ye=G,at=l[i].history.length-T;for(let Dt=0;DtRi();function Be(T){N=T,t(8,N),t(2,i),t(3,l)}function Ke(T){ut[T?"unshift":"push"](()=>{P=T,t(6,P)})}function Ve(){G=this.value,t(10,G)}const M=T=>H(T),Se=()=>J(),be=T=>Bo(T.content),Q=T=>vs(T),Qe=T=>B(T);function De(T){ut[T?"unshift":"push"](()=>{C=T,t(7,C)})}function Le(T){ut[T?"unshift":"push"](()=>{m=T,t(0,m),t(29,u)})}const x=T=>ne(T);function ue(T){ut[T?"unshift":"push"](()=>{w=T,t(1,w),t(28,c)})}function et(T){ut[T?"unshift":"push"](()=>{E=T,t(5,E)})}function Fe(){v=this.value,t(4,v)}const bt=T=>{const Ye=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);!_&&T.key==="Enter"&&!T.shiftKey&&!T.ctrlKey&&!T.metaKey&&!Ye?(T.preventDefault(),ve()):!_&&T.key},Wt=()=>{_?ta():ve()};return s.$$.update=()=>{if(s.$$.dirty[0]&536870913&&u&&m&&(t(0,m.value="",m),or.set(!1)),s.$$.dirty[0]&268435458&&c&&w&&(t(1,w.value="",w),_s.set(!1)),s.$$.dirty[0]&12){const T=i,Ye=l,at=l.length;T!==void 0&&Ye[T]&&t(8,N=Ye[T].title||"New Conversation"),(T==null||T<0||T>=at)&&(console.log("changing conversation from ID",i),xe.set(at>0?at-1:null),console.log("to ID",i))}s.$$.dirty[0]&134217728&&t(14,r=o.includes("Vision")),s.$$.dirty[0]&134217728&&t(13,n=o.includes("GPT")),s.$$.dirty[0]&12&&t(8,N=l[i]?l[i].title:"ChatGPT"),s.$$.dirty[0]&67108864&&t(11,D=a.length),s.$$.dirty[0]&33554432&&(F?t(12,z=1):t(12,z=0))},[m,w,i,l,v,E,P,C,N,ce,G,D,z,n,r,f,d,h,_,ne,oe,ve,B,J,H,F,a,o,c,u,Ce,Be,Ke,Ve,M,Se,be,Q,Qe,De,Le,x,ue,et,Fe,bt,Wt]}class Hf extends ee{constructor(e){super(),X(this,e,zf,Nf,Z,{},null,[-1,-1])}}const Jf="/assets/chat-431b71cc.svg";new Hf({target:document.getElementById("app")});window.addEventListener("load",()=>{const s=document.querySelector('link[rel="icon"]');s&&s.setAttribute("href",Jf)});export{bf as _}; diff --git a/dist/assets/index-9d5554b1.js b/dist/assets/index-9d5554b1.js new file mode 100644 index 0000000..62a77f7 --- /dev/null +++ b/dist/assets/index-9d5554b1.js @@ -0,0 +1 @@ +var z={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},H=/([astvzqmhlc])([^astvzqmhlc]*)/gi,V=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;function Z(r){const n=r.match(V);return n?n.map(Number):[]}function _(r){const n=[],t=String(r).trim();return t[0]!=="M"&&t[0]!=="m"||t.replace(H,(l,o,s)=>{const a=Z(s);let u=o.toLowerCase(),h=o;if(u==="m"&&a.length>2&&(n.push([h,...a.splice(0,2)]),u="l",h=h==="m"?"l":"L"),a.length=z[u]&&a.length&&z[u];)n.push([h,...a.splice(0,z[u])]);return""}),n}function G(r,n){const t=r.x*Math.cos(n)-r.y*Math.sin(n),l=r.y*Math.cos(n)+r.x*Math.sin(n);r.x=t,r.y=l}function U(r,n,t){r.x+=n,r.y+=t}function Q(r,n){r.x*=n,r.y*=n}var g=class L{constructor(n){this.commands=[],n&&n instanceof L?this.commands.push(...n.commands):n&&(this.commands=_(n))}addPath(n){n&&n instanceof L&&this.commands.push(...n.commands)}moveTo(n,t){this.commands.push(["M",n,t])}lineTo(n,t){this.commands.push(["L",n,t])}arc(n,t,l,o,s,a){this.commands.push(["AC",n,t,l,o,s,!!a])}arcTo(n,t,l,o,s){this.commands.push(["AT",n,t,l,o,s])}ellipse(n,t,l,o,s,a,u,h){this.commands.push(["E",n,t,l,o,s,a,u,!!h])}closePath(){this.commands.push(["Z"])}bezierCurveTo(n,t,l,o,s,a){this.commands.push(["C",n,t,l,o,s,a])}quadraticCurveTo(n,t,l,o){this.commands.push(["Q",n,t,l,o])}rect(n,t,l,o){this.commands.push(["R",n,t,l,o])}roundRect(n,t,l,o,s){typeof s>"u"?this.commands.push(["RR",n,t,l,o,0]):this.commands.push(["RR",n,t,l,o,s])}};function F(r,n){let t=0,l=0,o,s,a,u,h,i,R,q,C,A,N,S,E,f,p,w,d,b,P,I,$,m=null,k=null,y=null,T=null,v=null,M=null;r.beginPath();for(let c=0;c1&&(q=Math.sqrt(q),f*=q,p*=q),P={x:f*i.y/p,y:-(p*i.x)/f},C=f*f*p*p,A=f*f*i.y*i.y+p*p*i.x*i.x,u!==a?Q(P,Math.sqrt((C-A)/A)||0):Q(P,-Math.sqrt((C-A)/A)||0),s=Math.atan2((i.y-P.y)/p,(i.x-P.x)/f),o=Math.atan2(-(i.y+P.y)/p,-(i.x+P.x)/f),G(P,R),U(P,(h.x+M.x)/2,(h.y+M.y)/2),r.save(),r.translate(P.x,P.y),r.rotate(R),r.scale(f,p),r.arc(0,0,1,s,o,!u),r.restore();break;case"C":e=n[c],m=e[3],k=e[4],t=e[5],l=e[6],r.bezierCurveTo(e[1],e[2],m,k,t,l);break;case"c":e=n[c],r.bezierCurveTo(e[1]+t,e[2]+l,e[3]+t,e[4]+l,e[5]+t,e[6]+l),m=e[3]+t,k=e[4]+l,t+=e[5],l+=e[6];break;case"S":e=n[c],(m===null||k===null)&&(m=t,k=l),r.bezierCurveTo(2*t-m,2*l-k,e[1],e[2],e[3],e[4]),m=e[1],k=e[2],t=e[3],l=e[4];break;case"s":e=n[c],(m===null||k===null)&&(m=t,k=l),r.bezierCurveTo(2*t-m,2*l-k,e[1]+t,e[2]+l,e[3]+t,e[4]+l),m=e[1]+t,k=e[2]+l,t+=e[3],l+=e[4];break;case"Q":e=n[c],y=e[1],T=e[2],t=e[3],l=e[4],r.quadraticCurveTo(y,T,t,l);break;case"q":e=n[c],y=e[1]+t,T=e[2]+l,t+=e[3],l+=e[4],r.quadraticCurveTo(y,T,t,l);break;case"T":e=n[c],(y===null||T===null)&&(y=t,T=l),y=2*t-y,T=2*l-T,t=e[1],l=e[2],r.quadraticCurveTo(y,T,t,l);break;case"t":e=n[c],(y===null||T===null)&&(y=t,T=l),y=2*t-y,T=2*l-T,t+=e[1],l+=e[2],r.quadraticCurveTo(y,T,t,l);break;case"z":case"Z":v&&(t=v.x,l=v.y),v=null,r.closePath();break;case"AC":e=n[c],t=e[1],l=e[2],E=e[3],s=e[4],o=e[5],I=e[6],r.arc(t,l,E,s,o,I);break;case"AT":e=n[c],N=e[1],S=e[2],t=e[3],l=e[4],E=e[5],r.arcTo(N,S,t,l,E);break;case"E":e=n[c],t=e[1],l=e[2],f=e[3],p=e[4],R=e[5],s=e[6],o=e[7],I=e[8],r.save(),r.translate(t,l),r.rotate(R),r.scale(f,p),r.arc(0,0,1,s,o,I),r.restore();break;case"R":e=n[c],t=e[1],l=e[2],w=e[3],d=e[4],v={x:t,y:l},r.rect(t,l,w,d);break;case"RR":e=n[c],t=e[1],l=e[2],w=e[3],d=e[4],$=e[5],v={x:t,y:l},r.roundRect(t,l,w,d,$);break;default:throw new Error(`Invalid path command: ${b}`)}M?(M.x=t,M.y=l):M={x:t,y:l}}}function B(r,n,t,l,o=0){if(typeof o=="number"&&(o=[o]),Array.isArray(o)){if(o.length===0||o.length>4)throw new RangeError(`Failed to execute 'roundRect' on '${this.constructor.name}': ${o.length} radii provided. Between one and four radii are necessary.`);o.forEach(R=>{if(R<0)throw new RangeError(`Failed to execute 'roundRect' on '${this.constructor.name}': Radius value ${R} is negative.`)})}else return;if(o.length===1&&o[0]===0){this.rect(r,n,t,l);return}const s=Math.min(t,l)/2,a=Math.min(s,o[0]);let u=a,h=a,i=a;o.length===2&&(u=Math.min(s,o[1]),i=u),o.length===3&&(u=Math.min(s,o[1]),i=u,h=Math.min(s,o[2])),o.length===4&&(u=Math.min(s,o[1]),h=Math.min(s,o[2]),i=Math.min(s,o[3])),this.moveTo(r,n+l-i),this.arcTo(r,n,r+a,n,a),this.arcTo(r+t,n,r+t,n+u,u),this.arcTo(r+t,n+l,r+t-h,n+l,h),this.arcTo(r,n+l,r,n+l-i,i),this.moveTo(r,n)}function j(r){if(!r)return;const n=r.prototype.fill,t=r.prototype.stroke,l=r.prototype.isPointInPath;r.prototype.fill=function(...s){if(s[0]instanceof g){const u=s[0],h=s[1]||"nonzero";return F(this,u.commands),n.apply(this,[h])}const a=s[0]||"nonzero";return n.apply(this,[a])},r.prototype.stroke=function(s){s&&F(this,s.commands),t.apply(this)},r.prototype.isPointInPath=function(...s){if(s[0]instanceof g){const a=s[0],u=s[1],h=s[2],i=s[3]||"nonzero";return F(this,a.commands),l.apply(this,[u,h,i])}return l.apply(this,s)}}function J(r){r&&!r.prototype.roundRect&&(r.prototype.roundRect=B)}function K(r){r&&!r.prototype.roundRect&&(r.prototype.roundRect=B)}export{g as Path2D,j as applyPath2DToCanvasRenderingContext,J as applyRoundRectToCanvasRenderingContext2D,K as applyRoundRectToPath2D,F as buildPath,_ as parsePath,B as roundRect}; diff --git a/dist/assets/index-b0e9e5d3.css b/dist/assets/index-b0e9e5d3.css new file mode 100644 index 0000000..0268f72 --- /dev/null +++ b/dist/assets/index-b0e9e5d3.css @@ -0,0 +1 @@ +*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.left-1{left:.25rem}.right-0{right:0}.top-0{top:0}.top-1{top:.25rem}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.m-0{margin:0}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-10{margin-left:2.5rem;margin-right:2.5rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.my-3{margin-top:.75rem;margin-bottom:.75rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.ml-0{margin-left:0}.ml-10{margin-left:2.5rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-5{margin-left:1.25rem}.mr-0{margin-right:0}.mr-2{margin-right:.5rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.contents{display:contents}.hidden{display:none}.h-24{height:6rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-16{max-height:4rem}.min-h-\[50px\]{min-height:50px}.min-h-\[96px\]{min-height:96px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-\[24px\]{width:24px}.w-\[260px\]{width:260px}.w-full{width:100%}.min-w-\[24px\]{min-width:24px}.max-w-3xl{max-width:48rem}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.flex-grow,.grow{flex-grow:1}.grow-0{flex-grow:0}.-translate-x-\[100\%\]{--tw-translate-x: -100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap-reverse{flex-wrap:wrap-reverse}.place-content-center{place-content:center}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-l-none{border-top-left-radius:0;border-bottom-left-radius:0}.rounded-r-none{border-top-right-radius:0;border-bottom-right-radius:0}.border{border-width:1px}.border-2{border-width:2px}.border-b-2{border-bottom-width:2px}.border-l-2{border-left-width:2px}.border-r-2{border-right-width:2px}.border-t-2{border-top-width:2px}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity))}.border-green-800{--tw-border-opacity: 1;border-color:rgb(22 101 52 / var(--tw-border-opacity))}.border-white\/20{border-color:#fff3}.border-white\/50{border-color:#ffffff80}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.bg-chat{--tw-bg-opacity: 1;background-color:rgb(69 76 90 / var(--tw-bg-opacity))}.bg-good{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity))}.bg-green-700{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity))}.bg-hover2{--tw-bg-opacity: 1;background-color:rgb(51 57 67 / var(--tw-bg-opacity))}.bg-primary{--tw-bg-opacity: 1;background-color:rgb(40 44 52 / var(--tw-bg-opacity))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity))}.bg-red-700{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity))}.bg-secondary{--tw-bg-opacity: 1;background-color:rgb(33 37 43 / var(--tw-bg-opacity))}.bg-warning{--tw-bg-opacity: 1;background-color:rgb(194 62 69 / var(--tw-bg-opacity))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity))}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-20{padding-left:5rem;padding-right:5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.pb-3{padding-bottom:.75rem}.pb-5{padding-bottom:1.25rem}.pl-20{padding-left:5rem}.pl-3{padding-left:.75rem}.pt-1{padding-top:.25rem}.pt-5{padding-top:1.25rem}.pt-\[3px\]{padding-top:3px}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[1rem\]{font-size:1rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-white\/80{color:#fffc}.text-white\/90{color:#ffffffe6}.underline{text-decoration-line:underline}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}*{font-family:Segoe UI,sans-serif}body{background-color:#21252b}.icon-white{filter:invert(75%)}.hover\:bg-blue-400:hover{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.hover\:bg-good2:hover{--tw-bg-opacity: 1;background-color:rgb(72 137 254 / var(--tw-bg-opacity))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.hover\:bg-green-500:hover{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity))}.hover\:bg-hover:hover{--tw-bg-opacity: 1;background-color:rgb(43 48 56 / var(--tw-bg-opacity))}.hover\:bg-hover2:hover{--tw-bg-opacity: 1;background-color:rgb(51 57 67 / var(--tw-bg-opacity))}.hover\:bg-red-500:hover{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity))}.hover\:bg-warning:hover{--tw-bg-opacity: 1;background-color:rgb(194 62 69 / var(--tw-bg-opacity))}.hover\:bg-warningHover:hover{--tw-bg-opacity: 1;background-color:rgb(229 104 101 / var(--tw-bg-opacity))}.hover\:text-blue-500:hover{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}.hover\:opacity-hover:hover{opacity:.2}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:outline-primary:focus{outline-color:#282c34}@media (min-width: 768px){.md\:ml-\[260px\]{margin-left:260px}.md\:flex{display:flex}.md\:hidden{display:none}.md\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}.playbutton.svelte-2tsp55,.downloadbutton.svelte-2tsp55{color:#add8e6}.playbutton.svelte-2tsp55:hover,.downloadbutton.svelte-2tsp55:hover{color:#add8e6;text-decoration:underline}.notice.svelte-2tsp55{font-size:.8em;color:#c4c457}.conversation.svelte-2c65x7 .edit.svelte-2c65x7,.conversation.svelte-2c65x7 .delete.svelte-2c65x7,.conversation.svelte-2c65x7:hover .tokens.svelte-2c65x7{display:none}.conversation.svelte-2c65x7:hover .edit.svelte-2c65x7,.conversation.svelte-2c65x7:hover .delete.svelte-2c65x7{display:flex}.edit-input.svelte-2c65x7.svelte-2c65x7{background-color:#333;color:#fff;width:auto;max-width:145px;padding:8px;border-radius:4px;border:1px solid #555}.title-container.svelte-2c65x7.svelte-2c65x7{overflow:hidden}.title-container.svelte-2c65x7.svelte-2c65x7:hover{z-index:20}.title-text.svelte-2c65x7.svelte-2c65x7{white-space:nowrap;overflow:hidden;text-overflow:clip;display:inline-block;max-width:100%;vertical-align:top}.convo-container.svelte-2c65x7.svelte-2c65x7:after{content:"";position:absolute;top:0;right:3px;bottom:0;width:3em;background:linear-gradient(to right,rgb(33,37,43,0),#21252b 80%,#21252b);z-index:10}.convo-container.svelte-2c65x7:after .title-container.svelte-2c65x7:hover{background:linear-gradient(to right,rgb(33,37,43,0),#333943 80%,#333943)}.fixed{background-color:#0006}.min-h-screen{min-height:calc(100vh - 4rem)}.bg-white{width:24rem}.border{padding:.5rem}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation-name:fadeIn;animation-duration:.2s;animation-fill-mode:forwards}input:checked~.dot{transform:translate(1.5rem);background-color:#8ee78e}pre.svelte-hssbda{background-color:#0d0d0d;border-radius:0 0 10px 10px;padding:20px;margin:0 20px;opacity:0;animation:svelte-hssbda-fade-in .5s ease-in-out forwards;margin-bottom:1rem;font-weight:700;overflow-wrap:break-word;white-space:pre-wrap}.copycode.svelte-hssbda{display:flex;justify-content:flex-end;background-color:#2f2f2f;margin:0 20px;border-radius:10px 10px 0 0;padding:.5rem 1rem}button.svelte-hssbda{font-size:small;display:block;transition:all .1s ease-in-out;color:#bbb}button.svelte-hssbda:hover{color:#fff}@keyframes svelte-hssbda-fade-in{0%{opacity:0}to{opacity:1}}@keyframes svelte-6aocss-fade-in{0%{opacity:0}to{opacity:1}}em.svelte-djznuz{font-weight:700}ol.svelte-1dicnom,ul.svelte-1dicnom{padding-left:1rem;padding-right:1rem}li.svelte-fm7yqp{padding-bottom:.5rem;padding-left:.5rem;list-style-type:decimal}li.svelte-fm7yqp::marker{color:#fff6}code.svelte-we39e{font-weight:700}p.svelte-jw73bw{padding-bottom:1rem}.height-manager{height:calc(var(--app-height) * 100)}@media (min-width: 1024px){.height-manager{height:100vh}}.tools{opacity:0;visibility:hidden;transition:opacity .1s,visibility .1s}.message:hover .tools{opacity:1;visibility:visible}.file-input{width:.1px;height:.1px;opacity:0;overflow:hidden;position:absolute;z-index:-1}.file-label{display:inline-flex;align-items:center;justify-content:center;gap:10px;color:#fff}.file-label:hover,.file-label:active{background-color:#696d85;cursor:pointer}.file-label{display:inline-flex;align-items:center;justify-content:center;gap:10px}.upload-icon{width:36px;height:auto}.fileCount{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;border:2px solid white;border-radius:50%;background-color:transparent;color:#fff;font-size:16px}.pdf-icon{width:36px;height:auto}.copy-icon{filter:invert(60%)}.copy-icon:hover{filter:invert(100%)}.delete-icon{filter:grayscale(100%) invert(75%)}.delete-icon:hover{filter:none}.edit-icon{filter:grayscale(100%) invert(75%)}.edit-icon:hover{filter:grayscale(100%) invert(100%)}.inputbox-container{width:100%;justify-content:center;align-items:center;display:flex}::-webkit-scrollbar{width:8px}::-webkit-scrollbar-button{background-color:#464d5c;height:0px}::-webkit-scrollbar-track-piece{background-color:#282c34}::-webkit-scrollbar-thumb{height:50px;background-color:#666;border-radius:12px}::-webkit-scrollbar-corner{background-color:#646464}::-webkit-resizer{background-color:#666}.message p{padding-bottom:.5rem} diff --git a/dist/assets/index-b4911648.css b/dist/assets/index-b4911648.css deleted file mode 100644 index 544f3d5..0000000 --- a/dist/assets/index-b4911648.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0px;right:0px;bottom:0px;left:0px}.left-1{left:.25rem}.right-0{right:0px}.top-0{top:0px}.top-1{top:.25rem}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.m-0{margin:0}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-10{margin-left:2.5rem;margin-right:2.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.ml-0{margin-left:0}.ml-10{margin-left:2.5rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-5{margin-left:1.25rem}.mr-0{margin-right:0}.mr-2{margin-right:.5rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.contents{display:contents}.hidden{display:none}.h-24{height:6rem}.h-4{height:1rem}.h-40{height:10rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-16{max-height:4rem}.min-h-\[50px\]{min-height:50px}.min-h-\[96px\]{min-height:96px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-3{width:.75rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-\[24px\]{width:24px}.w-\[260px\]{width:260px}.w-full{width:100%}.min-w-\[24px\]{min-width:24px}.max-w-3xl{max-width:48rem}.max-w-lg{max-width:32rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.flex-grow,.grow{flex-grow:1}.grow-0{flex-grow:0}.-translate-x-\[100\%\]{--tw-translate-x: -100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap-reverse{flex-wrap:wrap-reverse}.place-content-center{place-content:center}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-l-none{border-top-left-radius:0;border-bottom-left-radius:0}.rounded-r-none{border-top-right-radius:0;border-bottom-right-radius:0}.border{border-width:1px}.border-2{border-width:2px}.border-b-2{border-bottom-width:2px}.border-l-2{border-left-width:2px}.border-r-2{border-right-width:2px}.border-t-2{border-top-width:2px}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity))}.border-gray-500{--tw-border-opacity: 1;border-color:rgb(107 114 128 / var(--tw-border-opacity))}.border-green-800{--tw-border-opacity: 1;border-color:rgb(22 101 52 / var(--tw-border-opacity))}.border-white\/20{border-color:#fff3}.border-white\/50{border-color:#ffffff80}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.bg-chat{--tw-bg-opacity: 1;background-color:rgb(69 76 90 / var(--tw-bg-opacity))}.bg-good{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity))}.bg-green-700{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity))}.bg-hover2{--tw-bg-opacity: 1;background-color:rgb(51 57 67 / var(--tw-bg-opacity))}.bg-primary{--tw-bg-opacity: 1;background-color:rgb(40 44 52 / var(--tw-bg-opacity))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity))}.bg-secondary{--tw-bg-opacity: 1;background-color:rgb(33 37 43 / var(--tw-bg-opacity))}.bg-warning{--tw-bg-opacity: 1;background-color:rgb(194 62 69 / var(--tw-bg-opacity))}.bg-yellow-600{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity))}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-20{padding-left:5rem;padding-right:5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.pb-3{padding-bottom:.75rem}.pb-5{padding-bottom:1.25rem}.pl-20{padding-left:5rem}.pl-3{padding-left:.75rem}.pt-1{padding-top:.25rem}.pt-5{padding-top:1.25rem}.pt-\[3px\]{padding-top:3px}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[1rem\]{font-size:1rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.text-white\/80{color:#fffc}.text-white\/90{color:#ffffffe6}.underline{text-decoration-line:underline}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}*{font-family:Segoe UI,sans-serif}body{background-color:#21252b}.icon-white{filter:invert(75%)}.hover\:bg-blue-400:hover{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.hover\:bg-good2:hover{--tw-bg-opacity: 1;background-color:rgb(72 137 254 / var(--tw-bg-opacity))}.hover\:bg-gray-500:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity))}.hover\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.hover\:bg-green-500:hover{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity))}.hover\:bg-hover:hover{--tw-bg-opacity: 1;background-color:rgb(43 48 56 / var(--tw-bg-opacity))}.hover\:bg-hover2:hover{--tw-bg-opacity: 1;background-color:rgb(51 57 67 / var(--tw-bg-opacity))}.hover\:bg-warning:hover{--tw-bg-opacity: 1;background-color:rgb(194 62 69 / var(--tw-bg-opacity))}.hover\:bg-warningHover:hover{--tw-bg-opacity: 1;background-color:rgb(229 104 101 / var(--tw-bg-opacity))}.hover\:text-blue-500:hover{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity))}.hover\:text-blue-700:hover{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}.hover\:opacity-hover:hover{opacity:.2}.focus\:bg-white:focus{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:outline-primary:focus{outline-color:#282c34}@media (min-width: 768px){.md\:ml-\[260px\]{margin-left:260px}.md\:flex{display:flex}.md\:hidden{display:none}.md\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}.playbutton.svelte-2tsp55,.downloadbutton.svelte-2tsp55{color:#add8e6}.playbutton.svelte-2tsp55:hover,.downloadbutton.svelte-2tsp55:hover{color:#add8e6;text-decoration:underline}.notice.svelte-2tsp55{font-size:.8em;color:#c4c457}.conversation.svelte-2c65x7 .edit.svelte-2c65x7,.conversation.svelte-2c65x7 .delete.svelte-2c65x7,.conversation.svelte-2c65x7:hover .tokens.svelte-2c65x7{display:none}.conversation.svelte-2c65x7:hover .edit.svelte-2c65x7,.conversation.svelte-2c65x7:hover .delete.svelte-2c65x7{display:flex}.edit-input.svelte-2c65x7.svelte-2c65x7{background-color:#333;color:#fff;width:auto;max-width:145px;padding:8px;border-radius:4px;border:1px solid #555}.title-container.svelte-2c65x7.svelte-2c65x7{overflow:hidden}.title-container.svelte-2c65x7.svelte-2c65x7:hover{z-index:20}.title-text.svelte-2c65x7.svelte-2c65x7{white-space:nowrap;overflow:hidden;text-overflow:clip;display:inline-block;max-width:100%;vertical-align:top}.convo-container.svelte-2c65x7.svelte-2c65x7:after{content:"";position:absolute;top:0;right:3px;bottom:0;width:3em;background:linear-gradient(to right,rgb(33,37,43,0),#21252b 80%,#21252b);z-index:10}.convo-container.svelte-2c65x7:after .title-container.svelte-2c65x7:hover{background:linear-gradient(to right,rgb(33,37,43,0),#333943 80%,#333943)}.fixed{background-color:#0006}.min-h-screen{min-height:calc(100vh - 4rem)}.bg-white{width:24rem}.border{padding:.5rem}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate-fade-in{animation-name:fadeIn;animation-duration:.2s;animation-fill-mode:forwards}input:checked~.dot{transform:translate(1.5rem);background-color:#8ee78e}pre.svelte-hssbda{background-color:#0d0d0d;border-radius:0 0 10px 10px;padding:20px;margin:0 20px;opacity:0;animation:svelte-hssbda-fade-in .5s ease-in-out forwards;margin-bottom:1rem;font-weight:700;overflow-wrap:break-word;white-space:pre-wrap}.copycode.svelte-hssbda{display:flex;justify-content:flex-end;background-color:#2f2f2f;margin:0 20px;border-radius:10px 10px 0 0;padding:.5rem 1rem}button.svelte-hssbda{font-size:small;display:block;transition:all .1s ease-in-out;color:#bbb}button.svelte-hssbda:hover{color:#fff}@keyframes svelte-hssbda-fade-in{0%{opacity:0}to{opacity:1}}em.svelte-djznuz{font-weight:700}ol.svelte-1dicnom,ul.svelte-1dicnom{padding-left:1rem;padding-right:1rem}li.svelte-fm7yqp{padding-bottom:.5rem;padding-left:.5rem;list-style-type:decimal}li.svelte-fm7yqp::marker{color:#fff6}code.svelte-we39e{font-weight:700}p.svelte-jw73bw{padding-bottom:1rem}.height-manager{height:calc(var(--app-height) * 100)}@media (min-width: 1024px){.height-manager{height:100vh}}.tools{opacity:0;visibility:hidden;transition:opacity .1s,visibility .1s}.message:hover .tools{opacity:1;visibility:visible}.file-input{width:.1px;height:.1px;opacity:0;overflow:hidden;position:absolute;z-index:-1}.file-label{display:inline-flex;align-items:center;justify-content:center;gap:10px;color:#fff}.file-label:hover,.file-label:active{background-color:#696d85;cursor:pointer}.file-label{display:inline-flex;align-items:center;justify-content:center;gap:10px}.upload-icon{width:24px;height:auto}.fileCount{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;border:2px solid white;border-radius:50%;background-color:transparent;color:#fff;font-size:16px}.copy-icon{filter:invert(60%)}.copy-icon:hover{filter:invert(100%)}.delete-icon{filter:grayscale(100%) invert(75%)}.delete-icon:hover{filter:none}.edit-icon{filter:grayscale(100%) invert(75%)}.edit-icon:hover{filter:grayscale(100%) invert(100%)}.inputbox-container{width:100%;justify-content:center;align-items:center;display:flex}::-webkit-scrollbar{width:8px}::-webkit-scrollbar-button{background-color:#464d5c;height:0px}::-webkit-scrollbar-track-piece{background-color:#282c34}::-webkit-scrollbar-thumb{height:50px;background-color:#666;border-radius:12px}::-webkit-scrollbar-corner{background-color:#646464}::-webkit-resizer{background-color:#666}.message p{padding-bottom:.5rem} diff --git a/dist/assets/pdf-ea9598b5.js b/dist/assets/pdf-ea9598b5.js new file mode 100644 index 0000000..08af6e7 --- /dev/null +++ b/dist/assets/pdf-ea9598b5.js @@ -0,0 +1,11 @@ +import{_ as Rt}from"./index-4a068af4.js";var Vt={976:(dt,et,V)=>{V.d(et,{AnnotationLayer:()=>ct,FreeTextAnnotationElement:()=>B,InkAnnotationElement:()=>Q,StampAnnotationElement:()=>ht});var y=V(292),z=V(419),_=V(792);function U(Z){return Math.floor(Math.max(0,Math.min(1,Z))*255).toString(16).padStart(2,"0")}function F(Z){return Math.max(0,Math.min(255,255*Z))}class C{static CMYK_G([m,l,e,n]){return["G",1-Math.min(1,.3*m+.59*e+.11*l+n)]}static G_CMYK([m]){return["CMYK",0,0,0,1-m]}static G_RGB([m]){return["RGB",m,m,m]}static G_rgb([m]){return m=F(m),[m,m,m]}static G_HTML([m]){const l=U(m);return`#${l}${l}${l}`}static RGB_G([m,l,e]){return["G",.3*m+.59*l+.11*e]}static RGB_rgb(m){return m.map(F)}static RGB_HTML(m){return`#${m.map(U).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([m,l,e,n]){return["RGB",1-Math.min(1,m+n),1-Math.min(1,e+n),1-Math.min(1,l+n)]}static CMYK_rgb([m,l,e,n]){return[F(1-Math.min(1,m+n)),F(1-Math.min(1,e+n)),F(1-Math.min(1,l+n))]}static CMYK_HTML(m){const l=this.CMYK_RGB(m).slice(1);return this.RGB_HTML(l)}static RGB_CMYK([m,l,e]){const n=1-m,a=1-l,i=1-e,h=Math.min(n,a,i);return["CMYK",n,a,i,h]}}var T=V(284);const A=1e3,o=9,d=new WeakSet;function u(Z){return{width:Z[2]-Z[0],height:Z[3]-Z[1]}}class b{static create(m){switch(m.data.annotationType){case y.AnnotationType.LINK:return new g(m);case y.AnnotationType.TEXT:return new t(m);case y.AnnotationType.WIDGET:switch(m.data.fieldType){case"Tx":return new c(m);case"Btn":return m.data.radioButton?new S(m):m.data.checkBox?new v(m):new M(m);case"Ch":return new I(m);case"Sig":return new f(m)}return new r(m);case y.AnnotationType.POPUP:return new O(m);case y.AnnotationType.FREETEXT:return new B(m);case y.AnnotationType.LINE:return new q(m);case y.AnnotationType.SQUARE:return new st(m);case y.AnnotationType.CIRCLE:return new X(m);case y.AnnotationType.POLYLINE:return new H(m);case y.AnnotationType.CARET:return new Y(m);case y.AnnotationType.INK:return new Q(m);case y.AnnotationType.POLYGON:return new G(m);case y.AnnotationType.HIGHLIGHT:return new K(m);case y.AnnotationType.UNDERLINE:return new at(m);case y.AnnotationType.SQUIGGLY:return new ot(m);case y.AnnotationType.STRIKEOUT:return new lt(m);case y.AnnotationType.STAMP:return new ht(m);case y.AnnotationType.FILEATTACHMENT:return new ft(m);default:return new s(m)}}}class s{#t=!1;constructor(m,{isRenderable:l=!1,ignoreBorder:e=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=l,this.data=m.data,this.layer=m.layer,this.linkService=m.linkService,this.downloadManager=m.downloadManager,this.imageResourcesPath=m.imageResourcesPath,this.renderForms=m.renderForms,this.svgFactory=m.svgFactory,this.annotationStorage=m.annotationStorage,this.enableScripting=m.enableScripting,this.hasJSActions=m.hasJSActions,this._fieldObjects=m.fieldObjects,this.parent=m.parent,l&&(this.container=this._createContainer(e)),n&&this._createQuadrilaterals()}static _hasPopupData({titleObj:m,contentsObj:l,richText:e}){return!!(m?.str||l?.str||e?.str)}get hasPopupData(){return s._hasPopupData(this.data)}_createContainer(m){const{data:l,parent:{page:e,viewport:n}}=this,a=document.createElement("section");a.setAttribute("data-annotation-id",l.id),this instanceof r||(a.tabIndex=A),a.style.zIndex=this.parent.zIndex++,l.popupRef&&a.setAttribute("aria-haspopup","dialog"),l.alternativeText&&(a.title=l.alternativeText),l.noRotate&&a.classList.add("norotate");const{pageWidth:i,pageHeight:h,pageX:p,pageY:w}=n.rawDims;if(!l.rect||this instanceof O){const{rotation:x}=l;return!l.hasOwnCanvas&&x!==0&&this.setRotation(x,a),a}const{width:E,height:R}=u(l.rect),P=y.Util.normalizeRect([l.rect[0],e.view[3]-l.rect[1]+e.view[1],l.rect[2],e.view[3]-l.rect[3]+e.view[1]]);if(!m&&l.borderStyle.width>0){a.style.borderWidth=`${l.borderStyle.width}px`;const x=l.borderStyle.horizontalCornerRadius,k=l.borderStyle.verticalCornerRadius;if(x>0||k>0){const j=`calc(${x}px * var(--scale-factor)) / calc(${k}px * var(--scale-factor))`;a.style.borderRadius=j}else if(this instanceof S){const j=`calc(${E}px * var(--scale-factor)) / calc(${R}px * var(--scale-factor))`;a.style.borderRadius=j}switch(l.borderStyle.style){case y.AnnotationBorderStyleType.SOLID:a.style.borderStyle="solid";break;case y.AnnotationBorderStyleType.DASHED:a.style.borderStyle="dashed";break;case y.AnnotationBorderStyleType.BEVELED:(0,y.warn)("Unimplemented border style: beveled");break;case y.AnnotationBorderStyleType.INSET:(0,y.warn)("Unimplemented border style: inset");break;case y.AnnotationBorderStyleType.UNDERLINE:a.style.borderBottomStyle="solid";break}const D=l.borderColor||null;D?(this.#t=!0,a.style.borderColor=y.Util.makeHexColor(D[0]|0,D[1]|0,D[2]|0)):a.style.borderWidth=0}a.style.left=`${100*(P[0]-p)/i}%`,a.style.top=`${100*(P[1]-w)/h}%`;const{rotation:L}=l;return l.hasOwnCanvas||L===0?(a.style.width=`${100*E/i}%`,a.style.height=`${100*R/h}%`):this.setRotation(L,a),a}setRotation(m,l=this.container){if(!this.data.rect)return;const{pageWidth:e,pageHeight:n}=this.parent.viewport.rawDims,{width:a,height:i}=u(this.data.rect);let h,p;m%180===0?(h=100*a/e,p=100*i/n):(h=100*i/e,p=100*a/n),l.style.width=`${h}%`,l.style.height=`${p}%`,l.setAttribute("data-main-rotation",(360-m)%360)}get _commonActions(){const m=(l,e,n)=>{const a=n.detail[l],i=a[0],h=a.slice(1);n.target.style[e]=C[`${i}_HTML`](h),this.annotationStorage.setValue(this.data.id,{[e]:C[`${i}_rgb`](h)})};return(0,y.shadow)(this,"_commonActions",{display:l=>{const{display:e}=l.detail,n=e%2===1;this.container.style.visibility=n?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:e===1||e===2})},print:l=>{this.annotationStorage.setValue(this.data.id,{noPrint:!l.detail.print})},hidden:l=>{const{hidden:e}=l.detail;this.container.style.visibility=e?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:l=>{setTimeout(()=>l.target.focus({preventScroll:!1}),0)},userName:l=>{l.target.title=l.detail.userName},readonly:l=>{l.target.disabled=l.detail.readonly},required:l=>{this._setRequired(l.target,l.detail.required)},bgColor:l=>{m("bgColor","backgroundColor",l)},fillColor:l=>{m("fillColor","backgroundColor",l)},fgColor:l=>{m("fgColor","color",l)},textColor:l=>{m("textColor","color",l)},borderColor:l=>{m("borderColor","borderColor",l)},strokeColor:l=>{m("strokeColor","borderColor",l)},rotation:l=>{const e=l.detail.rotation;this.setRotation(e),this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(m,l){const e=this._commonActions;for(const n of Object.keys(l.detail))(m[n]||e[n])?.(l)}_setDefaultPropertiesFromJS(m){if(!this.enableScripting)return;const l=this.annotationStorage.getRawValue(this.data.id);if(!l)return;const e=this._commonActions;for(const[n,a]of Object.entries(l)){const i=e[n];if(i){const h={detail:{[n]:a},target:m};i(h),delete l[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:m}=this.data;if(!m)return;const[l,e,n,a]=this.data.rect;if(m.length===1){const[,{x:k,y:D},{x:j,y:J}]=m[0];if(n===k&&a===D&&l===j&&e===J)return}const{style:i}=this.container;let h;if(this.#t){const{borderColor:k,borderWidth:D}=i;i.borderWidth=0,h=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const p=n-l,w=a-e,{svgFactory:E}=this,R=E.createElement("svg");R.classList.add("quadrilateralsContainer"),R.setAttribute("width",0),R.setAttribute("height",0);const P=E.createElement("defs");R.append(P);const L=E.createElement("clipPath"),x=`clippath_${this.data.id}`;L.setAttribute("id",x),L.setAttribute("clipPathUnits","objectBoundingBox"),P.append(L);for(const[,{x:k,y:D},{x:j,y:J}]of m){const $=E.createElement("rect"),tt=(j-l)/p,it=(a-D)/w,W=(k-j)/p,rt=(D-J)/w;$.setAttribute("x",tt),$.setAttribute("y",it),$.setAttribute("width",W),$.setAttribute("height",rt),L.append($),h?.push(``)}this.#t&&(h.push("')"),i.backgroundImage=h.join("")),this.container.append(R),this.container.style.clipPath=`url(#${x})`}_createPopup(){const{container:m,data:l}=this;m.setAttribute("aria-haspopup","dialog");const e=new O({data:{color:l.color,titleObj:l.titleObj,modificationDate:l.modificationDate,contentsObj:l.contentsObj,richText:l.richText,parentRect:l.rect,borderStyle:0,id:`popup_${l.id}`,rotation:l.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){(0,y.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(m,l=null){const e=[];if(this._fieldObjects){const n=this._fieldObjects[m];if(n)for(const{page:a,id:i,exportValues:h}of n){if(a===-1||i===l)continue;const p=typeof h=="string"?h:null,w=document.querySelector(`[data-element-id="${i}"]`);if(w&&!d.has(w)){(0,y.warn)(`_getElementsByName - element not allowed: ${i}`);continue}e.push({id:i,exportValue:p,domElement:w})}return e}for(const n of document.getElementsByName(m)){const{exportValue:a}=n,i=n.getAttribute("data-element-id");i!==l&&d.has(n)&&e.push({id:i,exportValue:a,domElement:n})}return e}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 m=this.getElementsToTriggerPopup();if(Array.isArray(m))for(const l of m)l.classList.add("highlightArea");else m.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:m,data:{id:l}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:m,editId:l})})}}class g extends s{constructor(m,l=null){super(m,{isRenderable:!0,ignoreBorder:!!l?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=m.data.isTooltipOnly}render(){const{data:m,linkService:l}=this,e=document.createElement("a");e.setAttribute("data-element-id",m.id);let n=!1;return m.url?(l.addLinkAttributes(e,m.url,m.newWindow),n=!0):m.action?(this._bindNamedAction(e,m.action),n=!0):m.attachment?(this.#e(e,m.attachment,m.attachmentDest),n=!0):m.setOCGState?(this.#s(e,m.setOCGState),n=!0):m.dest?(this._bindLink(e,m.dest),n=!0):(m.actions&&(m.actions.Action||m.actions["Mouse Up"]||m.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(e,m),n=!0),m.resetForm?(this._bindResetFormAction(e,m.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(e,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&this.container.append(e),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(m,l){m.href=this.linkService.getDestinationHash(l),m.onclick=()=>(l&&this.linkService.goToDestination(l),!1),(l||l==="")&&this.#t()}_bindNamedAction(m,l){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.linkService.executeNamedAction(l),!1),this.#t()}#e(m,l,e=null){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.downloadManager?.openOrDownloadData(l.content,l.filename,e),!1),this.#t()}#s(m,l){m.href=this.linkService.getAnchorUrl(""),m.onclick=()=>(this.linkService.executeSetOCGState(l),!1),this.#t()}_bindJSAction(m,l){m.href=this.linkService.getAnchorUrl("");const e=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(l.actions)){const a=e.get(n);a&&(m[a]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l.id,name:n}}),!1))}m.onclick||(m.onclick=()=>!1),this.#t()}_bindResetFormAction(m,l){const e=m.onclick;if(e||(m.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){(0,y.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),e||(m.onclick=()=>!1);return}m.onclick=()=>{e?.();const{fields:n,refs:a,include:i}=l,h=[];if(n.length!==0||a.length!==0){const E=new Set(a);for(const R of n){const P=this._fieldObjects[R]||[];for(const{id:L}of P)E.add(L)}for(const R of Object.values(this._fieldObjects))for(const P of R)E.has(P.id)===i&&h.push(P)}else for(const E of Object.values(this._fieldObjects))h.push(...E);const p=this.annotationStorage,w=[];for(const E of h){const{id:R}=E;switch(w.push(R),E.type){case"text":{const L=E.defaultValue||"";p.setValue(R,{value:L});break}case"checkbox":case"radiobutton":{const L=E.defaultValue===E.exportValues;p.setValue(R,{value:L});break}case"combobox":case"listbox":{const L=E.defaultValue||"";p.setValue(R,{value:L});break}default:continue}const P=document.querySelector(`[data-element-id="${R}"]`);if(P){if(!d.has(P)){(0,y.warn)(`_bindResetFormAction - element not allowed: ${R}`);continue}}else continue;P.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:w,name:"ResetForm"}}),!1}}}class t extends s{constructor(m){super(m,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const m=document.createElement("img");return m.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",m.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),m.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(m),this.container}}class r extends s{render(){return this.container}showElementAndHideCanvas(m){this.data.hasOwnCanvas&&(m.previousSibling?.nodeName==="CANVAS"&&(m.previousSibling.hidden=!0),m.hidden=!1)}_getKeyModifier(m){return y.FeatureTest.platform.isMac?m.metaKey:m.ctrlKey}_setEventListener(m,l,e,n,a){e.includes("mouse")?m.addEventListener(e,i=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:a(i),shift:i.shiftKey,modifier:this._getKeyModifier(i)}})}):m.addEventListener(e,i=>{if(e==="blur"){if(!l.focused||!i.relatedTarget)return;l.focused=!1}else if(e==="focus"){if(l.focused)return;l.focused=!0}a&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:a(i)}})})}_setEventListeners(m,l,e,n){for(const[a,i]of e)(i==="Action"||this.data.actions?.[i])&&((i==="Focus"||i==="Blur")&&(l||={focused:!1}),this._setEventListener(m,l,a,i,n),i==="Focus"&&!this.data.actions?.Blur?this._setEventListener(m,l,"blur","Blur",null):i==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(m,l,"focus","Focus",null))}_setBackgroundColor(m){const l=this.data.backgroundColor||null;m.style.backgroundColor=l===null?"transparent":y.Util.makeHexColor(l[0],l[1],l[2])}_setTextStyle(m){const l=["left","center","right"],{fontColor:e}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||o,a=m.style;let i;const h=2,p=w=>Math.round(10*w)/10;if(this.data.multiLine){const w=Math.abs(this.data.rect[3]-this.data.rect[1]-h),E=Math.round(w/(y.LINE_FACTOR*n))||1,R=w/E;i=Math.min(n,p(R/y.LINE_FACTOR))}else{const w=Math.abs(this.data.rect[3]-this.data.rect[1]-h);i=Math.min(n,p(w/y.LINE_FACTOR))}a.fontSize=`calc(${i}px * var(--scale-factor))`,a.color=y.Util.makeHexColor(e[0],e[1],e[2]),this.data.textAlignment!==null&&(a.textAlign=l[this.data.textAlignment])}_setRequired(m,l){l?m.setAttribute("required",!0):m.removeAttribute("required"),m.setAttribute("aria-required",l)}}class c extends r{constructor(m){const l=m.renderForms||m.data.hasOwnCanvas||!m.data.hasAppearance&&!!m.data.fieldValue;super(m,{isRenderable:l})}setPropertyOnSiblings(m,l,e,n){const a=this.annotationStorage;for(const i of this._getElementsByName(m.name,m.id))i.domElement&&(i.domElement[l]=e),a.setValue(i.id,{[n]:e})}render(){const m=this.annotationStorage,l=this.data.id;this.container.classList.add("textWidgetAnnotation");let e=null;if(this.renderForms){const n=m.getValue(l,{value:this.data.fieldValue});let a=n.value||"";const i=m.getValue(l,{charLimit:this.data.maxLen}).charLimit;i&&a.length>i&&(a=a.slice(0,i));let h=n.formattedValue||this.data.textContent?.join(` +`)||null;h&&this.data.comb&&(h=h.replaceAll(/\s+/g,""));const p={userValue:a,formattedValue:h,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(e=document.createElement("textarea"),e.textContent=h??a,this.data.doNotScroll&&(e.style.overflowY="hidden")):(e=document.createElement("input"),e.type="text",e.setAttribute("value",h??a),this.data.doNotScroll&&(e.style.overflowX="hidden")),this.data.hasOwnCanvas&&(e.hidden=!0),d.add(e),e.setAttribute("data-element-id",l),e.disabled=this.data.readOnly,e.name=this.data.fieldName,e.tabIndex=A,this._setRequired(e,this.data.required),i&&(e.maxLength=i),e.addEventListener("input",E=>{m.setValue(l,{value:E.target.value}),this.setPropertyOnSiblings(e,"value",E.target.value,"value"),p.formattedValue=null}),e.addEventListener("resetform",E=>{const R=this.data.defaultFieldValue??"";e.value=p.userValue=R,p.formattedValue=null});let w=E=>{const{formattedValue:R}=p;R!=null&&(E.target.value=R),E.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){e.addEventListener("focus",R=>{if(p.focused)return;const{target:P}=R;p.userValue&&(P.value=p.userValue),p.lastCommittedValue=P.value,p.commitKey=1,this.data.actions?.Focus||(p.focused=!0)}),e.addEventListener("updatefromsandbox",R=>{this.showElementAndHideCanvas(R.target);const P={value(L){p.userValue=L.detail.value??"",m.setValue(l,{value:p.userValue.toString()}),L.target.value=p.userValue},formattedValue(L){const{formattedValue:x}=L.detail;p.formattedValue=x,x!=null&&L.target!==document.activeElement&&(L.target.value=x),m.setValue(l,{formattedValue:x})},selRange(L){L.target.setSelectionRange(...L.detail.selRange)},charLimit:L=>{const{charLimit:x}=L.detail,{target:k}=L;if(x===0){k.removeAttribute("maxLength");return}k.setAttribute("maxLength",x);let D=p.userValue;!D||D.length<=x||(D=D.slice(0,x),k.value=p.userValue=D,m.setValue(l,{value:D}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l,name:"Keystroke",value:D,willCommit:!0,commitKey:1,selStart:k.selectionStart,selEnd:k.selectionEnd}}))}};this._dispatchEventFromSandbox(P,R)}),e.addEventListener("keydown",R=>{p.commitKey=1;let P=-1;if(R.key==="Escape"?P=0:R.key==="Enter"&&!this.data.multiLine?P=2:R.key==="Tab"&&(p.commitKey=3),P===-1)return;const{value:L}=R.target;p.lastCommittedValue!==L&&(p.lastCommittedValue=L,p.userValue=L,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l,name:"Keystroke",value:L,willCommit:!0,commitKey:P,selStart:R.target.selectionStart,selEnd:R.target.selectionEnd}}))});const E=w;w=null,e.addEventListener("blur",R=>{if(!p.focused||!R.relatedTarget)return;this.data.actions?.Blur||(p.focused=!1);const{value:P}=R.target;p.userValue=P,p.lastCommittedValue!==P&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l,name:"Keystroke",value:P,willCommit:!0,commitKey:p.commitKey,selStart:R.target.selectionStart,selEnd:R.target.selectionEnd}}),E(R)}),this.data.actions?.Keystroke&&e.addEventListener("beforeinput",R=>{p.lastCommittedValue=null;const{data:P,target:L}=R,{value:x,selectionStart:k,selectionEnd:D}=L;let j=k,J=D;switch(R.inputType){case"deleteWordBackward":{const $=x.substring(0,k).match(/\w*[^\w]*$/);$&&(j-=$[0].length);break}case"deleteWordForward":{const $=x.substring(k).match(/^[^\w]*\w*/);$&&(J+=$[0].length);break}case"deleteContentBackward":k===D&&(j-=1);break;case"deleteContentForward":k===D&&(J+=1);break}R.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l,name:"Keystroke",value:x,change:P||"",willCommit:!1,selStart:j,selEnd:J}})}),this._setEventListeners(e,p,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],R=>R.target.value)}if(w&&e.addEventListener("blur",w),this.data.comb){const R=(this.data.rect[2]-this.data.rect[0])/i;e.classList.add("comb"),e.style.letterSpacing=`calc(${R}px * var(--scale-factor) - 1ch)`}}else e=document.createElement("div"),e.textContent=this.data.fieldValue,e.style.verticalAlign="middle",e.style.display="table-cell",this.data.hasOwnCanvas&&(e.hidden=!0);return this._setTextStyle(e),this._setBackgroundColor(e),this._setDefaultPropertiesFromJS(e),this.container.append(e),this.container}}class f extends r{constructor(m){super(m,{isRenderable:!!m.data.hasOwnCanvas})}}class v extends r{constructor(m){super(m,{isRenderable:m.renderForms})}render(){const m=this.annotationStorage,l=this.data,e=l.id;let n=m.getValue(e,{value:l.exportValue===l.fieldValue}).value;typeof n=="string"&&(n=n!=="Off",m.setValue(e,{value:n})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const a=document.createElement("input");return d.add(a),a.setAttribute("data-element-id",e),a.disabled=l.readOnly,this._setRequired(a,this.data.required),a.type="checkbox",a.name=l.fieldName,n&&a.setAttribute("checked",!0),a.setAttribute("exportValue",l.exportValue),a.tabIndex=A,a.addEventListener("change",i=>{const{name:h,checked:p}=i.target;for(const w of this._getElementsByName(h,e)){const E=p&&w.exportValue===l.exportValue;w.domElement&&(w.domElement.checked=E),m.setValue(w.id,{value:E})}m.setValue(e,{value:p})}),a.addEventListener("resetform",i=>{const h=l.defaultFieldValue||"Off";i.target.checked=h===l.exportValue}),this.enableScripting&&this.hasJSActions&&(a.addEventListener("updatefromsandbox",i=>{const h={value(p){p.target.checked=p.detail.value!=="Off",m.setValue(e,{value:p.target.checked})}};this._dispatchEventFromSandbox(h,i)}),this._setEventListeners(a,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],i=>i.target.checked)),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class S extends r{constructor(m){super(m,{isRenderable:m.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const m=this.annotationStorage,l=this.data,e=l.id;let n=m.getValue(e,{value:l.fieldValue===l.buttonValue}).value;if(typeof n=="string"&&(n=n!==l.buttonValue,m.setValue(e,{value:n})),n)for(const i of this._getElementsByName(l.fieldName,e))m.setValue(i.id,{value:!1});const a=document.createElement("input");if(d.add(a),a.setAttribute("data-element-id",e),a.disabled=l.readOnly,this._setRequired(a,this.data.required),a.type="radio",a.name=l.fieldName,n&&a.setAttribute("checked",!0),a.tabIndex=A,a.addEventListener("change",i=>{const{name:h,checked:p}=i.target;for(const w of this._getElementsByName(h,e))m.setValue(w.id,{value:!1});m.setValue(e,{value:p})}),a.addEventListener("resetform",i=>{const h=l.defaultFieldValue;i.target.checked=h!=null&&h===l.buttonValue}),this.enableScripting&&this.hasJSActions){const i=l.buttonValue;a.addEventListener("updatefromsandbox",h=>{const p={value:w=>{const E=i===w.detail.value;for(const R of this._getElementsByName(w.target.name)){const P=E&&R.id===e;R.domElement&&(R.domElement.checked=P),m.setValue(R.id,{value:P})}}};this._dispatchEventFromSandbox(p,h)}),this._setEventListeners(a,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],h=>h.target.checked)}return this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class M extends g{constructor(m){super(m,{ignoreBorder:m.data.hasAppearance})}render(){const m=super.render();m.classList.add("buttonWidgetAnnotation","pushButton");const l=m.lastChild;return this.enableScripting&&this.hasJSActions&&l&&(this._setDefaultPropertiesFromJS(l),l.addEventListener("updatefromsandbox",e=>{this._dispatchEventFromSandbox({},e)})),m}}class I extends r{constructor(m){super(m,{isRenderable:m.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const m=this.annotationStorage,l=this.data.id,e=m.getValue(l,{value:this.data.fieldValue}),n=document.createElement("select");d.add(n),n.setAttribute("data-element-id",l),n.disabled=this.data.readOnly,this._setRequired(n,this.data.required),n.name=this.data.fieldName,n.tabIndex=A;let a=this.data.combo&&this.data.options.length>0;this.data.combo||(n.size=this.data.options.length,this.data.multiSelect&&(n.multiple=!0)),n.addEventListener("resetform",E=>{const R=this.data.defaultFieldValue;for(const P of n.options)P.selected=P.value===R});for(const E of this.data.options){const R=document.createElement("option");R.textContent=E.displayValue,R.value=E.exportValue,e.value.includes(E.exportValue)&&(R.setAttribute("selected",!0),a=!1),n.append(R)}let i=null;if(a){const E=document.createElement("option");E.value=" ",E.setAttribute("hidden",!0),E.setAttribute("selected",!0),n.prepend(E),i=()=>{E.remove(),n.removeEventListener("input",i),i=null},n.addEventListener("input",i)}const h=E=>{const R=E?"value":"textContent",{options:P,multiple:L}=n;return L?Array.prototype.filter.call(P,x=>x.selected).map(x=>x[R]):P.selectedIndex===-1?null:P[P.selectedIndex][R]};let p=h(!1);const w=E=>{const R=E.target.options;return Array.prototype.map.call(R,P=>({displayValue:P.textContent,exportValue:P.value}))};return this.enableScripting&&this.hasJSActions?(n.addEventListener("updatefromsandbox",E=>{const R={value(P){i?.();const L=P.detail.value,x=new Set(Array.isArray(L)?L:[L]);for(const k of n.options)k.selected=x.has(k.value);m.setValue(l,{value:h(!0)}),p=h(!1)},multipleSelection(P){n.multiple=!0},remove(P){const L=n.options,x=P.detail.remove;L[x].selected=!1,n.remove(x),L.length>0&&Array.prototype.findIndex.call(L,D=>D.selected)===-1&&(L[0].selected=!0),m.setValue(l,{value:h(!0),items:w(P)}),p=h(!1)},clear(P){for(;n.length!==0;)n.remove(0);m.setValue(l,{value:null,items:[]}),p=h(!1)},insert(P){const{index:L,displayValue:x,exportValue:k}=P.detail.insert,D=n.children[L],j=document.createElement("option");j.textContent=x,j.value=k,D?D.before(j):n.append(j),m.setValue(l,{value:h(!0),items:w(P)}),p=h(!1)},items(P){const{items:L}=P.detail;for(;n.length!==0;)n.remove(0);for(const x of L){const{displayValue:k,exportValue:D}=x,j=document.createElement("option");j.textContent=k,j.value=D,n.append(j)}n.options.length>0&&(n.options[0].selected=!0),m.setValue(l,{value:h(!0),items:w(P)}),p=h(!1)},indices(P){const L=new Set(P.detail.indices);for(const x of P.target.options)x.selected=L.has(x.index);m.setValue(l,{value:h(!0)}),p=h(!1)},editable(P){P.target.disabled=!P.detail.editable}};this._dispatchEventFromSandbox(R,E)}),n.addEventListener("input",E=>{const R=h(!0);m.setValue(l,{value:R}),E.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:l,name:"Keystroke",value:p,changeEx:R,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],E=>E.target.value)):n.addEventListener("input",function(E){m.setValue(l,{value:h(!0)})}),this.data.combo&&this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class O extends s{constructor(m){const{data:l,elements:e}=m;super(m,{isRenderable:s._hasPopupData(l)}),this.elements=e}render(){this.container.classList.add("popupAnnotation");const m=new N({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}),l=[];for(const e of this.elements)e.popup=m,l.push(e.data.id),e.addHighlightArea();return this.container.setAttribute("aria-controls",l.map(e=>`${y.AnnotationPrefix}${e}`).join(",")),this.container}}class N{#t=this.#b.bind(this);#e=this.#E.bind(this);#s=this.#w.bind(this);#n=this.#A.bind(this);#r=null;#i=null;#a=null;#l=null;#h=null;#d=null;#u=null;#c=!1;#o=null;#p=null;#g=null;#f=null;#m=!1;constructor({container:m,color:l,elements:e,titleObj:n,modificationDate:a,contentsObj:i,richText:h,parent:p,rect:w,parentRect:E,open:R}){this.#i=m,this.#f=n,this.#a=i,this.#g=h,this.#d=p,this.#r=l,this.#p=w,this.#u=E,this.#h=e,this.#l=z.PDFDateString.toDateObject(a),this.trigger=e.flatMap(P=>P.getElementsToTriggerPopup());for(const P of this.trigger)P.addEventListener("click",this.#n),P.addEventListener("mouseenter",this.#s),P.addEventListener("mouseleave",this.#e),P.classList.add("popupTriggerArea");for(const P of e)P.container?.addEventListener("keydown",this.#t);this.#i.hidden=!0,R&&this.#A()}render(){if(this.#o)return;const{page:{view:m},viewport:{rawDims:{pageWidth:l,pageHeight:e,pageX:n,pageY:a}}}=this.#d,i=this.#o=document.createElement("div");if(i.className="popup",this.#r){const $=i.style.outlineColor=y.Util.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?i.style.backgroundColor=`color-mix(in srgb, ${$} 30%, white)`:i.style.backgroundColor=y.Util.makeHexColor(...this.#r.map(it=>Math.floor(.7*(255-it)+it)))}const h=document.createElement("span");h.className="header";const p=document.createElement("h1");if(h.append(p),{dir:p.dir,str:p.textContent}=this.#f,i.append(h),this.#l){const $=document.createElement("span");$.classList.add("popupDate"),$.setAttribute("data-l10n-id","pdfjs-annotation-date-string"),$.setAttribute("data-l10n-args",JSON.stringify({date:this.#l.toLocaleDateString(),time:this.#l.toLocaleTimeString()})),h.append($)}const w=this.#a,E=this.#g;if(E?.str&&(!w?.str||w.str===E.str))T.XfaLayer.render({xfaHtml:E.html,intent:"richText",div:i}),i.lastChild.classList.add("richText","popupContent");else{const $=this._formatContents(w);i.append($)}let R=!!this.#u,P=R?this.#u:this.#p;for(const $ of this.#h)if(!P||y.Util.intersect($.data.rect,P)!==null){P=$.data.rect,R=!0;break}const L=y.Util.normalizeRect([P[0],m[3]-P[1]+m[1],P[2],m[3]-P[3]+m[1]]),x=5,k=R?P[2]-P[0]+x:0,D=L[0]+k,j=L[1],{style:J}=this.#i;J.left=`${100*(D-n)/l}%`,J.top=`${100*(j-a)/e}%`,this.#i.append(i)}_formatContents({str:m,dir:l}){const e=document.createElement("p");e.classList.add("popupContent"),e.dir=l;const n=m.split(/(?:\r\n?|\n)/);for(let a=0,i=n.length;a{a.key==="Enter"&&(n?a.metaKey:a.ctrlKey)&&this.#e()}),!l.popupRef&&this.hasPopupData?this._createPopup():e.classList.add("popupTriggerArea"),m.append(e),m}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class ct{#t=null;#e=null;#s=new Map;constructor({div:m,accessibilityManager:l,annotationCanvasMap:e,page:n,viewport:a}){this.div=m,this.#t=l,this.#e=e,this.page=n,this.viewport=a,this.zIndex=0}#n(m,l){const e=m.firstChild||m;e.id=`${y.AnnotationPrefix}${l}`,this.div.append(m),this.#t?.moveElementInDOM(this.div,m,e,!1)}async render(m){const{annotations:l}=m,e=this.div;(0,z.setLayerDimensions)(e,this.viewport);const n=new Map,a={data:null,layer:e,linkService:m.linkService,downloadManager:m.downloadManager,imageResourcesPath:m.imageResourcesPath||"",renderForms:m.renderForms!==!1,svgFactory:new z.DOMSVGFactory,annotationStorage:m.annotationStorage||new _.AnnotationStorage,enableScripting:m.enableScripting===!0,hasJSActions:m.hasJSActions,fieldObjects:m.fieldObjects,parent:this,elements:null};for(const i of l){if(i.noHTML)continue;const h=i.annotationType===y.AnnotationType.POPUP;if(h){const E=n.get(i.id);if(!E)continue;a.elements=E}else{const{width:E,height:R}=u(i.rect);if(E<=0||R<=0)continue}a.data=i;const p=b.create(a);if(!p.isRenderable)continue;if(!h&&i.popupRef){const E=n.get(i.popupRef);E?E.push(p):n.set(i.popupRef,[p])}p.annotationEditorType>0&&this.#s.set(p.data.id,p);const w=p.render();i.hidden&&(w.style.visibility="hidden"),this.#n(w,i.id)}this.#r()}update({viewport:m}){const l=this.div;this.viewport=m,(0,z.setLayerDimensions)(l,{rotation:m.rotation}),this.#r(),l.hidden=!1}#r(){if(!this.#e)return;const m=this.div;for(const[l,e]of this.#e){const n=m.querySelector(`[data-annotation-id="${l}"]`);if(!n)continue;const{firstChild:a}=n;a?a.nodeName==="CANVAS"?a.replaceWith(e):a.before(e):n.append(e)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(m){return this.#s.get(m)}}},792:(dt,et,V)=>{V.d(et,{AnnotationStorage:()=>F,PrintAnnotationStorage:()=>C,SerializableEmpty:()=>U});var y=V(292),z=V(310),_=V(651);const U=Object.freeze({map:null,hash:"",transfer:void 0});class F{#t=!1;#e=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(A,o){const d=this.#e.get(A);return d===void 0?o:Object.assign(o,d)}getRawValue(A){return this.#e.get(A)}remove(A){if(this.#e.delete(A),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const o of this.#e.values())if(o instanceof z.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(A,o){const d=this.#e.get(A);let u=!1;if(d!==void 0)for(const[b,s]of Object.entries(o))d[b]!==s&&(u=!0,d[b]=s);else u=!0,this.#e.set(A,o);u&&this.#s(),o instanceof z.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(o.constructor._type)}has(A){return this.#e.has(A)}getAll(){return this.#e.size>0?(0,y.objectFromMap)(this.#e):null}setAll(A){for(const[o,d]of Object.entries(A))this.setValue(o,d)}get size(){return this.#e.size}#s(){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 C(this)}get serializable(){if(this.#e.size===0)return U;const A=new Map,o=new _.MurmurHash3_64,d=[],u=Object.create(null);let b=!1;for(const[s,g]of this.#e){const t=g instanceof z.AnnotationEditor?g.serialize(!1,u):g;t&&(A.set(s,t),o.update(`${s}:${JSON.stringify(t)}`),b||=!!t.bitmap)}if(b)for(const s of A.values())s.bitmap&&d.push(s.bitmap);return A.size>0?{map:A,hash:o.hexdigest(),transfer:d}:U}get editorStats(){let A=null;const o=new Map;for(const d of this.#e.values()){if(!(d instanceof z.AnnotationEditor))continue;const u=d.telemetryFinalData;if(!u)continue;const{type:b}=u;o.has(b)||o.set(b,Object.getPrototypeOf(d).constructor),A||=Object.create(null);const s=A[b]||=new Map;for(const[g,t]of Object.entries(u)){if(g==="type")continue;let r=s.get(g);r||(r=new Map,s.set(g,r));const c=r.get(t)??0;r.set(t,c+1)}}for(const[d,u]of o)A[d]=u.computeTelemetryFinalData(A[d]);return A}}class C extends F{#t;constructor(A){super();const{map:o,hash:d,transfer:u}=A.serializable,b=structuredClone(o,u?{transfer:u}:null);this.#t={map:b,hash:d,transfer:u}}get print(){(0,y.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}}},831:(dt,et,V)=>{V.a(dt,async(y,z)=>{try{let st=function(a){if(typeof a=="string"||a instanceof URL?a={url:a}:(a instanceof ArrayBuffer||ArrayBuffer.isView(a))&&(a={data:a}),typeof a!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!a.url&&!a.data&&!a.range)throw new Error("Invalid parameter object: need either .data, .range or .url");const i=new Y,{docId:h}=i,p=a.url?H(a.url):null,w=a.data?G(a.data):null,E=a.httpHeaders||null,R=a.withCredentials===!0,P=a.password??null,L=a.range instanceof Q?a.range:null,x=Number.isInteger(a.rangeChunkSize)&&a.rangeChunkSize>0?a.rangeChunkSize:S;let k=a.worker instanceof ht?a.worker:null;const D=a.verbosity,j=typeof a.docBaseUrl=="string"&&!(0,F.isDataScheme)(a.docBaseUrl)?a.docBaseUrl:null,J=typeof a.cMapUrl=="string"?a.cMapUrl:null,$=a.cMapPacked!==!1,tt=a.CMapReaderFactory||N,it=typeof a.standardFontDataUrl=="string"?a.standardFontDataUrl:null,W=a.StandardFontDataFactory||q,rt=a.stopAtErrors!==!0,nt=Number.isInteger(a.maxImageSize)&&a.maxImageSize>-1?a.maxImageSize:-1,ut=a.isEvalSupported!==!1,gt=typeof a.isOffscreenCanvasSupported=="boolean"?a.isOffscreenCanvasSupported:!_.isNodeJS,mt=Number.isInteger(a.canvasMaxAreaInBytes)?a.canvasMaxAreaInBytes:-1,At=typeof a.disableFontFace=="boolean"?a.disableFontFace:_.isNodeJS,bt=a.fontExtraProperties===!0,Ct=a.enableXfa===!0,St=a.ownerDocument||globalThis.document,Tt=a.disableRange===!0,yt=a.disableStream===!0,xt=a.disableAutoFetch===!0,kt=a.pdfBug===!0,Pt=L?L.length:a.length??NaN,Nt=typeof a.useSystemFonts=="boolean"?a.useSystemFonts:!_.isNodeJS&&!At,Mt=typeof a.useWorkerFetch=="boolean"?a.useWorkerFetch:tt===F.DOMCMapReaderFactory&&W===F.DOMStandardFontDataFactory&&J&&it&&(0,F.isValidFetchUrl)(J,document.baseURI)&&(0,F.isValidFetchUrl)(it,document.baseURI),Ot=a.canvasFactory||new O({ownerDocument:St}),Et=a.filterFactory||new B({docId:h,ownerDocument:St}),wt=null;(0,_.setVerbosityLevel)(D);const It={canvasFactory:Ot,filterFactory:Et};if(Mt||(It.cMapReaderFactory=new tt({baseUrl:J,isCompressed:$}),It.standardFontDataFactory=new W({baseUrl:it})),!k){const vt={verbosity:D,port:d.GlobalWorkerOptions.workerPort};k=vt.port?ht.fromPort(vt):new ht(vt),i._worker=k}const Ht={docId:h,apiVersion:"4.1.392",data:w,password:P,disableAutoFetch:xt,rangeChunkSize:x,length:Pt,docBaseUrl:j,enableXfa:Ct,evaluatorOptions:{maxImageSize:nt,disableFontFace:At,ignoreErrors:rt,isEvalSupported:ut,isOffscreenCanvasSupported:gt,canvasMaxAreaInBytes:mt,fontExtraProperties:bt,useSystemFonts:Nt,cMapUrl:Mt?J:null,standardFontDataUrl:Mt?it:null}},_t={ignoreErrors:rt,isEvalSupported:ut,disableFontFace:At,fontExtraProperties:bt,enableXfa:Ct,ownerDocument:St,disableAutoFetch:xt,pdfBug:kt,styleElement:wt};return k.promise.then(function(){if(i.destroyed)throw new Error("Loading aborted");const vt=X(k,Ht),Ut=new Promise(function(Bt){let Dt;L?Dt=new g.PDFDataTransportStream(L,{disableRange:Tt,disableStream:yt}):w||(Dt=(Ft=>_.isNodeJS?function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype}()&&(0,F.isValidFetchUrl)(Ft.url)?new t.PDFFetchStream(Ft):new c.PDFNodeStream(Ft):(0,F.isValidFetchUrl)(Ft.url)?new t.PDFFetchStream(Ft):new r.PDFNetworkStream(Ft))({url:p,length:Pt,httpHeaders:E,withCredentials:R,rangeChunkSize:x,disableRange:Tt,disableStream:yt})),Bt(Dt)});return Promise.all([vt,Ut]).then(function([Bt,Dt]){if(i.destroyed)throw new Error("Loading aborted");const zt=new u.MessageHandler(h,Bt,k.port),Ft=new ft(zt,i,Dt,_t,It);i._transport=Ft,zt.send("Ready",null)})}).catch(i._capability.reject),i},H=function(a){if(a instanceof URL)return a.href;try{return new URL(a,window.location).href}catch{if(_.isNodeJS&&typeof a=="string")return a}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")},G=function(a){if(_.isNodeJS&&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(0,_.stringToBytes)(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.")};V.d(et,{PDFDataRangeTransport:()=>Q,PDFWorker:()=>ht,build:()=>n,getDocument:()=>st,version:()=>e});var _=V(292),U=V(792),F=V(419),C=V(10),T=V(573),A=V(923),o=V(814),d=V(164),u=V(178),b=V(62),s=V(626),g=V(585),t=V(94),r=V(457),c=V(786),f=V(50),v=y([T,c]);[T,c]=v.then?(await v)():v;const S=65536,M=100,I=5e3,O=_.isNodeJS?T.NodeCanvasFactory:F.DOMCanvasFactory,N=_.isNodeJS?T.NodeCMapReaderFactory:F.DOMCMapReaderFactory,B=_.isNodeJS?T.NodeFilterFactory:F.DOMFilterFactory,q=_.isNodeJS?T.NodeStandardFontDataFactory:F.DOMStandardFontDataFactory;async function X(a,i){if(a.destroyed)throw new Error("Worker was destroyed");const h=await a.messageHandler.sendWithPromise("GetDocRequest",i,i.data?[i.data.buffer]:null);if(a.destroyed)throw new Error("Worker was destroyed");return h}class Y{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Y.#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(i){throw this._worker?.port&&delete this._worker._pendingDestroy,i}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class Q{constructor(i,h,p=!1,w=null){this.length=i,this.initialData=h,this.progressiveDone=p,this.contentDispositionFilename=w,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(i){this._rangeListeners.push(i)}addProgressListener(i){this._progressListeners.push(i)}addProgressiveReadListener(i){this._progressiveReadListeners.push(i)}addProgressiveDoneListener(i){this._progressiveDoneListeners.push(i)}onDataRange(i,h){for(const p of this._rangeListeners)p(i,h)}onDataProgress(i,h){this._readyCapability.promise.then(()=>{for(const p of this._progressListeners)p(i,h)})}onDataProgressiveRead(i){this._readyCapability.promise.then(()=>{for(const h of this._progressiveReadListeners)h(i)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const i of this._progressiveDoneListeners)i()})}transportReady(){this._readyCapability.resolve()}requestDataRange(i,h){(0,_.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class K{constructor(i,h){this._pdfInfo=i,this._transport=h}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,_.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(i){return this._transport.getPage(i)}getPageIndex(i){return this._transport.getPageIndex(i)}getDestinations(){return this._transport.getDestinations()}getDestination(i){return this._transport.getDestination(i)}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:i="display"}={}){const{renderingIntent:h}=this._transport.getRenderingIntent(i);return this._transport.getOptionalContentConfig(h)}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(i=!1){return this._transport.startCleanup(i||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}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 at{#t=null;#e=!1;constructor(i,h,p,w=!1){this._pageIndex=i,this._pageInfo=h,this._transport=p,this._stats=w?new F.StatTimer:null,this._pdfBug=w,this.commonObjs=p.commonObjs,this.objs=new Z,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:i,rotation:h=this.rotate,offsetX:p=0,offsetY:w=0,dontFlip:E=!1}={}){return new F.PageViewport({viewBox:this.view,scale:i,rotation:h,offsetX:p,offsetY:w,dontFlip:E})}getAnnotations({intent:i="display"}={}){const{renderingIntent:h}=this._transport.getRenderingIntent(i);return this._transport.getAnnotations(this._pageIndex,h)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,_.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:i,viewport:h,intent:p="display",annotationMode:w=_.AnnotationMode.ENABLE,transform:E=null,background:R=null,optionalContentConfigPromise:P=null,annotationCanvasMap:L=null,pageColors:x=null,printAnnotationStorage:k=null}){this._stats?.time("Overall");const D=this._transport.getRenderingIntent(p,w,k),{renderingIntent:j,cacheKey:J}=D;this.#e=!1,this.#n(),P||=this._transport.getOptionalContentConfig(j);let $=this._intentStates.get(J);$||($=Object.create(null),this._intentStates.set(J,$)),$.streamReaderCancelTimeout&&(clearTimeout($.streamReaderCancelTimeout),$.streamReaderCancelTimeout=null);const tt=!!(j&_.RenderingIntentFlag.PRINT);$.displayReadyCapability||($.displayReadyCapability=Promise.withResolvers(),$.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(D));const it=nt=>{$.renderTasks.delete(W),(this._maybeCleanupAfterRender||tt)&&(this.#e=!0),this.#s(!tt),nt?(W.capability.reject(nt),this._abortOperatorList({intentState:$,reason:nt instanceof Error?nt:new Error(nt)})):W.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},W=new l({callback:it,params:{canvasContext:i,viewport:h,transform:E,background:R},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:L,operatorList:$.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!tt,pdfBug:this._pdfBug,pageColors:x});($.renderTasks||=new Set).add(W);const rt=W.task;return Promise.all([$.displayReadyCapability.promise,P]).then(([nt,ut])=>{if(this.destroyed){it();return}if(this._stats?.time("Rendering"),!(ut.renderingIntent&j))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");W.initializeGraphics({transparency:nt,optionalContentConfig:ut}),W.operatorListChanged()}).catch(it),rt}getOperatorList({intent:i="display",annotationMode:h=_.AnnotationMode.ENABLE,printAnnotationStorage:p=null}={}){function w(){R.operatorList.lastChunk&&(R.opListReadCapability.resolve(R.operatorList),R.renderTasks.delete(P))}const E=this._transport.getRenderingIntent(i,h,p,!0);let R=this._intentStates.get(E.cacheKey);R||(R=Object.create(null),this._intentStates.set(E.cacheKey,R));let P;return R.opListReadCapability||(P=Object.create(null),P.operatorListChanged=w,R.opListReadCapability=Promise.withResolvers(),(R.renderTasks||=new Set).add(P),R.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(E)),R.opListReadCapability.promise}streamTextContent({includeMarkedContent:i=!1,disableNormalization:h=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:i===!0,disableNormalization:h===!0},{highWaterMark:100,size(w){return w.items.length}})}getTextContent(i={}){if(this._transport._htmlForXfa)return this.getXfa().then(p=>f.XfaText.textContent(p));const h=this.streamTextContent(i);return new Promise(function(p,w){function E(){R.read().then(function({value:L,done:x}){if(x){p(P);return}Object.assign(P.styles,L.styles),P.items.push(...L.items),E()},w)}const R=h.getReader(),P={items:[],styles:Object.create(null)};E()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const i=[];for(const h of this._intentStates.values())if(this._abortOperatorList({intentState:h,reason:new Error("Page was destroyed."),force:!0}),!h.opListReadCapability)for(const p of h.renderTasks)i.push(p.completed),p.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(i)}cleanup(i=!1){this.#e=!0;const h=this.#s(!1);return i&&h&&(this._stats&&=new F.StatTimer),h}#s(i=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(i)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},I),!1;for(const{renderTasks:h,operatorList:p}of this._intentStates.values())if(h.size>0||!p.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#n(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(i,h){const p=this._intentStates.get(h);p&&(this._stats?.timeEnd("Page Request"),p.displayReadyCapability?.resolve(i))}_renderPageChunk(i,h){for(let p=0,w=i.length;p{P.read().then(({value:k,done:D})=>{if(D){L.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(k,L),x())},k=>{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(k);else if(L.opListReadCapability)L.opListReadCapability.reject(k);else throw k}})};x()}_abortOperatorList({intentState:i,reason:h,force:p=!1}){if(i.streamReader){if(i.streamReaderCancelTimeout&&(clearTimeout(i.streamReaderCancelTimeout),i.streamReaderCancelTimeout=null),!p){if(i.renderTasks.size>0)return;if(h instanceof F.RenderingCancelledException){let w=M;h.extraDelay>0&&h.extraDelay<1e3&&(w+=h.extraDelay),i.streamReaderCancelTimeout=setTimeout(()=>{i.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:i,reason:h,force:!0})},w);return}}if(i.streamReader.cancel(new _.AbortException(h.message)).catch(()=>{}),i.streamReader=null,!this._transport.destroyed){for(const[w,E]of this._intentStates)if(E===i){this._intentStates.delete(w);break}this.cleanup()}}}get stats(){return this._stats}}class ot{#t=new Set;#e=Promise.resolve();postMessage(i,h){const p={data:structuredClone(i,h?{transfer:h}:null)};this.#e.then(()=>{for(const w of this.#t)w.call(this,p)})}addEventListener(i,h){this.#t.add(h)}removeEventListener(i,h){this.#t.delete(h)}terminate(){this.#t.clear()}}const lt={isWorkerDisabled:!1,fakeWorkerId:0};_.isNodeJS&&(lt.isWorkerDisabled=!0,d.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),lt.isSameOrigin=function(a,i){let h;try{if(h=new URL(a),!h.origin||h.origin==="null")return!1}catch{return!1}const p=new URL(i,h);return h.origin===p.origin},lt.createCDNWrapper=function(a){const i=`await import("${a}");`;return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))};class ht{static#t;constructor({name:i=null,port:h=null,verbosity:p=(0,_.getVerbosityLevel)()}={}){if(this.name=i,this.destroyed=!1,this.verbosity=p,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,h){if(ht.#t?.has(h))throw new Error("Cannot use more than one PDFWorker per port.");(ht.#t||=new WeakMap).set(h,this),this._initializeFromPort(h);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(i){this._port=i,this._messageHandler=new u.MessageHandler("main","worker",i),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!lt.isWorkerDisabled&&!ht.#e){let{workerSrc:i}=ht;try{lt.isSameOrigin(window.location.href,i)||(i=lt.createCDNWrapper(new URL(i,window.location).href));const h=new Worker(i,{type:"module"}),p=new u.MessageHandler("main","worker",h),w=()=>{h.removeEventListener("error",E),p.destroy(),h.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},E=()=>{this._webWorker||w()};h.addEventListener("error",E),p.on("test",P=>{if(h.removeEventListener("error",E),this.destroyed){w();return}P?(this._messageHandler=p,this._port=h,this._webWorker=h,this._readyCapability.resolve(),p.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),p.destroy(),h.terminate())}),p.on("ready",P=>{if(h.removeEventListener("error",E),this.destroyed){w();return}try{R()}catch{this._setupFakeWorker()}});const R=()=>{const P=new Uint8Array;p.send("test",P,[P.buffer])};R();return}catch{(0,_.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){lt.isWorkerDisabled||((0,_.warn)("Setting up fake worker."),lt.isWorkerDisabled=!0),ht._setupFakeWorkerGlobal.then(i=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const h=new ot;this._port=h;const p=`fake${lt.fakeWorkerId++}`,w=new u.MessageHandler(p+"_worker",p,h);i.setup(w,h);const E=new u.MessageHandler(p,p+"_worker",h);this._messageHandler=E,this._readyCapability.resolve(),E.send("configure",{verbosity:this.verbosity})}).catch(i=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${i.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),ht.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(i){if(!i?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const h=this.#t?.get(i.port);if(h){if(h._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return h}return new ht(i)}static get workerSrc(){if(d.GlobalWorkerOptions.workerSrc)return d.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){const i=async()=>this.#e?this.#e:(await Rt(()=>import(this.workerSrc),[])).WorkerMessageHandler;return(0,_.shadow)(this,"_setupFakeWorkerGlobal",i())}}class ft{#t=new Map;#e=new Map;#s=new Map;#n=null;constructor(i,h,p,w,E){this.messageHandler=i,this.loadingTask=h,this.commonObjs=new Z,this.fontLoader=new C.FontLoader({ownerDocument:w.ownerDocument,styleElement:w.styleElement}),this._params=w,this.canvasFactory=E.canvasFactory,this.filterFactory=E.filterFactory,this.cMapReaderFactory=E.cMapReaderFactory,this.standardFontDataFactory=E.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=p,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(i,h=null){const p=this.#t.get(i);if(p)return p;const w=this.messageHandler.sendWithPromise(i,h);return this.#t.set(i,w),w}get annotationStorage(){return(0,_.shadow)(this,"annotationStorage",new U.AnnotationStorage)}getRenderingIntent(i,h=_.AnnotationMode.ENABLE,p=null,w=!1){let E=_.RenderingIntentFlag.DISPLAY,R=U.SerializableEmpty;switch(i){case"any":E=_.RenderingIntentFlag.ANY;break;case"display":break;case"print":E=_.RenderingIntentFlag.PRINT;break;default:(0,_.warn)(`getRenderingIntent - invalid intent: ${i}`)}switch(h){case _.AnnotationMode.DISABLE:E+=_.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case _.AnnotationMode.ENABLE:break;case _.AnnotationMode.ENABLE_FORMS:E+=_.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case _.AnnotationMode.ENABLE_STORAGE:E+=_.RenderingIntentFlag.ANNOTATIONS_STORAGE,R=(E&_.RenderingIntentFlag.PRINT&&p instanceof U.PrintAnnotationStorage?p:this.annotationStorage).serializable;break;default:(0,_.warn)(`getRenderingIntent - invalid annotationMode: ${h}`)}return w&&(E+=_.RenderingIntentFlag.OPLIST),{renderingIntent:E,cacheKey:`${E}_${R.hash}`,annotationStorageSerializable:R}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));const i=[];for(const p of this.#e.values())i.push(p._destroy());this.#e.clear(),this.#s.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const h=this.messageHandler.sendWithPromise("Terminate",null);return i.push(h),Promise.all(i).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,o.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new _.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:i,loadingTask:h}=this;i.on("GetReader",(p,w)=>{(0,_.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=E=>{this._lastProgress={loaded:E.loaded,total:E.total}},w.onPull=()=>{this._fullReader.read().then(function({value:E,done:R}){if(R){w.close();return}(0,_.assert)(E instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),w.enqueue(new Uint8Array(E),1,[E])}).catch(E=>{w.error(E)})},w.onCancel=E=>{this._fullReader.cancel(E),w.ready.catch(R=>{if(!this.destroyed)throw R})}}),i.on("ReaderHeadersReady",p=>{const w=Promise.withResolvers(),E=this._fullReader;return E.headersReady.then(()=>{(!E.isStreamingSupported||!E.isRangeSupported)&&(this._lastProgress&&h.onProgress?.(this._lastProgress),E.onProgress=R=>{h.onProgress?.({loaded:R.loaded,total:R.total})}),w.resolve({isStreamingSupported:E.isStreamingSupported,isRangeSupported:E.isRangeSupported,contentLength:E.contentLength})},w.reject),w.promise}),i.on("GetRangeReader",(p,w)=>{(0,_.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const E=this._networkStream.getRangeReader(p.begin,p.end);if(!E){w.close();return}w.onPull=()=>{E.read().then(function({value:R,done:P}){if(P){w.close();return}(0,_.assert)(R instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),w.enqueue(new Uint8Array(R),1,[R])}).catch(R=>{w.error(R)})},w.onCancel=R=>{E.cancel(R),w.ready.catch(P=>{if(!this.destroyed)throw P})}}),i.on("GetDoc",({pdfInfo:p})=>{this._numPages=p.numPages,this._htmlForXfa=p.htmlForXfa,delete p.htmlForXfa,h._capability.resolve(new K(p,this))}),i.on("DocException",function(p){let w;switch(p.name){case"PasswordException":w=new _.PasswordException(p.message,p.code);break;case"InvalidPDFException":w=new _.InvalidPDFException(p.message);break;case"MissingPDFException":w=new _.MissingPDFException(p.message);break;case"UnexpectedResponseException":w=new _.UnexpectedResponseException(p.message,p.status);break;case"UnknownErrorException":w=new _.UnknownErrorException(p.message,p.details);break;default:(0,_.unreachable)("DocException - expected a valid Error.")}h._capability.reject(w)}),i.on("PasswordRequest",p=>{if(this.#n=Promise.withResolvers(),h.onPassword){const w=E=>{E instanceof Error?this.#n.reject(E):this.#n.resolve({password:E})};try{h.onPassword(w,p.code)}catch(E){this.#n.reject(E)}}else this.#n.reject(new _.PasswordException(p.message,p.code));return this.#n.promise}),i.on("DataLoaded",p=>{h.onProgress?.({loaded:p.length,total:p.length}),this.downloadInfoCapability.resolve(p)}),i.on("StartRenderPage",p=>{if(this.destroyed)return;this.#e.get(p.pageIndex)._startRenderPage(p.transparency,p.cacheKey)}),i.on("commonobj",([p,w,E])=>{if(this.destroyed||this.commonObjs.has(p))return null;switch(w){case"Font":const R=this._params;if("error"in E){const k=E.error;(0,_.warn)(`Error during font loading: ${k}`),this.commonObjs.resolve(p,k);break}const P=R.pdfBug&&globalThis.FontInspector?.enabled?(k,D)=>globalThis.FontInspector.fontAdded(k,D):null,L=new C.FontFaceObject(E,{isEvalSupported:R.isEvalSupported,disableFontFace:R.disableFontFace,ignoreErrors:R.ignoreErrors,inspectFont:P});this.fontLoader.bind(L).catch(()=>i.sendWithPromise("FontFallback",{id:p})).finally(()=>{!R.fontExtraProperties&&L.data&&(L.data=null),this.commonObjs.resolve(p,L)});break;case"CopyLocalImage":const{imageRef:x}=E;(0,_.assert)(x,"The imageRef must be defined.");for(const k of this.#e.values())for(const[,D]of k.objs)if(D.ref===x)return D.dataLen?(this.commonObjs.resolve(p,structuredClone(D)),D.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(p,E);break;default:throw new Error(`Got unknown common object type ${w}`)}return null}),i.on("obj",([p,w,E,R])=>{if(this.destroyed)return;const P=this.#e.get(w);if(!P.objs.has(p)){if(P._intentStates.size===0){R?.bitmap?.close();return}switch(E){case"Image":P.objs.resolve(p,R),R?.dataLen>_.MAX_IMAGE_SIZE_TO_CACHE&&(P._maybeCleanupAfterRender=!0);break;case"Pattern":P.objs.resolve(p,R);break;default:throw new Error(`Got unknown object type ${E}`)}}}),i.on("DocProgress",p=>{this.destroyed||h.onProgress?.({loaded:p.loaded,total:p.total})}),i.on("FetchBuiltInCMap",p=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(p):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),i.on("FetchStandardFontData",p=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(p):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,_.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:i,transfer:h}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:i,filename:this._fullReader?.filename??null},h).finally(()=>{this.annotationStorage.resetModified()})}getPage(i){if(!Number.isInteger(i)||i<=0||i>this._numPages)return Promise.reject(new Error("Invalid page request."));const h=i-1,p=this.#s.get(h);if(p)return p;const w=this.messageHandler.sendWithPromise("GetPage",{pageIndex:h}).then(E=>{if(this.destroyed)throw new Error("Transport destroyed");const R=new at(h,E,this,this._params.pdfBug);return this.#e.set(h,R),R});return this.#s.set(h,w),w}getPageIndex(i){return typeof i!="object"||i===null||!Number.isInteger(i.num)||i.num<0||!Number.isInteger(i.gen)||i.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:i.num,gen:i.gen})}getAnnotations(i,h){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:i,intent:h})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(i){return typeof i!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:i})}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.#r("GetDocJSActions")}getPageJSActions(i){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:i})}getStructTree(i){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:i})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(i){return this.#r("GetOptionalContentConfig").then(h=>new s.OptionalContentConfig(h,i))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const i="GetMetadata",h=this.#t.get(i);if(h)return h;const p=this.messageHandler.sendWithPromise(i,null).then(w=>({info:w[0],metadata:w[1]?new b.Metadata(w[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(i,p),p}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(i=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const h of this.#e.values())if(!h.cleanup())throw new Error(`startCleanup: Page ${h.pageNumber} is currently rendering.`);this.commonObjs.clear(),i||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,o.cleanupTextLayer)()}}get loadingParams(){const{disableAutoFetch:i,enableXfa:h}=this._params;return(0,_.shadow)(this,"loadingParams",{disableAutoFetch:i,enableXfa:h})}}const ct=Symbol("INITIAL_DATA");class Z{#t=Object.create(null);#e(i){return this.#t[i]||={...Promise.withResolvers(),data:ct}}get(i,h=null){if(h){const w=this.#e(i);return w.promise.then(()=>h(w.data)),null}const p=this.#t[i];if(!p||p.data===ct)throw new Error(`Requesting object that isn't resolved yet ${i}.`);return p.data}has(i){const h=this.#t[i];return!!h&&h.data!==ct}resolve(i,h=null){const p=this.#e(i);p.data=h,p.resolve()}clear(){for(const i in this.#t){const{data:h}=this.#t[i];h?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const i in this.#t){const{data:h}=this.#t[i];h!==ct&&(yield[i,h])}}}class m{#t=null;constructor(i){this.#t=i,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(i=0){this.#t.cancel(null,i)}get separateAnnots(){const{separateAnnots:i}=this.#t.operatorList;if(!i)return!1;const{annotationCanvasMap:h}=this.#t;return i.form||i.canvas&&h?.size>0}}class l{static#t=new WeakSet;constructor({callback:i,params:h,objs:p,commonObjs:w,annotationCanvasMap:E,operatorList:R,pageIndex:P,canvasFactory:L,filterFactory:x,useRequestAnimationFrame:k=!1,pdfBug:D=!1,pageColors:j=null}){this.callback=i,this.params=h,this.objs=p,this.commonObjs=w,this.annotationCanvasMap=E,this.operatorListIdx=null,this.operatorList=R,this._pageIndex=P,this.canvasFactory=L,this.filterFactory=x,this._pdfBug=D,this.pageColors=j,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=k===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new m(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=h.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:i=!1,optionalContentConfig:h}){if(this.cancelled)return;if(this._canvas){if(l.#t.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.");l.#t.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:p,viewport:w,transform:E,background:R}=this.params;this.gfx=new A.CanvasGraphics(p,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:h},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:E,viewport:w,transparency:i,background:R}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(i=null,h=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),l.#t.delete(this._canvas),this.callback(i||new F.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,h))}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?window.requestAnimationFrame(()=>{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(),l.#t.delete(this._canvas),this.callback())))}}const e="4.1.392",n="fcb76a78d";z()}catch(S){z(S)}})},583:(dt,et,V)=>{V.d(et,{BaseCMapReaderFactory:()=>U,BaseCanvasFactory:()=>_,BaseFilterFactory:()=>z,BaseSVGFactory:()=>C,BaseStandardFontDataFactory:()=>F});var y=V(292);class z{constructor(){this.constructor===z&&(0,y.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(A){return"none"}addHCMFilter(A,o){return"none"}addHighlightHCMFilter(A,o,d,u,b){return"none"}destroy(A=!1){}}class _{constructor(){this.constructor===_&&(0,y.unreachable)("Cannot initialize BaseCanvasFactory.")}create(A,o){if(A<=0||o<=0)throw new Error("Invalid canvas size");const d=this._createCanvas(A,o);return{canvas:d,context:d.getContext("2d")}}reset(A,o,d){if(!A.canvas)throw new Error("Canvas is not specified");if(o<=0||d<=0)throw new Error("Invalid canvas size");A.canvas.width=o,A.canvas.height=d}destroy(A){if(!A.canvas)throw new Error("Canvas is not specified");A.canvas.width=0,A.canvas.height=0,A.canvas=null,A.context=null}_createCanvas(A,o){(0,y.unreachable)("Abstract method `_createCanvas` called.")}}class U{constructor({baseUrl:A=null,isCompressed:o=!0}){this.constructor===U&&(0,y.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=A,this.isCompressed=o}async fetch({name:A}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!A)throw new Error("CMap name must be specified.");const o=this.baseUrl+A+(this.isCompressed?".bcmap":""),d=this.isCompressed?y.CMapCompressionType.BINARY:y.CMapCompressionType.NONE;return this._fetchData(o,d).catch(u=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${o}`)})}_fetchData(A,o){(0,y.unreachable)("Abstract method `_fetchData` called.")}}class F{constructor({baseUrl:A=null}){this.constructor===F&&(0,y.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=A}async fetch({filename:A}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!A)throw new Error("Font filename must be specified.");const o=`${this.baseUrl}${A}`;return this._fetchData(o).catch(d=>{throw new Error(`Unable to load font data at: ${o}`)})}_fetchData(A){(0,y.unreachable)("Abstract method `_fetchData` called.")}}class C{constructor(){this.constructor===C&&(0,y.unreachable)("Cannot initialize BaseSVGFactory.")}create(A,o,d=!1){if(A<=0||o<=0)throw new Error("Invalid SVG dimensions");const u=this._createSVG("svg:svg");return u.setAttribute("version","1.1"),d||(u.setAttribute("width",`${A}px`),u.setAttribute("height",`${o}px`)),u.setAttribute("preserveAspectRatio","none"),u.setAttribute("viewBox",`0 0 ${A} ${o}`),u}createElement(A){if(typeof A!="string")throw new Error("Invalid SVG element type");return this._createSVG(A)}_createSVG(A){(0,y.unreachable)("Abstract method `_createSVG` called.")}}},923:(dt,et,V)=>{V.d(et,{CanvasGraphics:()=>m});var y=V(292),z=V(419);const _={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function U(l,e){if(!e)return;const n=e[2]-e[0],a=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],n,a),l.clip(i)}class F{constructor(){this.constructor===F&&(0,y.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,y.unreachable)("Abstract method `getPattern` called.")}}class C extends F{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}_createGradient(e){let n;this._type==="axial"?n=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(n=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const a of this._colorStops)n.addColorStop(a[0],a[1]);return n}getPattern(e,n,a,i){let h;if(i===_.STROKE||i===_.FILL){const p=n.current.getClippedPathBoundingBox(i,(0,z.getCurrentTransform)(e))||[0,0,0,0],w=Math.ceil(p[2]-p[0])||1,E=Math.ceil(p[3]-p[1])||1,R=n.cachedCanvases.getCanvas("pattern",w,E,!0),P=R.context;P.clearRect(0,0,P.canvas.width,P.canvas.height),P.beginPath(),P.rect(0,0,P.canvas.width,P.canvas.height),P.translate(-p[0],-p[1]),a=y.Util.transform(a,[1,0,0,1,p[0],p[1]]),P.transform(...n.baseTransform),this.matrix&&P.transform(...this.matrix),U(P,this._bbox),P.fillStyle=this._createGradient(P),P.fill(),h=e.createPattern(R.canvas,"no-repeat");const L=new DOMMatrix(a);h.setTransform(L)}else U(e,this._bbox),h=this._createGradient(e);return h}}function T(l,e,n,a,i,h,p,w){const E=e.coords,R=e.colors,P=l.data,L=l.width*4;let x;E[n+1]>E[a+1]&&(x=n,n=a,a=x,x=h,h=p,p=x),E[a+1]>E[i+1]&&(x=a,a=i,i=x,x=p,p=w,w=x),E[n+1]>E[a+1]&&(x=n,n=a,a=x,x=h,h=p,p=x);const k=(E[n]+e.offsetX)*e.scaleX,D=(E[n+1]+e.offsetY)*e.scaleY,j=(E[a]+e.offsetX)*e.scaleX,J=(E[a+1]+e.offsetY)*e.scaleY,$=(E[i]+e.offsetX)*e.scaleX,tt=(E[i+1]+e.offsetY)*e.scaleY;if(D>=tt)return;const it=R[h],W=R[h+1],rt=R[h+2],nt=R[p],ut=R[p+1],gt=R[p+2],mt=R[w],At=R[w+1],bt=R[w+2],Ct=Math.round(D),St=Math.round(tt);let Tt,yt,xt,kt,Pt,Nt,Mt,Ot;for(let Et=Ct;Et<=St;Et++){if(Ettt?vt=1:J===tt?vt=0:vt=(J-Et)/(J-tt),Tt=j-(j-$)*vt,yt=nt-(nt-mt)*vt,xt=ut-(ut-At)*vt,kt=gt-(gt-bt)*vt}let wt;Ettt?wt=1:wt=(D-Et)/(D-tt),Pt=k-(k-$)*wt,Nt=it-(it-mt)*wt,Mt=W-(W-At)*wt,Ot=rt-(rt-bt)*wt;const It=Math.round(Math.min(Tt,Pt)),Ht=Math.round(Math.max(Tt,Pt));let _t=L*Et+It*4;for(let vt=It;vt<=Ht;vt++)wt=(Tt-vt)/(Tt-Pt),wt<0?wt=0:wt>1&&(wt=1),P[_t++]=yt-(yt-Nt)*wt|0,P[_t++]=xt-(xt-Mt)*wt|0,P[_t++]=kt-(kt-Ot)*wt|0,P[_t++]=255}}function A(l,e,n){const a=e.coords,i=e.colors;let h,p;switch(e.type){case"lattice":const w=e.verticesPerRow,E=Math.floor(a.length/w)-1,R=w-1;for(h=0;h=i?h=i:a=h/e,{scale:a,size:h}}clipBbox(e,n,a,i,h){const p=i-n,w=h-a;e.ctx.rect(n,a,p,w),e.current.updateRectMinMax((0,z.getCurrentTransform)(e.ctx),[n,a,i,h]),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,n,a){const i=e.ctx,h=e.current;switch(n){case b.COLORED:const p=this.ctx;i.fillStyle=p.fillStyle,i.strokeStyle=p.strokeStyle,h.fillColor=p.fillStyle,h.strokeColor=p.strokeStyle;break;case b.UNCOLORED:const w=y.Util.makeHexColor(a[0],a[1],a[2]);i.fillStyle=w,i.strokeStyle=w,h.fillColor=w,h.strokeColor=w;break;default:throw new y.FormatError(`Unsupported paint type: ${n}`)}}getPattern(e,n,a,i){let h=a;i!==_.SHADING&&(h=y.Util.transform(h,n.baseTransform),this.matrix&&(h=y.Util.transform(h,this.matrix)));const p=this.createPatternCanvas(n);let w=new DOMMatrix(h);w=w.translate(p.offsetX,p.offsetY),w=w.scale(1/p.scaleX,1/p.scaleY);const E=e.createPattern(p.canvas,"repeat");return E.setTransform(w),E}}function g({src:l,srcPos:e=0,dest:n,width:a,height:i,nonBlackColor:h=4294967295,inverseDecode:p=!1}){const w=y.FeatureTest.isLittleEndian?4278190080:255,[E,R]=p?[h,w]:[w,h],P=a>>3,L=a&7,x=l.length;n=new Uint32Array(n.buffer);let k=0;for(let D=0;D{l.save=l.__originalSave,l.restore=l.__originalRestore,l.rotate=l.__originalRotate,l.scale=l.__originalScale,l.translate=l.__originalTranslate,l.transform=l.__originalTransform,l.setTransform=l.__originalSetTransform,l.resetTransform=l.__originalResetTransform,l.clip=l.__originalClip,l.moveTo=l.__originalMoveTo,l.lineTo=l.__originalLineTo,l.bezierCurveTo=l.__originalBezierCurveTo,l.rect=l.__originalRect,l.closePath=l.__originalClosePath,l.beginPath=l.__originalBeginPath,delete l._removeMirroring},l.save=function(){e.save(),this.__originalSave()},l.restore=function(){e.restore(),this.__originalRestore()},l.translate=function(a,i){e.translate(a,i),this.__originalTranslate(a,i)},l.scale=function(a,i){e.scale(a,i),this.__originalScale(a,i)},l.transform=function(a,i,h,p,w,E){e.transform(a,i,h,p,w,E),this.__originalTransform(a,i,h,p,w,E)},l.setTransform=function(a,i,h,p,w,E){e.setTransform(a,i,h,p,w,E),this.__originalSetTransform(a,i,h,p,w,E)},l.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},l.rotate=function(a){e.rotate(a),this.__originalRotate(a)},l.clip=function(a){e.clip(a),this.__originalClip(a)},l.moveTo=function(n,a){e.moveTo(n,a),this.__originalMoveTo(n,a)},l.lineTo=function(n,a){e.lineTo(n,a),this.__originalLineTo(n,a)},l.bezierCurveTo=function(n,a,i,h,p,w){e.bezierCurveTo(n,a,i,h,p,w),this.__originalBezierCurveTo(n,a,i,h,p,w)},l.rect=function(n,a,i,h){e.rect(n,a,i,h),this.__originalRect(n,a,i,h)},l.closePath=function(){e.closePath(),this.__originalClosePath()},l.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}class O{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,n,a){let i;return this.cache[e]!==void 0?(i=this.cache[e],this.canvasFactory.reset(i,n,a)):(i=this.canvasFactory.create(n,a),this.cache[e]=i),i}delete(e){delete this.cache[e]}clear(){for(const e in this.cache){const n=this.cache[e];this.canvasFactory.destroy(n),delete this.cache[e]}}}function N(l,e,n,a,i,h,p,w,E,R){const[P,L,x,k,D,j]=(0,z.getCurrentTransform)(l);if(L===0&&x===0){const tt=p*P+D,it=Math.round(tt),W=w*k+j,rt=Math.round(W),nt=(p+E)*P+D,ut=Math.abs(Math.round(nt)-it)||1,gt=(w+R)*k+j,mt=Math.abs(Math.round(gt)-rt)||1;return l.setTransform(Math.sign(P),0,0,Math.sign(k),it,rt),l.drawImage(e,n,a,i,h,0,0,ut,mt),l.setTransform(P,L,x,k,D,j),[ut,mt]}if(P===0&&k===0){const tt=w*x+D,it=Math.round(tt),W=p*L+j,rt=Math.round(W),nt=(w+R)*x+D,ut=Math.abs(Math.round(nt)-it)||1,gt=(p+E)*L+j,mt=Math.abs(Math.round(gt)-rt)||1;return l.setTransform(0,Math.sign(L),Math.sign(x),0,it,rt),l.drawImage(e,n,a,i,h,0,0,mt,ut),l.setTransform(P,L,x,k,D,j),[mt,ut]}l.drawImage(e,n,a,i,h,p,w,E,R);const J=Math.hypot(P,L),$=Math.hypot(x,k);return[J*E,$*R]}function B(l){const{width:e,height:n}=l;if(e>S||n>S)return null;const a=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=e+1;let p=new Uint8Array(h*(n+1)),w,E,R;const P=e+7&-8;let L=new Uint8Array(P*n),x=0;for(const $ of l.data){let tt=128;for(;tt>0;)L[x++]=$&tt?0:255,tt>>=1}let k=0;for(x=0,L[x]!==0&&(p[0]=1,++k),E=1;E>2)+(L[x+1]?4:0)+(L[x-P+1]?8:0),i[$]&&(p[R+E]=i[$],++k),x++;if(L[x-P]!==L[x]&&(p[R+E]=L[x]?2:4,++k),k>a)return null}for(x=P*(n-1),R=w*h,L[x]!==0&&(p[R]=8,++k),E=1;Ea)return null;const D=new Int32Array([0,h,-1,0,-h,0,0,0,1]),j=new Path2D;for(w=0;k&&w<=n;w++){let $=w*h;const tt=$+e;for(;$>4,p[$]&=W>>2|W<<2),j.lineTo($%h,$/h|0),p[$]||--k}while(it!==$);--w}return L=null,p=null,function($){$.save(),$.scale(1/e,-1/n),$.translate(0,-n),$.fill(j),$.beginPath(),$.restore()}}class q{constructor(e,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=y.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=y.FONT_IDENTITY_MATRIX,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=y.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,e,n])}clone(){const e=Object.create(this);return e.clipBox=this.clipBox.slice(),e}setCurrentPoint(e,n){this.x=e,this.y=n}updatePathMinMax(e,n,a){[n,a]=y.Util.applyTransform([n,a],e),this.minX=Math.min(this.minX,n),this.minY=Math.min(this.minY,a),this.maxX=Math.max(this.maxX,n),this.maxY=Math.max(this.maxY,a)}updateRectMinMax(e,n){const a=y.Util.applyTransform(n,e),i=y.Util.applyTransform(n.slice(2),e),h=y.Util.applyTransform([n[0],n[3]],e),p=y.Util.applyTransform([n[2],n[1]],e);this.minX=Math.min(this.minX,a[0],i[0],h[0],p[0]),this.minY=Math.min(this.minY,a[1],i[1],h[1],p[1]),this.maxX=Math.max(this.maxX,a[0],i[0],h[0],p[0]),this.maxY=Math.max(this.maxY,a[1],i[1],h[1],p[1])}updateScalingPathMinMax(e,n){y.Util.scaleMinMax(e,n),this.minX=Math.min(this.minX,n[0]),this.minY=Math.min(this.minY,n[1]),this.maxX=Math.max(this.maxX,n[2]),this.maxY=Math.max(this.maxY,n[3])}updateCurvePathMinMax(e,n,a,i,h,p,w,E,R,P){const L=y.Util.bezierBoundingBox(n,a,i,h,p,w,E,R,P);P||this.updateRectMinMax(e,L)}getPathBoundingBox(e=_.FILL,n=null){const a=[this.minX,this.minY,this.maxX,this.maxY];if(e===_.STROKE){n||(0,y.unreachable)("Stroke bounding box must include transform.");const i=y.Util.singularValueDecompose2dScale(n),h=i[0]*this.lineWidth/2,p=i[1]*this.lineWidth/2;a[0]-=h,a[1]-=p,a[2]+=h,a[3]+=p}return a}updateClipFromPath(){const e=y.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(e){this.clipBox=e,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(e=_.FILL,n=null){return y.Util.intersect(this.clipBox,this.getPathBoundingBox(e,n))}}function st(l,e){if(typeof ImageData<"u"&&e instanceof ImageData){l.putImageData(e,0,0);return}const n=e.height,a=e.width,i=n%M,h=(n-i)/M,p=i===0?h:h+1,w=l.createImageData(a,M);let E=0,R;const P=e.data,L=w.data;let x,k,D,j;if(e.kind===y.ImageKind.GRAYSCALE_1BPP){const J=P.byteLength,$=new Uint32Array(L.buffer,0,L.byteLength>>2),tt=$.length,it=a+7>>3,W=4294967295,rt=y.FeatureTest.isLittleEndian?4278190080:255;for(x=0;xit?a:nt*8-7,mt=gt&-8;let At=0,bt=0;for(;ut>=1}for(;R=h&&(D=i,j=a*D),R=0,k=j;k--;)L[R++]=P[E++],L[R++]=P[E++],L[R++]=P[E++],L[R++]=255;l.putImageData(w,0,x*M)}else throw new Error(`bad image kind: ${e.kind}`)}function X(l,e){if(e.bitmap){l.drawImage(e.bitmap,0,0);return}const n=e.height,a=e.width,i=n%M,h=(n-i)/M,p=i===0?h:h+1,w=l.createImageData(a,M);let E=0;const R=e.data,P=w.data;for(let L=0;L>8,l[h-2]=l[h-2]*p+n*w>>8,l[h-1]=l[h-1]*p+a*w>>8}}}function Q(l,e,n){const a=l.length,i=1/255;for(let h=3;h>8]>>8:e[i]*h>>16}}function at(l,e,n,a,i,h,p,w,E,R,P){const L=!!h,x=L?h[0]:0,k=L?h[1]:0,D=L?h[2]:0,j=i==="Luminosity"?K:Q,$=Math.min(a,Math.ceil(1048576/n));for(let tt=0;ttv&&typeof a=="function",P=R?Date.now()+f:0;let L=0;const x=this.commonObjs,k=this.objs;let D;for(;;){if(i!==void 0&&w===i.nextBreakPoint)return i.breakIt(w,a),w;if(D=p[w],D!==y.OPS.dependency)this[D].apply(this,h[w]);else for(const j of h[w]){const J=j.startsWith("g_")?x:k;if(!J.has(j))return J.get(j,a),w}if(w++,w===E)return w;if(R&&++L>v){if(Date.now()>P)return a(),w;L=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();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 e of this._cachedBitmapsMap.values()){for(const n of e.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){const n=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=n}}}_scaleImage(e,n){const a=e.width,i=e.height;let h=Math.max(Math.hypot(n[0],n[1]),1),p=Math.max(Math.hypot(n[2],n[3]),1),w=a,E=i,R="prescale1",P,L;for(;h>2&&w>1||p>2&&E>1;){let x=w,k=E;h>2&&w>1&&(x=w>=16384?Math.floor(w/2)-1||1:Math.ceil(w/2),h/=w/x),p>2&&E>1&&(k=E>=16384?Math.floor(E/2)-1||1:Math.ceil(E)/2,p/=E/k),P=this.cachedCanvases.getCanvas(R,x,k),L=P.context,L.clearRect(0,0,x,k),L.drawImage(e,0,0,w,E,0,0,x,k),e=P.canvas,w=x,E=k,R=R==="prescale1"?"prescale2":"prescale1"}return{img:e,paintWidth:w,paintHeight:E}}_createMaskCanvas(e){const n=this.ctx,{width:a,height:i}=e,h=this.current.fillColor,p=this.current.patternFill,w=(0,z.getCurrentTransform)(n);let E,R,P,L;if((e.bitmap||e.data)&&e.count>1){const gt=e.bitmap||e.data.buffer;R=JSON.stringify(p?w:[w.slice(0,4),h]),E=this._cachedBitmapsMap.get(gt),E||(E=new Map,this._cachedBitmapsMap.set(gt,E));const mt=E.get(R);if(mt&&!p){const At=Math.round(Math.min(w[0],w[2])+w[4]),bt=Math.round(Math.min(w[1],w[3])+w[5]);return{canvas:mt,offsetX:At,offsetY:bt}}P=mt}P||(L=this.cachedCanvases.getCanvas("maskCanvas",a,i),X(L.context,e));let x=y.Util.transform(w,[1/a,0,0,-1/i,0,0]);x=y.Util.transform(x,[1,0,0,1,0,-i]);const[k,D,j,J]=y.Util.getAxialAlignedBoundingBox([0,0,a,i],x),$=Math.round(j-k)||1,tt=Math.round(J-D)||1,it=this.cachedCanvases.getCanvas("fillCanvas",$,tt),W=it.context,rt=k,nt=D;W.translate(-rt,-nt),W.transform(...x),P||(P=this._scaleImage(L.canvas,(0,z.getCurrentTransformInverse)(W)),P=P.img,E&&p&&E.set(R,P)),W.imageSmoothingEnabled=lt((0,z.getCurrentTransform)(W),e.interpolate),N(W,P,0,0,P.width,P.height,0,0,a,i),W.globalCompositeOperation="source-in";const ut=y.Util.transform((0,z.getCurrentTransformInverse)(W),[1,0,0,1,-rt,-nt]);return W.fillStyle=p?h.getPattern(n,this,ut,_.FILL):h,W.fillRect(0,0,a,i),E&&!p&&(this.cachedCanvases.delete("fillCanvas"),E.set(R,it.canvas)),{canvas:it.canvas,offsetX:Math.round(rt),offsetY:Math.round(nt)}}setLineWidth(e){e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(e){this.ctx.lineCap=ht[e]}setLineJoin(e){this.ctx.lineJoin=ft[e]}setMiterLimit(e){this.ctx.miterLimit=e}setDash(e,n){const a=this.ctx;a.setLineDash!==void 0&&(a.setLineDash(e),a.lineDashOffset=n)}setRenderingIntent(e){}setFlatness(e){}setGState(e){for(const[n,a]of e)switch(n){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=a;break;case"ca":this.current.fillAlpha=a,this.ctx.globalAlpha=a;break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask=a?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(a);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode():!this.current.activeSMask&&e&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const e=this.ctx.canvas.width,n=this.ctx.canvas.height,a="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(a,e,n);this.suspendedCtx=this.ctx,this.ctx=i.context;const h=this.ctx;h.setTransform(...(0,z.getCurrentTransform)(this.suspendedCtx)),H(this.suspendedCtx,h),I(h,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(),H(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,a=this.suspendedCtx;ot(a,n,this.ctx,e),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()}save(){this.inSMaskMode?(H(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const e=this.current;this.stateStack.push(e),this.current=e.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),H(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(e,n,a,i,h,p){this.ctx.transform(e,n,a,i,h,p),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,n,a){const i=this.ctx,h=this.current;let p=h.x,w=h.y,E,R;const P=(0,z.getCurrentTransform)(i),L=P[0]===0&&P[3]===0||P[1]===0&&P[2]===0,x=L?a.slice(0):null;for(let k=0,D=0,j=e.length;kr&&(R=r),this.current.fontSizeScale=n/R,this.ctx.font=`${E} ${w} ${R}px ${p}`}setTextRenderingMode(e){this.current.textRenderingMode=e}setTextRise(e){this.current.textRise=e}moveText(e,n){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=n}setLeadingMoveText(e,n){this.setLeading(-n),this.moveText(e,n)}setTextMatrix(e,n,a,i,h,p){this.current.textMatrix=[e,n,a,i,h,p],this.current.textMatrixScale=Math.hypot(e,n),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(e,n,a,i){const h=this.ctx,p=this.current,w=p.font,E=p.textRenderingMode,R=p.fontSize/p.fontSizeScale,P=E&y.TextRenderingMode.FILL_STROKE_MASK,L=!!(E&y.TextRenderingMode.ADD_TO_PATH_FLAG),x=p.patternFill&&!w.missingFile;let k;(w.disableFontFace||L||x)&&(k=w.getPathGenerator(this.commonObjs,e)),w.disableFontFace||x?(h.save(),h.translate(n,a),h.beginPath(),k(h,R),i&&h.setTransform(...i),(P===y.TextRenderingMode.FILL||P===y.TextRenderingMode.FILL_STROKE)&&h.fill(),(P===y.TextRenderingMode.STROKE||P===y.TextRenderingMode.FILL_STROKE)&&h.stroke(),h.restore()):((P===y.TextRenderingMode.FILL||P===y.TextRenderingMode.FILL_STROKE)&&h.fillText(e,n,a),(P===y.TextRenderingMode.STROKE||P===y.TextRenderingMode.FILL_STROKE)&&h.strokeText(e,n,a)),L&&(this.pendingTextPaths||=[]).push({transform:(0,z.getCurrentTransform)(h),x:n,y:a,fontSize:R,addToPath:k})}get isFontSubpixelAAEnabled(){const{context:e}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);e.scale(1.5,1),e.fillText("I",0,10);const n=e.getImageData(0,0,10,10).data;let a=!1;for(let i=3;i0&&n[i]<255){a=!0;break}return(0,y.shadow)(this,"isFontSubpixelAAEnabled",a)}showText(e){const n=this.current,a=n.font;if(a.isType3Font)return this.showType3Text(e);const i=n.fontSize;if(i===0)return;const h=this.ctx,p=n.fontSizeScale,w=n.charSpacing,E=n.wordSpacing,R=n.fontDirection,P=n.textHScale*R,L=e.length,x=a.vertical,k=x?1:-1,D=a.defaultVMetrics,j=i*n.fontMatrix[0],J=n.textRenderingMode===y.TextRenderingMode.FILL&&!a.disableFontFace&&!n.patternFill;h.save(),h.transform(...n.textMatrix),h.translate(n.x,n.y+n.textRise),R>0?h.scale(P,-1):h.scale(P,1);let $;if(n.patternFill){h.save();const nt=n.fillColor.getPattern(h,this,(0,z.getCurrentTransformInverse)(h),_.FILL);$=(0,z.getCurrentTransform)(h),h.restore(),h.fillStyle=nt}let tt=n.lineWidth;const it=n.textMatrixScale;if(it===0||tt===0){const nt=n.textRenderingMode&y.TextRenderingMode.FILL_STROKE_MASK;(nt===y.TextRenderingMode.STROKE||nt===y.TextRenderingMode.FILL_STROKE)&&(tt=this.getSinglePixelWidth())}else tt/=it;if(p!==1&&(h.scale(p,p),tt/=p),h.lineWidth=tt,a.isInvalidPDFjsFont){const nt=[];let ut=0;for(const gt of e)nt.push(gt.unicode),ut+=gt.width;h.fillText(nt.join(""),0,0),n.x+=ut*j*P,h.restore(),this.compose();return}let W=0,rt;for(rt=0;rt0){const yt=h.measureText(mt).width*1e3/i*p;if(Stnew m(p,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new s(e,a,this.ctx,h,i)}else n=this._getPattern(e[1],e[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(e,n,a){const i=y.Util.makeHexColor(e,n,a);this.ctx.strokeStyle=i,this.current.strokeColor=i}setFillRGBColor(e,n,a){const i=y.Util.makeHexColor(e,n,a);this.ctx.fillStyle=i,this.current.fillColor=i,this.current.patternFill=!1}_getPattern(e,n=null){let a;return this.cachedPatterns.has(e)?a=this.cachedPatterns.get(e):(a=u(this.getObject(e)),this.cachedPatterns.set(e,a)),n&&(a.matrix=n),a}shadingFill(e){if(!this.contentVisible)return;const n=this.ctx;this.save();const a=this._getPattern(e);n.fillStyle=a.getPattern(n,this,(0,z.getCurrentTransformInverse)(n),_.SHADING);const i=(0,z.getCurrentTransformInverse)(n);if(i){const{width:h,height:p}=n.canvas,[w,E,R,P]=y.Util.getAxialAlignedBoundingBox([0,0,h,p],i);this.ctx.fillRect(w,E,R-w,P-E)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,y.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,y.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(e,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(e)&&e.length===6&&this.transform(...e),this.baseTransform=(0,z.getCurrentTransform)(this.ctx),n)){const a=n[2]-n[0],i=n[3]-n[1];this.ctx.rect(n[0],n[1],a,i),this.current.updateRectMinMax((0,z.getCurrentTransform)(this.ctx),n),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;e.isolated||(0,y.info)("TODO: Support non-isolated groups."),e.knockout&&(0,y.warn)("Knockout groups not supported.");const a=(0,z.getCurrentTransform)(n);if(e.matrix&&n.transform(...e.matrix),!e.bbox)throw new Error("Bounding box is required.");let i=y.Util.getAxialAlignedBoundingBox(e.bbox,(0,z.getCurrentTransform)(n));const h=[0,0,n.canvas.width,n.canvas.height];i=y.Util.intersect(i,h)||[0,0,0,0];const p=Math.floor(i[0]),w=Math.floor(i[1]);let E=Math.max(Math.ceil(i[2])-p,1),R=Math.max(Math.ceil(i[3])-w,1),P=1,L=1;E>c&&(P=E/c,E=c),R>c&&(L=R/c,R=c),this.current.startNewPathAndClipBox([0,0,E,R]);let x="groupAt"+this.groupLevel;e.smask&&(x+="_smask_"+this.smaskCounter++%2);const k=this.cachedCanvases.getCanvas(x,E,R),D=k.context;D.scale(1/P,1/L),D.translate(-p,-w),D.transform(...a),e.smask?this.smaskStack.push({canvas:k.canvas,context:D,offsetX:p,offsetY:w,scaleX:P,scaleY:L,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(n.setTransform(1,0,0,1,0,0),n.translate(p,w),n.scale(P,L),n.save()),H(n,D),this.ctx=D,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(n),this.groupLevel++}endGroup(e){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,a=this.groupStack.pop();if(this.ctx=a,this.ctx.imageSmoothingEnabled=!1,e.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=(0,z.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const h=y.Util.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],i);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(h)}}beginAnnotation(e,n,a,i,h){if(this.#t(),G(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),Array.isArray(n)&&n.length===4){const p=n[2]-n[0],w=n[3]-n[1];if(h&&this.annotationCanvasMap){a=a.slice(),a[4]-=n[0],a[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=p,n[3]=w;const[E,R]=y.Util.singularValueDecompose2dScale((0,z.getCurrentTransform)(this.ctx)),{viewportScale:P}=this,L=Math.ceil(p*this.outputScaleX*P),x=Math.ceil(w*this.outputScaleY*P);this.annotationCanvas=this.canvasFactory.create(L,x);const{canvas:k,context:D}=this.annotationCanvas;this.annotationCanvasMap.set(e,k),this.annotationCanvas.savedCtx=this.ctx,this.ctx=D,this.ctx.save(),this.ctx.setTransform(E,0,0,-R,0,w*R),G(this.ctx)}else G(this.ctx),this.ctx.rect(n[0],n[1],p,w),this.ctx.clip(),this.endPath()}this.current=new q(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...a),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e){if(!this.contentVisible)return;const n=e.count;e=this.getObject(e.data,e),e.count=n;const a=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=B(e)),i.compiled)){i.compiled(a);return}const h=this._createMaskCanvas(e),p=h.canvas;a.save(),a.setTransform(1,0,0,1,0,0),a.drawImage(p,h.offsetX,h.offsetY),a.restore(),this.compose()}paintImageMaskXObjectRepeat(e,n,a=0,i=0,h,p){if(!this.contentVisible)return;e=this.getObject(e.data,e);const w=this.ctx;w.save();const E=(0,z.getCurrentTransform)(w);w.transform(n,a,i,h,0,0);const R=this._createMaskCanvas(e);w.setTransform(1,0,0,1,R.offsetX-E[4],R.offsetY-E[5]);for(let P=0,L=p.length;PL?P/L:1,w=R>L?R/L:1}}this._cachedScaleForStroking[0]=p,this._cachedScaleForStroking[1]=w}return this._cachedScaleForStroking}rescaleAndStroke(e){const{ctx:n}=this,{lineWidth:a}=this.current,[i,h]=this.getScaleForStroking();if(n.lineWidth=a||1,i===1&&h===1){n.stroke();return}const p=n.getLineDash();if(e&&n.save(),n.scale(i,h),p.length>0){const w=Math.max(i,h);n.setLineDash(p.map(E=>E/w)),n.lineDashOffset/=w}n.stroke(),e&&n.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}}for(const l in y.OPS)m.prototype[l]!==void 0&&(m.prototype[y.OPS[l]]=m.prototype[l])},419:(dt,et,V)=>{V.d(et,{DOMCMapReaderFactory:()=>A,DOMCanvasFactory:()=>C,DOMFilterFactory:()=>F,DOMSVGFactory:()=>d,DOMStandardFontDataFactory:()=>o,PDFDateString:()=>M,PageViewport:()=>u,PixelsPerInch:()=>U,RenderingCancelledException:()=>b,StatTimer:()=>c,fetchData:()=>T,getColorValues:()=>N,getCurrentTransform:()=>B,getCurrentTransformInverse:()=>q,getFilenameFromUrl:()=>t,getPdfFilenameFromUrl:()=>r,getRGB:()=>O,getXfaPageViewport:()=>I,isDataScheme:()=>s,isPdfFile:()=>g,isValidFetchUrl:()=>f,noContextMenu:()=>v,setLayerDimensions:()=>st});var y=V(583),z=V(292);const _="http://www.w3.org/2000/svg";class U{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}class F extends y.BaseFilterFactory{#t;#e;#s;#n;#r;#i=0;constructor({docId:H,ownerDocument:G=globalThis.document}={}){super(),this.#s=H,this.#n=G}get#a(){return this.#t||=new Map}get#l(){return this.#r||=new Map}get#h(){if(!this.#e){const H=this.#n.createElement("div"),{style:G}=H;G.visibility="hidden",G.contain="strict",G.width=G.height=0,G.position="absolute",G.top=G.left=0,G.zIndex=-1;const Y=this.#n.createElementNS(_,"svg");Y.setAttribute("width",0),Y.setAttribute("height",0),this.#e=this.#n.createElementNS(_,"defs"),H.append(Y),Y.append(this.#e),this.#n.body.append(H)}return this.#e}addFilter(H){if(!H)return"none";let G=this.#a.get(H);if(G)return G;let Y,Q,K,at;if(H.length===1){const ft=H[0],ct=new Array(256);for(let Z=0;Z<256;Z++)ct[Z]=ft[Z]/255;at=Y=Q=K=ct.join(",")}else{const[ft,ct,Z]=H,m=new Array(256),l=new Array(256),e=new Array(256);for(let n=0;n<256;n++)m[n]=ft[n]/255,l[n]=ct[n]/255,e[n]=Z[n]/255;Y=m.join(","),Q=l.join(","),K=e.join(","),at=`${Y}${Q}${K}`}if(G=this.#a.get(at),G)return this.#a.set(H,G),G;const ot=`g_${this.#s}_transfer_map_${this.#i++}`,lt=`url(#${ot})`;this.#a.set(H,lt),this.#a.set(at,lt);const ht=this.#u(ot);return this.#o(Y,Q,K,ht),lt}addHCMFilter(H,G){const Y=`${H}-${G}`,Q="base";let K=this.#l.get(Q);if(K?.key===Y||(K?(K.filter?.remove(),K.key=Y,K.url="none",K.filter=null):(K={key:Y,url:"none",filter:null},this.#l.set(Q,K)),!H||!G))return K.url;const at=this.#p(H);H=z.Util.makeHexColor(...at);const ot=this.#p(G);if(G=z.Util.makeHexColor(...ot),this.#h.style.color="",H==="#000000"&&G==="#ffffff"||H===G)return K.url;const lt=new Array(256);for(let m=0;m<=255;m++){const l=m/255;lt[m]=l<=.03928?l/12.92:((l+.055)/1.055)**2.4}const ht=lt.join(","),ft=`g_${this.#s}_hcm_filter`,ct=K.filter=this.#u(ft);this.#o(ht,ht,ht,ct),this.#d(ct);const Z=(m,l)=>{const e=at[m]/255,n=ot[m]/255,a=new Array(l+1);for(let i=0;i<=l;i++)a[i]=e+i/l*(n-e);return a.join(",")};return this.#o(Z(0,5),Z(1,5),Z(2,5),ct),K.url=`url(#${ft})`,K.url}addHighlightHCMFilter(H,G,Y,Q,K){const at=`${G}-${Y}-${Q}-${K}`;let ot=this.#l.get(H);if(ot?.key===at||(ot?(ot.filter?.remove(),ot.key=at,ot.url="none",ot.filter=null):(ot={key:at,url:"none",filter:null},this.#l.set(H,ot)),!G||!Y))return ot.url;const[lt,ht]=[G,Y].map(this.#p.bind(this));let ft=Math.round(.2126*lt[0]+.7152*lt[1]+.0722*lt[2]),ct=Math.round(.2126*ht[0]+.7152*ht[1]+.0722*ht[2]),[Z,m]=[Q,K].map(this.#p.bind(this));ct{const p=new Array(256),w=(ct-ft)/h,E=a/255,R=(i-a)/(255*h);let P=0;for(let L=0;L<=h;L++){const x=Math.round(ft+L*w),k=E+L*R;for(let D=P;D<=x;D++)p[D]=k;P=x+1}for(let L=P;L<256;L++)p[L]=p[P-1];return p.join(",")},e=`g_${this.#s}_hcm_${H}_filter`,n=ot.filter=this.#u(e);return this.#d(n),this.#o(l(Z[0],m[0],5),l(Z[1],m[1],5),l(Z[2],m[2],5),n),ot.url=`url(#${e})`,ot.url}destroy(H=!1){H&&this.#l.size!==0||(this.#e&&(this.#e.parentNode.parentNode.remove(),this.#e=null),this.#t&&(this.#t.clear(),this.#t=null),this.#i=0)}#d(H){const G=this.#n.createElementNS(_,"feColorMatrix");G.setAttribute("type","matrix"),G.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"),H.append(G)}#u(H){const G=this.#n.createElementNS(_,"filter");return G.setAttribute("color-interpolation-filters","sRGB"),G.setAttribute("id",H),this.#h.append(G),G}#c(H,G,Y){const Q=this.#n.createElementNS(_,G);Q.setAttribute("type","discrete"),Q.setAttribute("tableValues",Y),H.append(Q)}#o(H,G,Y,Q){const K=this.#n.createElementNS(_,"feComponentTransfer");Q.append(K),this.#c(K,"feFuncR",H),this.#c(K,"feFuncG",G),this.#c(K,"feFuncB",Y)}#p(H){return this.#h.style.color=H,O(getComputedStyle(this.#h).getPropertyValue("color"))}}class C extends y.BaseCanvasFactory{constructor({ownerDocument:H=globalThis.document}={}){super(),this._document=H}_createCanvas(H,G){const Y=this._document.createElement("canvas");return Y.width=H,Y.height=G,Y}}async function T(X,H="text"){if(f(X,document.baseURI)){const G=await fetch(X);if(!G.ok)throw new Error(G.statusText);switch(H){case"arraybuffer":return G.arrayBuffer();case"blob":return G.blob();case"json":return G.json()}return G.text()}return new Promise((G,Y)=>{const Q=new XMLHttpRequest;Q.open("GET",X,!0),Q.responseType=H,Q.onreadystatechange=()=>{if(Q.readyState===XMLHttpRequest.DONE){if(Q.status===200||Q.status===0){switch(H){case"arraybuffer":case"blob":case"json":G(Q.response);return}G(Q.responseText);return}Y(new Error(Q.statusText))}},Q.send(null)})}class A extends y.BaseCMapReaderFactory{_fetchData(H,G){return T(H,this.isCompressed?"arraybuffer":"text").then(Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,z.stringToBytes)(Y),compressionType:G}))}}class o extends y.BaseStandardFontDataFactory{_fetchData(H){return T(H,"arraybuffer").then(G=>new Uint8Array(G))}}class d extends y.BaseSVGFactory{_createSVG(H){return document.createElementNS(_,H)}}class u{constructor({viewBox:H,scale:G,rotation:Y,offsetX:Q=0,offsetY:K=0,dontFlip:at=!1}){this.viewBox=H,this.scale=G,this.rotation=Y,this.offsetX=Q,this.offsetY=K;const ot=(H[2]+H[0])/2,lt=(H[3]+H[1])/2;let ht,ft,ct,Z;switch(Y%=360,Y<0&&(Y+=360),Y){case 180:ht=-1,ft=0,ct=0,Z=1;break;case 90:ht=0,ft=1,ct=1,Z=0;break;case 270:ht=0,ft=-1,ct=-1,Z=0;break;case 0:ht=1,ft=0,ct=0,Z=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}at&&(ct=-ct,Z=-Z);let m,l,e,n;ht===0?(m=Math.abs(lt-H[1])*G+Q,l=Math.abs(ot-H[0])*G+K,e=(H[3]-H[1])*G,n=(H[2]-H[0])*G):(m=Math.abs(ot-H[0])*G+Q,l=Math.abs(lt-H[1])*G+K,e=(H[2]-H[0])*G,n=(H[3]-H[1])*G),this.transform=[ht*G,ft*G,ct*G,Z*G,m-ht*G*ot-ct*G*lt,l-ft*G*ot-Z*G*lt],this.width=e,this.height=n}get rawDims(){const{viewBox:H}=this;return(0,z.shadow)(this,"rawDims",{pageWidth:H[2]-H[0],pageHeight:H[3]-H[1],pageX:H[0],pageY:H[1]})}clone({scale:H=this.scale,rotation:G=this.rotation,offsetX:Y=this.offsetX,offsetY:Q=this.offsetY,dontFlip:K=!1}={}){return new u({viewBox:this.viewBox.slice(),scale:H,rotation:G,offsetX:Y,offsetY:Q,dontFlip:K})}convertToViewportPoint(H,G){return z.Util.applyTransform([H,G],this.transform)}convertToViewportRectangle(H){const G=z.Util.applyTransform([H[0],H[1]],this.transform),Y=z.Util.applyTransform([H[2],H[3]],this.transform);return[G[0],G[1],Y[0],Y[1]]}convertToPdfPoint(H,G){return z.Util.applyInverseTransform([H,G],this.transform)}}class b extends z.BaseException{constructor(H,G=0){super(H,"RenderingCancelledException"),this.extraDelay=G}}function s(X){const H=X.length;let G=0;for(;G=1&&Q<=12?Q-1:0;let K=parseInt(G[3],10);K=K>=1&&K<=31?K:1;let at=parseInt(G[4],10);at=at>=0&&at<=23?at:0;let ot=parseInt(G[5],10);ot=ot>=0&&ot<=59?ot:0;let lt=parseInt(G[6],10);lt=lt>=0&<<=59?lt:0;const ht=G[7]||"Z";let ft=parseInt(G[8],10);ft=ft>=0&&ft<=23?ft:0;let ct=parseInt(G[9],10)||0;return ct=ct>=0&&ct<=59?ct:0,ht==="-"?(at+=ft,ot+=ct):ht==="+"&&(at-=ft,ot-=ct),new Date(Date.UTC(Y,Q,K,at,ot,lt))}}function I(X,{scale:H=1,rotation:G=0}){const{width:Y,height:Q}=X.attributes.style,K=[0,0,parseInt(Y),parseInt(Q)];return new u({viewBox:K,scale:H,rotation:G})}function O(X){if(X.startsWith("#")){const H=parseInt(X.slice(1),16);return[(H&16711680)>>16,(H&65280)>>8,H&255]}return X.startsWith("rgb(")?X.slice(4,-1).split(",").map(H=>parseInt(H)):X.startsWith("rgba(")?X.slice(5,-1).split(",").map(H=>parseInt(H)).slice(0,3):((0,z.warn)(`Not a valid color format: "${X}"`),[0,0,0])}function N(X){const H=document.createElement("span");H.style.visibility="hidden",document.body.append(H);for(const G of X.keys()){H.style.color=G;const Y=window.getComputedStyle(H).color;X.set(G,O(Y))}H.remove()}function B(X){const{a:H,b:G,c:Y,d:Q,e:K,f:at}=X.getTransform();return[H,G,Y,Q,K,at]}function q(X){const{a:H,b:G,c:Y,d:Q,e:K,f:at}=X.getTransform().invertSelf();return[H,G,Y,Q,K,at]}function st(X,H,G=!1,Y=!0){if(H instanceof u){const{pageWidth:Q,pageHeight:K}=H.rawDims,{style:at}=X,ot=z.FeatureTest.isCSSRoundSupported,lt=`var(--scale-factor) * ${Q}px`,ht=`var(--scale-factor) * ${K}px`,ft=ot?`round(${lt}, 1px)`:`calc(${lt})`,ct=ot?`round(${ht}, 1px)`:`calc(${ht})`;!G||H.rotation%180===0?(at.width=ft,at.height=ct):(at.width=ct,at.height=ft)}Y&&X.setAttribute("data-main-rotation",H.rotation)}},47:(dt,et,V)=>{V.d(et,{DrawLayer:()=>_});var y=V(419),z=V(292);class _{#t=null;#e=0;#s=new Map;#n=new Map;constructor({pageIndex:F}){this.pageIndex=F}setParent(F){if(!this.#t){this.#t=F;return}if(this.#t!==F){if(this.#s.size>0)for(const C of this.#s.values())C.remove(),F.append(C);this.#t=F}}static get _svgFactory(){return(0,z.shadow)(this,"_svgFactory",new y.DOMSVGFactory)}static#r(F,{x:C=0,y:T=0,width:A=1,height:o=1}={}){const{style:d}=F;d.top=`${100*T}%`,d.left=`${100*C}%`,d.width=`${100*A}%`,d.height=`${100*o}%`}#i(F){const C=_._svgFactory.create(1,1,!0);return this.#t.append(C),C.setAttribute("aria-hidden",!0),_.#r(C,F),C}#a(F,C){const T=_._svgFactory.createElement("clipPath");F.append(T);const A=`clip_${C}`;T.setAttribute("id",A),T.setAttribute("clipPathUnits","objectBoundingBox");const o=_._svgFactory.createElement("use");return T.append(o),o.setAttribute("href",`#${C}`),o.classList.add("clip"),A}highlight(F,C,T,A=!1){const o=this.#e++,d=this.#i(F.box);d.classList.add("highlight"),F.free&&d.classList.add("free");const u=_._svgFactory.createElement("defs");d.append(u);const b=_._svgFactory.createElement("path");u.append(b);const s=`path_p${this.pageIndex}_${o}`;b.setAttribute("id",s),b.setAttribute("d",F.toSVGPath()),A&&this.#n.set(o,b);const g=this.#a(u,s),t=_._svgFactory.createElement("use");return d.append(t),d.setAttribute("fill",C),d.setAttribute("fill-opacity",T),t.setAttribute("href",`#${s}`),this.#s.set(o,d),{id:o,clipPathId:`url(#${g})`}}highlightOutline(F){const C=this.#e++,T=this.#i(F.box);T.classList.add("highlightOutline");const A=_._svgFactory.createElement("defs");T.append(A);const o=_._svgFactory.createElement("path");A.append(o);const d=`path_p${this.pageIndex}_${C}`;o.setAttribute("id",d),o.setAttribute("d",F.toSVGPath()),o.setAttribute("vector-effect","non-scaling-stroke");let u;if(F.free){T.classList.add("free");const g=_._svgFactory.createElement("mask");A.append(g),u=`mask_p${this.pageIndex}_${C}`,g.setAttribute("id",u),g.setAttribute("maskUnits","objectBoundingBox");const t=_._svgFactory.createElement("rect");g.append(t),t.setAttribute("width","1"),t.setAttribute("height","1"),t.setAttribute("fill","white");const r=_._svgFactory.createElement("use");g.append(r),r.setAttribute("href",`#${d}`),r.setAttribute("stroke","none"),r.setAttribute("fill","black"),r.setAttribute("fill-rule","nonzero"),r.classList.add("mask")}const b=_._svgFactory.createElement("use");T.append(b),b.setAttribute("href",`#${d}`),u&&b.setAttribute("mask",`url(#${u})`);const s=b.cloneNode();return T.append(s),b.classList.add("mainOutline"),s.classList.add("secondaryOutline"),this.#s.set(C,T),C}finalizeLine(F,C){const T=this.#n.get(F);this.#n.delete(F),this.updateBox(F,C.box),T.setAttribute("d",C.toSVGPath())}updateLine(F,C){this.#s.get(F).firstChild.firstChild.setAttribute("d",C.toSVGPath())}removeFreeHighlight(F){this.remove(F),this.#n.delete(F)}updatePath(F,C){this.#n.get(F).setAttribute("d",C.toSVGPath())}updateBox(F,C){_.#r(this.#s.get(F),C)}show(F,C){this.#s.get(F).classList.toggle("hidden",!C)}rotate(F,C){this.#s.get(F).setAttribute("data-main-rotation",C)}changeColor(F,C){this.#s.get(F).setAttribute("fill",C)}changeOpacity(F,C){this.#s.get(F).setAttribute("fill-opacity",C)}addClass(F,C){this.#s.get(F).classList.add(C)}removeClass(F,C){this.#s.get(F).classList.remove(C)}remove(F){this.#t!==null&&(this.#s.get(F).remove(),this.#s.delete(F))}destroy(){this.#t=null;for(const F of this.#s.values())F.remove();this.#s.clear()}}},731:(dt,et,V)=>{V.d(et,{AnnotationEditorLayer:()=>s});var y=V(292),z=V(310),_=V(830),U=V(976);const F=/\r\n?|\n/g;class C extends z.AnnotationEditor{#t=this.editorDivBlur.bind(this);#e=this.editorDivFocus.bind(this);#s=this.editorDivInput.bind(this);#n=this.editorDivKeydown.bind(this);#r=this.editorDivPaste.bind(this);#i;#a="";#l=`${this.id}-editor`;#h;#d=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=C.prototype,r=v=>v.isEmpty(),c=_.AnnotationEditorUIManager.TRANSLATE_SMALL,f=_.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,y.shadow)(this,"_keyboardManager",new _.KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-c,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-f,0],checker:r}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[c,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[f,0],checker:r}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-c],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-f],checker:r}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,c],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,f],checker:r}]]))}static _type="freetext";static _editorType=y.AnnotationEditorType.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#i=t.color||C._defaultColor||z.AnnotationEditor._defaultLineColor,this.#h=t.fontSize||C._defaultFontSize}static initialize(t,r){z.AnnotationEditor.initialize(t,r,{strings:["pdfjs-free-text-default-content"]});const c=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(c.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,r){switch(t){case y.AnnotationEditorParamsType.FREETEXT_SIZE:C._defaultFontSize=r;break;case y.AnnotationEditorParamsType.FREETEXT_COLOR:C._defaultColor=r;break}}updateParams(t,r){switch(t){case y.AnnotationEditorParamsType.FREETEXT_SIZE:this.#u(r);break;case y.AnnotationEditorParamsType.FREETEXT_COLOR:this.#c(r);break}}static get defaultPropertiesToUpdate(){return[[y.AnnotationEditorParamsType.FREETEXT_SIZE,C._defaultFontSize],[y.AnnotationEditorParamsType.FREETEXT_COLOR,C._defaultColor||z.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[y.AnnotationEditorParamsType.FREETEXT_SIZE,this.#h],[y.AnnotationEditorParamsType.FREETEXT_COLOR,this.#i]]}#u(t){const r=f=>{this.editorDiv.style.fontSize=`calc(${f}px * var(--scale-factor))`,this.translate(0,-(f-this.#h)*this.parentScale),this.#h=f,this.#p()},c=this.#h;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#c(t){const r=f=>{this.#i=this.editorDiv.style.color=f},c=this.#i;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,r){this._uiManager.translateSelectedEditors(t,r,!0)}getInitialTranslation(){const t=this.parentScale;return[-C._internalPadding*t,-(C._internalPadding+this.#h)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){this.isInEditMode()||(this.parent.setEditingState(!1),this.parent.updateToolbar(y.AnnotationEditorType.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.editorDiv.addEventListener("keydown",this.#n),this.editorDiv.addEventListener("focus",this.#e),this.editorDiv.addEventListener("blur",this.#t),this.editorDiv.addEventListener("input",this.#s),this.editorDiv.addEventListener("paste",this.#r))}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#l),this._isDraggable=!0,this.editorDiv.removeEventListener("keydown",this.#n),this.editorDiv.removeEventListener("focus",this.#e),this.editorDiv.removeEventListener("blur",this.#t),this.editorDiv.removeEventListener("input",this.#s),this.editorDiv.removeEventListener("paste",this.#r),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){this.width||(this.enableEditMode(),this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#o(){const t=[];this.editorDiv.normalize();for(const r of this.editorDiv.childNodes)t.push(C.#g(r));return t.join(` +`)}#p(){const[t,r]=this.parentDimensions;let c;if(this.isAttachedToDOM)c=this.div.getBoundingClientRect();else{const{currentLayer:f,div:v}=this,S=v.style.display;v.style.display="hidden",f.div.append(this.div),c=v.getBoundingClientRect(),v.remove(),v.style.display=S}this.rotation%180===this.parentRotation%180?(this.width=c.width/t,this.height=c.height/r):(this.width=c.height/t,this.height=c.width/r),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#a,r=this.#a=this.#o().trimEnd();if(t===r)return;const c=f=>{if(this.#a=f,!f){this.remove();return}this.#f(),this._uiManager.rebuild(this),this.#p()};this.addCommands({cmd:()=>{c(r)},undo:()=>{c(t)},mustExec:!1}),this.#p()}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){C._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,r;this.width&&(t=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#l),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text"),this.enableEditing(),z.AnnotationEditor._l10nPromise.get("pdfjs-free-text-default-content").then(f=>this.editorDiv?.setAttribute("default-content",f)),this.editorDiv.contentEditable=!0;const{style:c}=this.editorDiv;if(c.fontSize=`calc(${this.#h}px * var(--scale-factor))`,c.color=this.#i,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),(0,_.bindEvents)(this,this.div,["dblclick","keydown"]),this.width){const[f,v]=this.parentDimensions;if(this.annotationElementId){const{position:S}=this.#d;let[M,I]=this.getInitialTranslation();[M,I]=this.pageTranslationToScreen(M,I);const[O,N]=this.pageDimensions,[B,q]=this.pageTranslation;let st,X;switch(this.rotation){case 0:st=t+(S[0]-B)/O,X=r+this.height-(S[1]-q)/N;break;case 90:st=t+(S[0]-B)/O,X=r-(S[1]-q)/N,[M,I]=[I,-M];break;case 180:st=t-this.width+(S[0]-B)/O,X=r-(S[1]-q)/N,[M,I]=[-M,-I];break;case 270:st=t+(S[0]-B-this.height*N)/O,X=r+(S[1]-q-this.width*O)/N,[M,I]=[-I,M];break}this.setAt(st*f,X*v,M,I)}else this.setAt(t*f,r*v,this.width*f,this.height*v);this.#f(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#g(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(F,"")}editorDivPaste(t){const r=t.clipboardData||window.clipboardData,{types:c}=r;if(c.length===1&&c[0]==="text/plain")return;t.preventDefault();const f=C.#b(r.getData("text")||"").replaceAll(F,` +`);if(!f)return;const v=window.getSelection();if(!v.rangeCount)return;this.editorDiv.normalize(),v.deleteFromDocument();const S=v.getRangeAt(0);if(!f.includes(` +`)){S.insertNode(document.createTextNode(f)),this.editorDiv.normalize(),v.collapseToStart();return}const{startContainer:M,startOffset:I}=S,O=[],N=[];if(M.nodeType===Node.TEXT_NODE){const st=M.parentElement;if(N.push(M.nodeValue.slice(I).replaceAll(F,"")),st!==this.editorDiv){let X=O;for(const H of this.editorDiv.childNodes){if(H===st){X=N;continue}X.push(C.#g(H))}}O.push(M.nodeValue.slice(0,I).replaceAll(F,""))}else if(M===this.editorDiv){let st=O,X=0;for(const H of this.editorDiv.childNodes)X++===I&&(st=N),st.push(C.#g(H))}this.#a=`${O.join(` +`)}${f}${N.join(` +`)}`,this.#f();const B=new Range;let q=O.reduce((st,X)=>st+X.length,0);for(const{firstChild:st}of this.editorDiv.childNodes)if(st.nodeType===Node.TEXT_NODE){const X=st.nodeValue.length;if(q<=X){B.setStart(st,q),B.setEnd(st,q);break}q-=X}v.removeAllRanges(),v.addRange(B)}#f(){if(this.editorDiv.replaceChildren(),!!this.#a)for(const t of this.#a.split(` +`)){const r=document.createElement("div");r.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(r)}}#m(){return this.#a.replaceAll(" "," ")}static#b(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static deserialize(t,r,c){let f=null;if(t instanceof U.FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:S,fontColor:M},rect:I,rotation:O,id:N},textContent:B,textPosition:q,parent:{page:{pageNumber:st}}}=t;if(!B||B.length===0)return null;f=t={annotationType:y.AnnotationEditorType.FREETEXT,color:Array.from(M),fontSize:S,value:B.join(` +`),position:q,pageIndex:st-1,rect:I,rotation:O,id:N,deleted:!1}}const v=super.deserialize(t,r,c);return v.#h=t.fontSize,v.#i=y.Util.makeHexColor(...t.color),v.#a=C.#b(t.value),v.annotationElementId=t.id||null,v.#d=f,v}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};const r=C._internalPadding*this.parentScale,c=this.getRect(r,r),f=z.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#i),v={annotationType:y.AnnotationEditorType.FREETEXT,color:f,fontSize:this.#h,value:this.#m(),pageIndex:this.pageIndex,rect:c,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?v:this.annotationElementId&&!this.#A(v)?null:(v.id=this.annotationElementId,v)}#A(t){const{value:r,fontSize:c,color:f,pageIndex:v}=this.#d;return this._hasBeenMoved||t.value!==r||t.fontSize!==c||t.color.some((S,M)=>S!==f[M])||t.pageIndex!==v}}var T=V(61),A=V(259),o=V(419);class d extends z.AnnotationEditor{#t=null;#e=0;#s;#n=null;#r=null;#i=null;#a=null;#l=0;#h=null;#d=null;#u=null;#c=!1;#o=this.#T.bind(this);#p=null;#g;#f=null;#m="";#b;#A="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=y.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=d.prototype;return(0,y.shadow)(this,"_keyboardManager",new _.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||d._defaultColor,this.#b=t.thickness||d._defaultThickness,this.#g=t.opacity||d._defaultOpacity,this.#s=t.boxes||null,this.#A=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#c=!0,this.#E(t),this.#S()):(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#a=t.focusNode,this.#l=t.focusOffset,this.#w(),this.#S(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#c?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#b,methodOfCreation:this.#A}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#w(){const t=new T.Outliner(this.#s,.001);this.#d=t.getOutlines(),{x:this.x,y:this.y,width:this.width,height:this.height}=this.#d.box;const r=new T.Outliner(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#i=r.getOutlines();const{lastPoint:c}=this.#i.box;this.#p=[(c[0]-this.x)/this.width,(c[1]-this.y)/this.height]}#E({highlightOutlines:t,highlightId:r,clipPathId:c}){this.#d=t;const f=1.5;if(this.#i=t.getNewOutline(this.#b/2+f,.0025),r>=0)this.#u=r,this.#n=c,this.parent.drawLayer.finalizeLine(r,t),this.#f=this.parent.drawLayer.highlightOutline(this.#i);else if(this.parent){const N=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(this.#u,t),this.parent.drawLayer.updateBox(this.#u,d.#x(this.#d.box,(N-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#f,this.#i),this.parent.drawLayer.updateBox(this.#f,d.#x(this.#i.box,N))}const{x:v,y:S,width:M,height:I}=t.box;switch(this.rotation){case 0:this.x=v,this.y=S,this.width=M,this.height=I;break;case 90:{const[N,B]=this.parentDimensions;this.x=S,this.y=1-v,this.width=M*B/N,this.height=I*N/B;break}case 180:this.x=1-v,this.y=1-S,this.width=M,this.height=I;break;case 270:{const[N,B]=this.parentDimensions;this.x=1-S,this.y=v,this.width=M*B/N,this.height=I*N/B;break}}const{lastPoint:O}=this.#i.box;this.#p=[(O[0]-v)/M,(O[1]-S)/I]}static initialize(t,r){z.AnnotationEditor.initialize(t,r),d._defaultColor||=r.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,r){switch(t){case y.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:d._defaultColor=r;break;case y.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:d._defaultThickness=r;break}}translateInPage(t,r){}get toolbarPosition(){return this.#p}updateParams(t,r){switch(t){case y.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#L(r);break;case y.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#M(r);break}}static get defaultPropertiesToUpdate(){return[[y.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,d._defaultColor],[y.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,d._defaultThickness]]}get propertiesToUpdate(){return[[y.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||d._defaultColor],[y.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#b||d._defaultThickness],[y.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#c]]}#L(t){const r=f=>{this.color=f,this.parent?.drawLayer.changeColor(this.#u,f),this.#r?.updateColor(f)},c=this.color;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#M(t){const r=this.#b,c=f=>{this.#b=f,this.#y(f)};this.addCommands({cmd:c.bind(this,t),undo:c.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.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 A.ColorPicker({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.#k())}getBaseTranslation(){return[0,0]}getRect(t,r){return super.getRect(t,r,this.#k())}onceAdded(){this.parent.addUndoableEditor(this),this.div.focus()}remove(){this.#v(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#S(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let r=!1;this.parent&&!t?this.#v():t&&(this.#S(t),r=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),r&&this.select()}#y(t){if(!this.#c)return;this.#E({highlightOutlines:this.#d.getNewOutline(t/2)}),this.fixAndSetPosition();const[r,c]=this.parentDimensions;this.setDims(this.width*r,this.height*c)}#v(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#f),this.#f=null)}#S(t=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#n}=t.drawLayer.highlight(this.#d,this.color,this.#g),this.#f=t.drawLayer.highlightOutline(this.#i),this.#h&&(this.#h.style.clipPath=this.#n))}static#x({x:t,y:r,width:c,height:f},v){switch(v){case 90:return{x:1-r-f,y:t,width:f,height:c};case 180:return{x:1-t-c,y:1-r-f,width:c,height:f};case 270:return{x:r,y:1-t-c,width:f,height:c}}return{x:t,y:r,width:c,height:f}}rotate(t){const{drawLayer:r}=this.parent;let c;this.#c?(t=(t-this.rotation+360)%360,c=d.#x(this.#d.box,t)):c=d.#x(this,t),r.rotate(this.#u,t),r.rotate(this.#f,t),r.updateBox(this.#u,c),r.updateBox(this.#f,d.#x(this.#i.box,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.#c?t.classList.add("free"):this.div.addEventListener("keydown",this.#o);const r=this.#h=document.createElement("div");t.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=this.#n;const[c,f]=this.parentDimensions;return this.setDims(this.width*c,this.height*f),(0,_.bindEvents)(this,this.#h,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.parent.drawLayer.addClass(this.#f,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#f,"hovered")}#T(t){d._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#F(!0);break;case 1:case 3:this.#F(!1);break}}#F(t){if(!this.#t)return;const r=window.getSelection();t?r.setPosition(this.#t,this.#e):r.setPosition(this.#a,this.#l)}select(){super.select(),this.#f&&(this.parent?.drawLayer.removeClass(this.#f,"hovered"),this.parent?.drawLayer.addClass(this.#f,"selected"))}unselect(){super.unselect(),this.#f&&(this.parent?.drawLayer.removeClass(this.#f,"selected"),this.#c||this.#F(!1))}get _mustFixPosition(){return!this.#c}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.show(this.#u,t),this.parent.drawLayer.show(this.#f,t))}#k(){return this.#c?this.rotation:0}#I(){if(this.#c)return null;const[t,r]=this.pageDimensions,c=this.#s,f=new Array(c.length*8);let v=0;for(const{x:S,y:M,width:I,height:O}of c){const N=S*t,B=(1-M-O)*r;f[v]=f[v+4]=N,f[v+1]=f[v+3]=B,f[v+2]=f[v+6]=N+I*t,f[v+5]=f[v+7]=B+O*r,v+=8}return f}#R(t){return this.#d.serialize(t,this.#k())}static startHighlighting(t,r,{target:c,x:f,y:v}){const{x:S,y:M,width:I,height:O}=c.getBoundingClientRect(),N=X=>{this.#_(t,X)},B={capture:!0,passive:!1},q=X=>{X.preventDefault(),X.stopPropagation()},st=X=>{c.removeEventListener("pointermove",N),window.removeEventListener("blur",st),window.removeEventListener("pointerup",st),window.removeEventListener("pointerdown",q,B),window.removeEventListener("contextmenu",o.noContextMenu),this.#P(t,X)};window.addEventListener("blur",st),window.addEventListener("pointerup",st),window.addEventListener("pointerdown",q,B),window.addEventListener("contextmenu",o.noContextMenu),c.addEventListener("pointermove",N),this._freeHighlight=new T.FreeOutliner({x:f,y:v},[S,M,I,O],t.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#_(t,r){this._freeHighlight.add(r)&&t.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#P(t,r){this._freeHighlight.isEmpty()?t.drawLayer.removeFreeHighlight(this._freeHighlightId):t.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static deserialize(t,r,c){const f=super.deserialize(t,r,c),{rect:[v,S,M,I],color:O,quadPoints:N}=t;f.color=y.Util.makeHexColor(...O),f.#g=t.opacity;const[B,q]=f.pageDimensions;f.width=(M-v)/B,f.height=(I-S)/q;const st=f.#s=[];for(let X=0;X{this.thickness=f,this.#N()},c=this.thickness;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#m(t){const r=f=>{this.color=f,this.#T()},c=this.color;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#b(t){const r=f=>{this.opacity=f,this.#T()};t/=100;const c=this.opacity;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,c),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(this.#k(),this.#I()),this.isAttachedToDOM||(this.parent.add(this),this.#R()),this.#N()))}remove(){this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.#a&&(clearTimeout(this.#a),this.#a=null),this.#c.disconnect(),this.#c=null,super.remove())}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&t===null&&this._uiManager.addShouldRescale(this),super.setParent(t)}onScaleChanging(){const[t,r]=this.parentDimensions,c=this.width*t,f=this.height*r;this.setDimensions(c,f)}enableEditMode(){this.#h||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#i))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#i))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#A(){const{parentRotation:t,parentDimensions:[r,c]}=this;switch(t){case 90:return[0,c,c,r];case 180:return[r,c,r,c];case 270:return[r,0,c,r];default:return[0,0,r,c]}}#w(){const{ctx:t,color:r,opacity:c,thickness:f,parentScale:v,scaleFactor:S}=this;t.lineWidth=f*v/S,t.lineCap="round",t.lineJoin="round",t.miterLimit=10,t.strokeStyle=`${r}${(0,_.opacityToHex)(c)}`}#E(t,r){this.canvas.addEventListener("contextmenu",o.noContextMenu),this.canvas.addEventListener("pointerleave",this.#n),this.canvas.addEventListener("pointermove",this.#s),this.canvas.addEventListener("pointerup",this.#r),this.canvas.removeEventListener("pointerdown",this.#i),this.isEditing=!0,this.#u||(this.#u=!0,this.#R(),this.thickness||=u._defaultThickness,this.color||=u._defaultColor||z.AnnotationEditor._defaultLineColor,this.opacity??=u._defaultOpacity),this.currentPath.push([t,r]),this.#d=!1,this.#w(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#L(t,r){const[c,f]=this.currentPath.at(-1);if(this.currentPath.length>1&&t===c&&r===f)return;const v=this.currentPath;let S=this.#l;if(v.push([t,r]),this.#d=!0,v.length<=2){S.moveTo(...v[0]),S.lineTo(t,r);return}v.length===3&&(this.#l=S=new Path2D,S.moveTo(...v[0])),this.#S(S,...v.at(-3),...v.at(-2),t,r)}#M(){if(this.currentPath.length===0)return;const t=this.currentPath.at(-1);this.#l.lineTo(...t)}#y(t,r){this.#g=null,t=Math.min(Math.max(t,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),this.#L(t,r),this.#M();let c;if(this.currentPath.length!==1)c=this.#x();else{const I=[t,r];c=[[I,I.slice(),I.slice(),I]]}const f=this.#l,v=this.currentPath;this.currentPath=[],this.#l=new Path2D;const S=()=>{this.allRawPaths.push(v),this.paths.push(c),this.bezierPath2D.push(f),this._uiManager.rebuild(this)},M=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(this.#k(),this.#I()),this.#N())};this.addCommands({cmd:S,undo:M,mustExec:!0})}#v(){if(!this.#d)return;this.#d=!1;const t=Math.ceil(this.thickness*this.parentScale),r=this.currentPath.slice(-3),c=r.map(S=>S[0]),f=r.map(S=>S[1]);Math.min(...c)-t,Math.max(...c)+t,Math.min(...f)-t,Math.max(...f)+t;const{ctx:v}=this;v.save(),v.clearRect(0,0,this.canvas.width,this.canvas.height);for(const S of this.bezierPath2D)v.stroke(S);v.stroke(this.#l),v.restore()}#S(t,r,c,f,v,S,M){const I=(r+f)/2,O=(c+v)/2,N=(f+S)/2,B=(v+M)/2;t.bezierCurveTo(I+2*(f-I)/3,O+2*(v-O)/3,N+2*(f-N)/3,B+2*(v-B)/3,N,B)}#x(){const t=this.currentPath;if(t.length<=2)return[[t[0],t[0],t.at(-1),t.at(-1)]];const r=[];let c,[f,v]=t[0];for(c=1;c{this.#a=null,this.canvas.removeEventListener("contextmenu",o.noContextMenu)},10),this.#y(t.offsetX,t.offsetY),this.addToAnnotationStorage(),this.setInBackground()}#k(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")}#I(){this.#c=new ResizeObserver(t=>{const r=t[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)}),this.#c.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#h}render(){if(this.div)return this.div;let t,r;this.width&&(t=this.x,r=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[c,f,v,S]=this.#A();if(this.setAt(c,f,0,0),this.setDims(v,S),this.#k(),this.width){const[M,I]=this.parentDimensions;this.setAspectRatio(this.width*M,this.height*I),this.setAt(t*M,r*I,this.width*M,this.height*I),this.#u=!0,this.#R(),this.setDims(this.width*M,this.height*I),this.#T(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#I(),this.div}#R(){if(!this.#u)return;const[t,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t),this.canvas.height=Math.ceil(this.height*r),this.#P()}setDimensions(t,r){const c=Math.round(t),f=Math.round(r);if(this.#o===c&&this.#p===f)return;this.#o=c,this.#p=f,this.canvas.style.visibility="hidden";const[v,S]=this.parentDimensions;this.width=t/v,this.height=r/S,this.fixAndSetPosition(),this.#h&&this.#_(t,r),this.#R(),this.#T(),this.canvas.style.visibility="visible",this.fixDims()}#_(t,r){const c=this.#B(),f=(t-c)/this.#e,v=(r-c)/this.#t;this.scaleFactor=Math.min(f,v)}#P(){const t=this.#B()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#D(t){const r=new Path2D;for(let c=0,f=t.length;c`image/${r}`))}static get supportedTypesStr(){return(0,y.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,r){r.pasteEditor(y.AnnotationEditorType.STAMP,{bitmapFile:t.getAsFile()})}#c(t,r=!1){if(!t){this.remove();return}this.#t=t.bitmap,r||(this.#e=t.id,this.#d=t.isSvg),t.file&&(this.#i=t.file.name),this.#g()}#o(){this.#s=null,this._uiManager.enableWaiting(!1),this.#a&&this.div.focus()}#p(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(r=>this.#c(r,!0)).finally(()=>this.#o());return}if(this.#n){const r=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(r).then(c=>this.#c(c)).finally(()=>this.#o());return}if(this.#r){const r=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(r).then(c=>this.#c(c)).finally(()=>this.#o());return}const t=document.createElement("input");t.type="file",t.accept=b.supportedTypesStr,this.#s=new Promise(r=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const c=await this._uiManager.imageManager.getFromFile(t.files[0]);this.#c(c)}r()}),t.addEventListener("cancel",()=>{this.remove(),r()})}).finally(()=>this.#o()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#a?.remove(),this.#a=null,this.#l?.disconnect(),this.#l=null,this.#h&&(clearTimeout(this.#h),this.#h=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#p();return}super.rebuild(),this.div!==null&&(this.#e&&this.#a===null&&this.#p(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#n||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,r;if(this.width&&(t=this.x,r=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#p(),this.width){const[c,f]=this.parentDimensions;this.setAt(t*c,r*f,this.width*c,this.height*f)}return this.div}#g(){const{div:t}=this;let{width:r,height:c}=this.#t;const[f,v]=this.pageDimensions,S=.75;if(this.width)r=this.width*f,c=this.height*v;else if(r>S*f||c>S*v){const N=Math.min(S*f/r,S*v/c);r*=N,c*=N}const[M,I]=this.parentDimensions;this.setDims(r*M/f,c*I/v),this._uiManager.enableWaiting(!1);const O=this.#a=document.createElement("canvas");t.append(O),t.hidden=!1,this.#b(r,c),this.#w(),this.#u||(this.parent.addUndoableEditor(this),this.#u=!0),this._reportTelemetry({action:"inserted_image"}),this.#i&&O.setAttribute("aria-label",this.#i)}#f(t,r){const[c,f]=this.parentDimensions;this.width=t/c,this.height=r/f,this.setDims(t,r),this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,this.#h!==null&&clearTimeout(this.#h);const v=200;this.#h=setTimeout(()=>{this.#h=null,this.#b(t,r)},v)}#m(t,r){const{width:c,height:f}=this.#t;let v=c,S=f,M=this.#t;for(;v>2*t||S>2*r;){const I=v,O=S;v>2*t&&(v=v>=16384?Math.floor(v/2)-1:Math.ceil(v/2)),S>2*r&&(S=S>=16384?Math.floor(S/2)-1:Math.ceil(S/2));const N=new OffscreenCanvas(v,S);N.getContext("2d").drawImage(M,0,0,I,O,0,0,v,S),M=N.transferToImageBitmap()}return M}#b(t,r){t=Math.ceil(t),r=Math.ceil(r);const c=this.#a;if(!c||c.width===t&&c.height===r)return;c.width=t,c.height=r;const f=this.#d?this.#t:this.#m(t,r);if(this._uiManager.hasMLManager&&!this.hasAltText()){const S=new OffscreenCanvas(t,r);S.getContext("2d").drawImage(f,0,0,f.width,f.height,0,0,t,r),S.convertToBlob().then(I=>{const O=new FileReader;O.onload=()=>{const N=O.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:N}}).then(B=>{const q=B?.output||"";this.parent&&q&&!this.hasAltText()&&(this.altTextData={altText:q,decorative:!1})})},O.readAsDataURL(I)})}const v=c.getContext("2d");v.filter=this._uiManager.hcmFilter,v.drawImage(f,0,0,f.width,f.height,0,0,t,r)}getImageForAltText(){return this.#a}#A(t){if(t){if(this.#d){const f=this._uiManager.imageManager.getSvgUrl(this.#e);if(f)return f}const r=document.createElement("canvas");return{width:r.width,height:r.height}=this.#t,r.getContext("2d").drawImage(this.#t,0,0),r.toDataURL()}if(this.#d){const[r,c]=this.pageDimensions,f=Math.round(this.width*r*o.PixelsPerInch.PDF_TO_CSS_UNITS),v=Math.round(this.height*c*o.PixelsPerInch.PDF_TO_CSS_UNITS),S=new OffscreenCanvas(f,v);return S.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,f,v),S.transferToImageBitmap()}return structuredClone(this.#t)}#w(){this.#l=new ResizeObserver(t=>{const r=t[0].contentRect;r.width&&r.height&&this.#f(r.width,r.height)}),this.#l.observe(this.div)}static deserialize(t,r,c){if(t instanceof U.StampAnnotationElement)return null;const f=super.deserialize(t,r,c),{rect:v,bitmapUrl:S,bitmapId:M,isSvg:I,accessibilityData:O}=t;M&&c.imageManager.isValidId(M)?f.#e=M:f.#n=S,f.#d=I;const[N,B]=f.pageDimensions;return f.width=(v[2]-v[0])/N,f.height=(v[3]-v[1])/B,O&&(f.altTextData=O),f}serialize(t=!1,r=null){if(this.isEmpty())return null;const c={annotationType:y.AnnotationEditorType.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#d,structTreeParentId:this._structTreeParentId};if(t)return c.bitmapUrl=this.#A(!0),c.accessibilityData=this.altTextData,c;const{decorative:f,altText:v}=this.altTextData;if(!f&&v&&(c.accessibilityData={type:"Figure",alt:v}),r===null)return c;r.stamps||=new Map;const S=this.#d?(c.rect[2]-c.rect[0])*(c.rect[3]-c.rect[1]):null;if(!r.stamps.has(this.#e))r.stamps.set(this.#e,{area:S,serialized:c}),c.bitmap=this.#A(!1);else if(this.#d){const M=r.stamps.get(this.#e);S>M.area&&(M.area=S,M.serialized.bitmap.close(),M.serialized.bitmap=this.#A(!1))}return c}}class s{#t;#e=!1;#s=null;#n=null;#r=null;#i=null;#a=null;#l=new Map;#h=!1;#d=!1;#u=!1;#c=null;#o;static _initialized=!1;static#p=new Map([C,u,b,d].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:r,div:c,accessibilityManager:f,annotationLayer:v,drawLayer:S,textLayer:M,viewport:I,l10n:O}){const N=[...s.#p.values()];if(!s._initialized){s._initialized=!0;for(const B of N)B.initialize(O,t)}t.registerEditorTypes(N),this.#o=t,this.pageIndex=r,this.div=c,this.#t=f,this.#s=v,this.viewport=I,this.#c=M,this.drawLayer=S,this.#o.addLayer(this)}get isEmpty(){return this.#l.size===0}get isInvisible(){return this.isEmpty&&this.#o.getMode()===y.AnnotationEditorType.NONE}updateToolbar(t){this.#o.updateToolbar(t)}updateMode(t=this.#o.getMode()){switch(this.#A(),t){case y.AnnotationEditorType.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case y.AnnotationEditorType.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case y.AnnotationEditorType.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:r}=this.div;for(const c of s.#p.values())r.toggle(`${c._type}Editing`,t===c._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#c?.div}addInkEditorIfNeeded(t){if(this.#o.getMode()!==y.AnnotationEditorType.INK)return;if(!t){for(const c of this.#l.values())if(c.isEmpty()){c.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){this.#o.setEditingState(t)}addCommands(t){this.#o.addCommands(t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const c of this.#l.values())c.enableEditing(),c.annotationElementId&&t.add(c.annotationElementId);if(!this.#s)return;const r=this.#s.getEditableAnnotations();for(const c of r){if(c.hide(),this.#o.isDeletedAnnotationElement(c.data.id)||t.has(c.data.id))continue;const f=this.deserialize(c);f&&(this.addOrRebuild(f),f.enableEditing())}}disable(){this.#u=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Set;for(const c of this.#l.values()){if(c.disableEditing(),!c.annotationElementId||c.serialize()!==null){t.add(c.annotationElementId);continue}this.getEditableAnnotation(c.annotationElementId)?.show(),c.remove()}if(this.#s){const c=this.#s.getEditableAnnotations();for(const f of c){const{id:v}=f.data;t.has(v)||this.#o.isDeletedAnnotationElement(v)||f.show()}}this.#A(),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const c of s.#p.values())r.remove(`${c._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#u=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#o.getActive()!==t&&this.#o.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1,this.#c?.div&&!this.#i&&(this.#i=this.#g.bind(this),this.#c.div.addEventListener("pointerdown",this.#i),this.#c.div.classList.add("highlighting"))}disableTextSelection(){this.div.tabIndex=0,this.#c?.div&&this.#i&&(this.#c.div.removeEventListener("pointerdown",this.#i),this.#i=null,this.#c.div.classList.remove("highlighting"))}#g(t){if(this.#o.unselectAll(),t.target===this.#c.div){const{isMac:r}=y.FeatureTest.platform;if(t.button!==0||t.ctrlKey&&r)return;this.#o.showAllEditors("highlight",!0,!0),this.#c.div.classList.add("free"),d.startHighlighting(this,this.#o.direction==="ltr",t),this.#c.div.addEventListener("pointerup",()=>{this.#c.div.classList.remove("free")},{once:!0}),t.preventDefault()}}enableClick(){this.#r||(this.#r=this.pointerdown.bind(this),this.#n=this.pointerup.bind(this),this.div.addEventListener("pointerdown",this.#r),this.div.addEventListener("pointerup",this.#n))}disableClick(){this.#r&&(this.div.removeEventListener("pointerdown",this.#r),this.div.removeEventListener("pointerup",this.#n),this.#r=null,this.#n=null)}attach(t){this.#l.set(t.id,t);const{annotationElementId:r}=t;r&&this.#o.isDeletedAnnotationElement(r)&&this.#o.removeDeletedAnnotationElement(t)}detach(t){this.#l.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#u&&t.annotationElementId&&this.#o.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#o.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,this.#d||this.addInkEditorIfNeeded(!1)}changeParent(t){t.parent!==this&&(t.annotationElementId&&(this.#o.addDeletedAnnotationElement(t.annotationElementId),z.AnnotationEditor.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#o.addEditor(t),this.attach(t),!t.isAttachedToDOM){const r=t.render();this.div.append(r),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),this.#o.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:r}=document;t.div.contains(r)&&!this.#a&&(t._focusEventsAllowed=!1,this.#a=setTimeout(()=>{this.#a=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0}),r.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 r=()=>t._uiManager.rebuild(t),c=()=>{t.remove()};this.addCommands({cmd:r,undo:c,mustExec:!1})}getNextId(){return this.#o.getId()}get#f(){return s.#p.get(this.#o.getMode())}#m(t){const r=this.#f;return r?new r.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#f?.canCreateNewEmptyEditor()}pasteEditor(t,r){this.#o.updateToolbar(t),this.#o.updateMode(t);const{offsetX:c,offsetY:f}=this.#b(),v=this.getNextId(),S=this.#m({parent:this,id:v,x:c,y:f,uiManager:this.#o,isCentered:!0,...r});S&&this.add(S)}deserialize(t){return s.#p.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#o)||null}createAndAddNewEditor(t,r,c={}){const f=this.getNextId(),v=this.#m({parent:this,id:f,x:t.offsetX,y:t.offsetY,uiManager:this.#o,isCentered:r,...c});return v&&this.add(v),v}#b(){const{x:t,y:r,width:c,height:f}=this.div.getBoundingClientRect(),v=Math.max(0,t),S=Math.max(0,r),M=Math.min(window.innerWidth,t+c),I=Math.min(window.innerHeight,r+f),O=(v+M)/2-t,N=(S+I)/2-r,[B,q]=this.viewport.rotation%180===0?[O,N]:[N,O];return{offsetX:B,offsetY:q}}addNewEditor(){this.createAndAddNewEditor(this.#b(),!0)}setSelected(t){this.#o.setSelected(t)}toggleSelected(t){this.#o.toggleSelected(t)}isSelected(t){return this.#o.isSelected(t)}unselect(t){this.#o.unselect(t)}pointerup(t){const{isMac:r}=y.FeatureTest.platform;if(!(t.button!==0||t.ctrlKey&&r)&&t.target===this.div&&this.#h){if(this.#h=!1,!this.#e){this.#e=!0;return}if(this.#o.getMode()===y.AnnotationEditorType.STAMP){this.#o.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#o.getMode()===y.AnnotationEditorType.HIGHLIGHT&&this.enableTextSelection(),this.#h){this.#h=!1;return}const{isMac:r}=y.FeatureTest.platform;if(t.button!==0||t.ctrlKey&&r||t.target!==this.div)return;this.#h=!0;const c=this.#o.getActive();this.#e=!c||c.isEmpty()}findNewParent(t,r,c){const f=this.#o.findParent(r,c);return f===null||f===this?!1:(f.changeParent(t),!0)}destroy(){this.#o.getActive()?.parent===this&&(this.#o.commitOrRemove(),this.#o.setActiveEditor(null)),this.#a&&(clearTimeout(this.#a),this.#a=null);for(const t of this.#l.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#l.clear(),this.#o.removeLayer(this)}#A(){this.#d=!0;for(const t of this.#l.values())t.isEmpty()&&t.remove();this.#d=!1}render({viewport:t}){this.viewport=t,(0,o.setLayerDimensions)(this.div,t);for(const r of this.#o.getEditors(this.pageIndex))this.add(r),r.rebuild();this.updateMode()}update({viewport:t}){this.#o.commitOrRemove(),this.#A();const r=this.viewport.rotation,c=t.rotation;if(this.viewport=t,(0,o.setLayerDimensions)(this.div,{rotation:c}),r!==c)for(const f of this.#l.values())f.rotate(c);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:r}=this.viewport.rawDims;return[t,r]}get scale(){return this.#o.viewParameters.realScale}}},259:(dt,et,V)=>{V.d(et,{ColorPicker:()=>U});var y=V(292),z=V(830),_=V(419);class U{#t=this.#g.bind(this);#e=this.#m.bind(this);#s=null;#n=null;#r;#i=null;#a=!1;#l=!1;#h=null;#d;#u=null;#c;static get _keyboardManager(){return(0,y.shadow)(this,"_keyboardManager",new z.KeyboardManager([[["Escape","mac+Escape"],U.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],U.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],U.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],U.prototype._moveToPrevious],[["Home","mac+Home"],U.prototype._moveToBeginning],[["End","mac+End"],U.prototype._moveToEnd]]))}constructor({editor:C=null,uiManager:T=null}){C?(this.#l=!1,this.#c=y.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#h=C):(this.#l=!0,this.#c=y.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#u=C?._uiManager||T,this.#d=this.#u._eventBus,this.#r=C?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){const C=this.#s=document.createElement("button");C.className="colorPicker",C.tabIndex="0",C.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),C.setAttribute("aria-haspopup",!0),C.addEventListener("click",this.#f.bind(this)),C.addEventListener("keydown",this.#t);const T=this.#n=document.createElement("span");return T.className="swatch",T.setAttribute("aria-hidden",!0),T.style.backgroundColor=this.#r,C.append(T),C}renderMainDropdown(){const C=this.#i=this.#o();return C.setAttribute("aria-orientation","horizontal"),C.setAttribute("aria-labelledby","highlightColorPickerLabel"),C}#o(){const C=document.createElement("div");C.addEventListener("contextmenu",_.noContextMenu),C.className="dropdown",C.role="listbox",C.setAttribute("aria-multiselectable",!1),C.setAttribute("aria-orientation","vertical"),C.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[T,A]of this.#u.highlightColors){const o=document.createElement("button");o.tabIndex="0",o.role="option",o.setAttribute("data-color",A),o.title=T,o.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${T}`);const d=document.createElement("span");o.append(d),d.className="swatch",d.style.backgroundColor=A,o.setAttribute("aria-selected",A===this.#r),o.addEventListener("click",this.#p.bind(this,A)),C.append(o)}return C.addEventListener("keydown",this.#t),C}#p(C,T){T.stopPropagation(),this.#d.dispatch("switchannotationeditorparams",{source:this,type:this.#c,value:C})}_colorSelectFromKeyboard(C){if(C.target===this.#s){this.#f(C);return}const T=C.target.getAttribute("data-color");T&&this.#p(T,C)}_moveToNext(C){if(!this.#b){this.#f(C);return}if(C.target===this.#s){this.#i.firstChild?.focus();return}C.target.nextSibling?.focus()}_moveToPrevious(C){if(C.target===this.#i?.firstChild||C.target===this.#s){this.#b&&this._hideDropdownFromKeyboard();return}this.#b||this.#f(C),C.target.previousSibling?.focus()}_moveToBeginning(C){if(!this.#b){this.#f(C);return}this.#i.firstChild?.focus()}_moveToEnd(C){if(!this.#b){this.#f(C);return}this.#i.lastChild?.focus()}#g(C){U._keyboardManager.exec(this,C)}#f(C){if(this.#b){this.hideDropdown();return}if(this.#a=C.detail===0,window.addEventListener("pointerdown",this.#e),this.#i){this.#i.classList.remove("hidden");return}const T=this.#i=this.#o();this.#s.append(T)}#m(C){this.#i?.contains(C.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),window.removeEventListener("pointerdown",this.#e)}get#b(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#l){if(!this.#b){this.#h?.unselect();return}this.hideDropdown(),this.#s.focus({preventScroll:!0,focusVisible:this.#a})}}updateColor(C){if(this.#n&&(this.#n.style.backgroundColor=C),!this.#i)return;const T=this.#u.highlightColors.values();for(const A of this.#i.children)A.setAttribute("aria-selected",T.next().value===C)}destroy(){this.#s?.remove(),this.#s=null,this.#n=null,this.#i?.remove(),this.#i=null}}},310:(dt,et,V)=>{V.d(et,{AnnotationEditor:()=>C});var y=V(830),z=V(292),_=V(419);class U{#t="";#e=!1;#s=null;#n=null;#r=null;#i=!1;#a=null;static _l10nPromise=null;constructor(o){this.#a=o}static initialize(o){U._l10nPromise||=o}async render(){const o=this.#s=document.createElement("button");o.className="altText";const d=await U._l10nPromise.get("pdfjs-editor-alt-text-button-label");o.textContent=d,o.setAttribute("aria-label",d),o.tabIndex="0",o.addEventListener("contextmenu",_.noContextMenu),o.addEventListener("pointerdown",b=>b.stopPropagation());const u=b=>{b.preventDefault(),this.#a._uiManager.editAltText(this.#a)};return o.addEventListener("click",u,{capture:!0}),o.addEventListener("keydown",b=>{b.target===o&&b.key==="Enter"&&(this.#i=!0,u(b))}),await this.#l(),o}finish(){this.#s&&(this.#s.focus({focusVisible:this.#i}),this.#i=!1)}isEmpty(){return!this.#t&&!this.#e}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:o,decorative:d}){this.#t===o&&this.#e===d||(this.#t=o,this.#e=d,this.#l())}toggle(o=!1){this.#s&&(!o&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#s.disabled=!o)}destroy(){this.#s?.remove(),this.#s=null,this.#n=null}async#l(){const o=this.#s;if(!o)return;if(!this.#t&&!this.#e){o.classList.remove("done"),this.#n?.remove();return}o.classList.add("done"),U._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then(b=>{o.setAttribute("aria-label",b)});let d=this.#n;if(!d){this.#n=d=document.createElement("span"),d.className="tooltip",d.setAttribute("role","tooltip");const b=d.id=`alt-text-tooltip-${this.#a.id}`;o.setAttribute("aria-describedby",b);const s=100;o.addEventListener("mouseenter",()=>{this.#r=setTimeout(()=>{this.#r=null,this.#n.classList.add("show"),this.#a._reportTelemetry({action:"alt_text_tooltip"})},s)}),o.addEventListener("mouseleave",()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")})}d.innerText=this.#e?await U._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,d.parentNode||o.append(d),this.#a.getImageForAltText()?.setAttribute("aria-describedby",d.id)}}var F=V(362);class C{#t=null;#e=null;#s=!1;#n=!1;#r=null;#i=null;#a=this.focusin.bind(this);#l=this.focusout.bind(this);#h=null;#d="";#u=!1;#c=null;#o=!1;#p=!1;#g=!1;#f=null;#m=0;#b=0;#A=null;_initialOptions=Object.create(null);_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#w=!1;#E=C._zIndex++;static _borderLineWidth=-1;static _colorManager=new y.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const o=C.prototype._resizeWithKeyboard,d=y.AnnotationEditorUIManager.TRANSLATE_SMALL,u=y.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,z.shadow)(this,"_resizerKeyboardManager",new y.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],o,{args:[-d,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],o,{args:[-u,0]}],[["ArrowRight","mac+ArrowRight"],o,{args:[d,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],o,{args:[u,0]}],[["ArrowUp","mac+ArrowUp"],o,{args:[0,-d]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],o,{args:[0,-u]}],[["ArrowDown","mac+ArrowDown"],o,{args:[0,d]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],o,{args:[0,u]}],[["Escape","mac+Escape"],C.prototype._stopResizingWithKeyboard]]))}constructor(o){this.constructor===C&&(0,z.unreachable)("Cannot initialize AnnotationEditor."),this.parent=o.parent,this.id=o.id,this.width=this.height=null,this.pageIndex=o.parent.pageIndex,this.name=o.name,this.div=null,this._uiManager=o.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=o.isCentered,this._structTreeParentId=null;const{rotation:d,rawDims:{pageWidth:u,pageHeight:b,pageX:s,pageY:g}}=this.parent.viewport;this.rotation=d,this.pageRotation=(360+d-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[u,b],this.pageTranslation=[s,g];const[t,r]=this.parentDimensions;this.x=o.x/t,this.y=o.y/r,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,z.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(o){const d=new T({id:o.parent.getNextId(),parent:o.parent,uiManager:o._uiManager});d.annotationElementId=o.annotationElementId,d.deleted=!0,d._uiManager.addToAnnotationStorage(d)}static initialize(o,d,u){if(C._l10nPromise||=new Map(["pdfjs-editor-alt-text-button-label","pdfjs-editor-alt-text-edit-button-label","pdfjs-editor-alt-text-decorative-tooltip","pdfjs-editor-resizer-label-topLeft","pdfjs-editor-resizer-label-topMiddle","pdfjs-editor-resizer-label-topRight","pdfjs-editor-resizer-label-middleRight","pdfjs-editor-resizer-label-bottomRight","pdfjs-editor-resizer-label-bottomMiddle","pdfjs-editor-resizer-label-bottomLeft","pdfjs-editor-resizer-label-middleLeft"].map(s=>[s,o.get(s.replaceAll(/([A-Z])/g,g=>`-${g.toLowerCase()}`))])),u?.strings)for(const s of u.strings)C._l10nPromise.set(s,o.get(s));if(C._borderLineWidth!==-1)return;const b=getComputedStyle(document.documentElement);C._borderLineWidth=parseFloat(b.getPropertyValue("--outline-width"))||0}static updateDefaultParams(o,d){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(o){return!1}static paste(o,d){(0,z.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(o){this.#w=o,this.div?.classList.toggle("draggable",o)}get isEnterHandled(){return!0}center(){const[o,d]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*d/(o*2),this.y+=this.width*o/(d*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*d/(o*2),this.y-=this.width*o/(d*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(o){this._uiManager.addCommands(o)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#E}setParent(o){o!==null?(this.pageIndex=o.pageIndex,this.pageDimensions=o.pageDimensions):this.#D(),this.parent=o}focusin(o){this._focusEventsAllowed&&(this.#u?this.#u=!1:this.parent.setSelected(this))}focusout(o){!this._focusEventsAllowed||!this.isAttachedToDOM||o.relatedTarget?.closest(`#${this.id}`)||(o.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(o,d,u,b){const[s,g]=this.parentDimensions;[u,b]=this.screenToPageTranslation(u,b),this.x=(o+u)/s,this.y=(d+b)/g,this.fixAndSetPosition()}#L([o,d],u,b){[u,b]=this.screenToPageTranslation(u,b),this.x+=u/o,this.y+=b/d,this.fixAndSetPosition()}translate(o,d){this.#L(this.parentDimensions,o,d)}translateInPage(o,d){this.#c||=[this.x,this.y],this.#L(this.pageDimensions,o,d),this.div.scrollIntoView({block:"nearest"})}drag(o,d){this.#c||=[this.x,this.y];const[u,b]=this.parentDimensions;if(this.x+=o/u,this.y+=d/b,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:c,y:f}=this.div.getBoundingClientRect();this.parent.findNewParent(this,c,f)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:s,y:g}=this;const[t,r]=this.getBaseTranslation();s+=t,g+=r,this.div.style.left=`${(100*s).toFixed(2)}%`,this.div.style.top=`${(100*g).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#c&&(this.#c[0]!==this.x||this.#c[1]!==this.y)}getBaseTranslation(){const[o,d]=this.parentDimensions,{_borderLineWidth:u}=C,b=u/o,s=u/d;switch(this.rotation){case 90:return[-b,s];case 180:return[b,s];case 270:return[b,-s];default:return[-b,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(o=this.rotation){const[d,u]=this.pageDimensions;let{x:b,y:s,width:g,height:t}=this;if(g*=d,t*=u,b*=d,s*=u,this._mustFixPosition)switch(o){case 0:b=Math.max(0,Math.min(d-g,b)),s=Math.max(0,Math.min(u-t,s));break;case 90:b=Math.max(0,Math.min(d-t,b)),s=Math.min(u,Math.max(g,s));break;case 180:b=Math.min(d,Math.max(g,b)),s=Math.min(u,Math.max(t,s));break;case 270:b=Math.min(d,Math.max(t,b)),s=Math.max(0,Math.min(u-g,s));break}this.x=b/=d,this.y=s/=u;const[r,c]=this.getBaseTranslation();b+=r,s+=c;const{style:f}=this.div;f.left=`${(100*b).toFixed(2)}%`,f.top=`${(100*s).toFixed(2)}%`,this.moveInDOM()}static#M(o,d,u){switch(u){case 90:return[d,-o];case 180:return[-o,-d];case 270:return[-d,o];default:return[o,d]}}screenToPageTranslation(o,d){return C.#M(o,d,this.parentRotation)}pageTranslationToScreen(o,d){return C.#M(o,d,360-this.parentRotation)}#y(o){switch(o){case 90:{const[d,u]=this.pageDimensions;return[0,-d/u,u/d,0]}case 180:return[-1,0,0,-1];case 270:{const[d,u]=this.pageDimensions;return[0,d/u,-u/d,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:o,pageDimensions:[d,u]}=this,b=d*o,s=u*o;return z.FeatureTest.isCSSRoundSupported?[Math.round(b),Math.round(s)]:[b,s]}setDims(o,d){const[u,b]=this.parentDimensions;this.div.style.width=`${(100*o/u).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*d/b).toFixed(2)}%`)}fixDims(){const{style:o}=this.div,{height:d,width:u}=o,b=u.endsWith("%"),s=!this.#n&&d.endsWith("%");if(b&&s)return;const[g,t]=this.parentDimensions;b||(o.width=`${(100*parseFloat(u)/g).toFixed(2)}%`),!this.#n&&!s&&(o.height=`${(100*parseFloat(d)/t).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#v(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");const o=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(const d of o){const u=document.createElement("div");this.#r.append(u),u.classList.add("resizer",d),u.setAttribute("data-resizer-name",d),u.addEventListener("pointerdown",this.#S.bind(this,d)),u.addEventListener("contextmenu",_.noContextMenu),u.tabIndex=-1}this.div.prepend(this.#r)}#S(o,d){d.preventDefault();const{isMac:u}=z.FeatureTest.platform;if(d.button!==0||d.ctrlKey&&u)return;this.#e?.toggle(!1);const b=this.#T.bind(this,o),s=this._isDraggable;this._isDraggable=!1;const g={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",b,g);const t=this.x,r=this.y,c=this.width,f=this.height,v=this.parent.div.style.cursor,S=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(d.target).cursor;const M=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=s,window.removeEventListener("pointerup",M),window.removeEventListener("blur",M),window.removeEventListener("pointermove",b,g),this.parent.div.style.cursor=v,this.div.style.cursor=S,this.#x(t,r,c,f)};window.addEventListener("pointerup",M),window.addEventListener("blur",M)}#x(o,d,u,b){const s=this.x,g=this.y,t=this.width,r=this.height;s===o&&g===d&&t===u&&r===b||this.addCommands({cmd:()=>{this.width=t,this.height=r,this.x=s,this.y=g;const[c,f]=this.parentDimensions;this.setDims(c*t,f*r),this.fixAndSetPosition()},undo:()=>{this.width=u,this.height=b,this.x=o,this.y=d;const[c,f]=this.parentDimensions;this.setDims(c*u,f*b),this.fixAndSetPosition()},mustExec:!0})}#T(o,d){const[u,b]=this.parentDimensions,s=this.x,g=this.y,t=this.width,r=this.height,c=C.MIN_SIZE/u,f=C.MIN_SIZE/b,v=m=>Math.round(m*1e4)/1e4,S=this.#y(this.rotation),M=(m,l)=>[S[0]*m+S[2]*l,S[1]*m+S[3]*l],I=this.#y(360-this.rotation),O=(m,l)=>[I[0]*m+I[2]*l,I[1]*m+I[3]*l];let N,B,q=!1,st=!1;switch(o){case"topLeft":q=!0,N=(m,l)=>[0,0],B=(m,l)=>[m,l];break;case"topMiddle":N=(m,l)=>[m/2,0],B=(m,l)=>[m/2,l];break;case"topRight":q=!0,N=(m,l)=>[m,0],B=(m,l)=>[0,l];break;case"middleRight":st=!0,N=(m,l)=>[m,l/2],B=(m,l)=>[0,l/2];break;case"bottomRight":q=!0,N=(m,l)=>[m,l],B=(m,l)=>[0,0];break;case"bottomMiddle":N=(m,l)=>[m/2,l],B=(m,l)=>[m/2,0];break;case"bottomLeft":q=!0,N=(m,l)=>[0,l],B=(m,l)=>[m,0];break;case"middleLeft":st=!0,N=(m,l)=>[0,l/2],B=(m,l)=>[m,l/2];break}const X=N(t,r),H=B(t,r);let G=M(...H);const Y=v(s+G[0]),Q=v(g+G[1]);let K=1,at=1,[ot,lt]=this.screenToPageTranslation(d.movementX,d.movementY);if([ot,lt]=O(ot/u,lt/b),q){const m=Math.hypot(t,r);K=at=Math.max(Math.min(Math.hypot(H[0]-X[0]-ot,H[1]-X[1]-lt)/m,1/t,1/r),c/t,f/r)}else st?K=Math.max(c,Math.min(1,Math.abs(H[0]-X[0]-ot)))/t:at=Math.max(f,Math.min(1,Math.abs(H[1]-X[1]-lt)))/r;const ht=v(t*K),ft=v(r*at);G=M(...B(ht,ft));const ct=Y-G[0],Z=Q-G[1];this.width=ht,this.height=ft,this.x=ct,this.y=Z,this.setDims(u*ht,b*ft),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#h||this.#p?this.#h:(this.#h=new F.EditorToolbar(this),this.div.append(this.#h.render()),this.#e&&this.#h.addAltTextButton(await this.#e.render()),this.#h)}removeEditToolbar(){this.#h&&(this.#h.remove(),this.#h=null,this.#e?.destroy())}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#e||(U.initialize(C._l10nPromise),this.#e=new U(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(o){this.#e&&(this.#e.data=o)}hasAltText(){return!this.#e?.isEmpty()}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.#s?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.div.addEventListener("focusin",this.#a),this.div.addEventListener("focusout",this.#l);const[o,d]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*d/o).toFixed(2)}%`,this.div.style.maxHeight=`${(100*o/d).toFixed(2)}%`);const[u,b]=this.getInitialTranslation();return this.translate(u,b),(0,y.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(o){const{isMac:d}=z.FeatureTest.platform;if(o.button!==0||o.ctrlKey&&d){o.preventDefault();return}if(this.#u=!0,this._isDraggable){this.#k(o);return}this.#F(o)}#F(o){const{isMac:d}=z.FeatureTest.platform;o.ctrlKey&&!d||o.shiftKey||o.metaKey&&d?this.parent.toggleSelected(this):this.parent.setSelected(this)}#k(o){const d=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let u,b;d&&(this.div.classList.add("moving"),u={passive:!0,capture:!0},this.#m=o.clientX,this.#b=o.clientY,b=g=>{const{clientX:t,clientY:r}=g,[c,f]=this.screenToPageTranslation(t-this.#m,r-this.#b);this.#m=t,this.#b=r,this._uiManager.dragSelectedEditors(c,f)},window.addEventListener("pointermove",b,u));const s=()=>{window.removeEventListener("pointerup",s),window.removeEventListener("blur",s),d&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",b,u)),this.#u=!1,this._uiManager.endDragSession()||this.#F(o)};window.addEventListener("pointerup",s),window.addEventListener("blur",s)}moveInDOM(){this.#f&&clearTimeout(this.#f),this.#f=setTimeout(()=>{this.#f=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(o,d,u){o.changeParent(this),this.x=d,this.y=u,this.fixAndSetPosition()}getRect(o,d,u=this.rotation){const b=this.parentScale,[s,g]=this.pageDimensions,[t,r]=this.pageTranslation,c=o/b,f=d/b,v=this.x*s,S=this.y*g,M=this.width*s,I=this.height*g;switch(u){case 0:return[v+c+t,g-S-f-I+r,v+c+M+t,g-S-f+r];case 90:return[v+f+t,g-S+c+r,v+f+I+t,g-S+c+M+r];case 180:return[v-c-M+t,g-S+f+r,v-c+t,g-S+f+I+r];case 270:return[v-f-I+t,g-S-c-M+r,v-f+t,g-S-c+r];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(o,d){const[u,b,s,g]=o,t=s-u,r=g-b;switch(this.rotation){case 0:return[u,d-g,t,r];case 90:return[u,d-b,r,t];case 180:return[s,d-b,t,r];case 270:return[s,d-g,r,t];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#p=!0}disableEditMode(){this.#p=!1}isInEditMode(){return this.#p}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#a),this.div?.addEventListener("focusout",this.#l)}rotate(o){}serialize(o=!1,d=null){(0,z.unreachable)("An editor must be serializable")}static deserialize(o,d,u){const b=new this.prototype.constructor({parent:d,id:d.getNextId(),uiManager:u});b.rotation=o.rotation;const[s,g]=b.pageDimensions,[t,r,c,f]=b.getRectInCurrentCoords(o.rect,g);return b.x=t/s,b.y=r/g,b.width=c/s,b.height=f/g,b}remove(){if(this.div.removeEventListener("focusin",this.#a),this.div.removeEventListener("focusout",this.#l),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#f&&(clearTimeout(this.#f),this.#f=null),this.#D(),this.removeEditToolbar(),this.#A){for(const o of this.#A.values())clearTimeout(o);this.#A=null}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#v(),this.#r.classList.remove("hidden"),(0,y.bindEvents)(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(o){if(!this.isResizable||o.target!==this.div||o.key!=="Enter")return;this._uiManager.setSelected(this),this.#i={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const d=this.#r.children;if(!this.#t){this.#t=Array.from(d);const g=this.#I.bind(this),t=this.#R.bind(this);for(const r of this.#t){const c=r.getAttribute("data-resizer-name");r.setAttribute("role","spinbutton"),r.addEventListener("keydown",g),r.addEventListener("blur",t),r.addEventListener("focus",this.#_.bind(this,c)),C._l10nPromise.get(`pdfjs-editor-resizer-label-${c}`).then(f=>r.setAttribute("aria-label",f))}}const u=this.#t[0];let b=0;for(const g of d){if(g===u)break;b++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(s!==b){if(sb)for(let t=0;tt.setAttribute("aria-label",f))}}this.#P(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),o.preventDefault(),o.stopImmediatePropagation()}#I(o){C._resizerKeyboardManager.exec(this,o)}#R(o){this.#g&&o.relatedTarget?.parentNode!==this.#r&&this.#D()}#_(o){this.#d=this.#g?o:""}#P(o){if(this.#t)for(const d of this.#t)d.tabIndex=o}_resizeWithKeyboard(o,d){this.#g&&this.#T(this.#d,{movementX:o,movementY:d})}#D(){if(this.#g=!1,this.#P(-1),this.#i){const{savedX:o,savedY:d,savedWidth:u,savedHeight:b}=this.#i;this.#x(o,d,u,b),this.#i=null}}_stopResizingWithKeyboard(){this.#D(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this.#h){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this.#h?.show()});return}this.#h?.show()}unselect(){this.#r?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this.#h?.hide()}updateParams(o,d){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#o}set isEditing(o){this.#o=o,this.parent&&(o?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(o,d){this.#n=!0;const u=o/d,{style:b}=this.div;b.aspectRatio=u,b.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(o,d=!1){if(d){this.#A||=new Map;const{action:u}=o;let b=this.#A.get(u);b&&clearTimeout(b),b=setTimeout(()=>{this._reportTelemetry(o),this.#A.delete(u),this.#A.size===0&&(this.#A=null)},C._telemetryTimeout),this.#A.set(u,b);return}o.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:o}})}show(o=this._isVisible){this.div.classList.toggle("hidden",!o),this._isVisible=o}enable(){this.div&&(this.div.tabIndex=0),this.#s=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#s=!0}}class T extends C{constructor(o){super(o),this.annotationElementId=o.annotationElementId,this.deleted=!0}serialize(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex}}}},61:(dt,et,V)=>{V.d(et,{FreeOutliner:()=>F,Outliner:()=>z});var y=V(292);class z{#t;#e=[];#s=[];constructor(A,o=0,d=0,u=!0){let b=1/0,s=-1/0,g=1/0,t=-1/0;const c=10**-4;for(const{x:N,y:B,width:q,height:st}of A){const X=Math.floor((N-o)/c)*c,H=Math.ceil((N+q+o)/c)*c,G=Math.floor((B-o)/c)*c,Y=Math.ceil((B+st+o)/c)*c,Q=[X,G,Y,!0],K=[H,G,Y,!1];this.#e.push(Q,K),b=Math.min(b,X),s=Math.max(s,H),g=Math.min(g,G),t=Math.max(t,Y)}const f=s-b+2*d,v=t-g+2*d,S=b-d,M=g-d,I=this.#e.at(u?-1:-2),O=[I[0],I[2]];for(const N of this.#e){const[B,q,st]=N;N[0]=(B-S)/f,N[1]=(q-M)/v,N[2]=(st-M)/v}this.#t={x:S,y:M,width:f,height:v,lastPoint:O}}getOutlines(){this.#e.sort((o,d)=>o[0]-d[0]||o[1]-d[1]||o[2]-d[2]);const A=[];for(const o of this.#e)o[3]?(A.push(...this.#l(o)),this.#i(o)):(this.#a(o),A.push(...this.#l(o)));return this.#n(A)}#n(A){const o=[],d=new Set;for(const s of A){const[g,t,r]=s;o.push([g,t,s],[g,r,s])}o.sort((s,g)=>s[1]-g[1]||s[0]-g[0]);for(let s=0,g=o.length;s0;){const s=d.values().next().value;let[g,t,r,c,f]=s;d.delete(s);let v=g,S=t;for(b=[g,r],u.push(b);;){let M;if(d.has(c))M=c;else if(d.has(f))M=f;else break;d.delete(M),[g,t,r,c,f]=M,v!==g&&(b.push(v,S,g,S===t?t:r),v=g),S=S===t?r:t}b.push(v,S)}return new U(u,this.#t)}#r(A){const o=this.#s;let d=0,u=o.length-1;for(;d<=u;){const b=d+u>>1,s=o[b][0];if(s===A)return b;s=0;u--){const[b,s]=this.#s[u];if(b!==A)break;if(b===A&&s===o){this.#s.splice(u,1);return}}}#l(A){const[o,d,u]=A,b=[[o,d,u]],s=this.#r(u);for(let g=0;g=t){if(S>r)b[c][1]=r;else{if(f===1)return[];b.splice(c,1),c--,f--}continue}b[c][2]=t,S>r&&b.push([o,r,S])}}}return b}}class _{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(A,o){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof C}}class U extends _{#t;#e;constructor(A,o){super(),this.#e=A,this.#t=o}toSVGPath(){const A=[];for(const o of this.#e){let[d,u]=o;A.push(`M${d} ${u}`);for(let b=2;b=6;M-=6)isNaN(o[M])?S.push(`L${o[M+4]} ${o[M+5]}`):S.push(`C${o[M]} ${o[M+1]} ${o[M+2]} ${o[M+3]} ${o[M+4]} ${o[M+5]}`);return S.push(`L${o[4]} ${o[5]} Z`),S.join(" ")}getOutlines(){const A=this.#r,o=this.#e,d=this.#i,u=d.subarray(4,6),b=d.subarray(16,18),[s,g,t,r]=this.#t,c=new Float64Array((this.#o?.length??0)+2);for(let N=0,B=c.length-2;N=6;N-=6)for(let B=0;B<6;B+=2){if(isNaN(o[N+B])){I[O]=I[O+1]=NaN,O+=2;continue}I[O]=o[N+B],I[O+1]=o[N+B+1],O+=2}return I.set([NaN,NaN,NaN,NaN,o[4],o[5]],O),new C(I,c,this.#t,this.#u,this.#s,this.#n)}}class C extends _{#t;#e=null;#s;#n;#r;#i;#a;constructor(A,o,d,u,b,s){super(),this.#a=A,this.#r=o,this.#t=d,this.#i=u,this.#s=b,this.#n=s,this.#d(s);const{x:g,y:t,width:r,height:c}=this.#e;for(let f=0,v=A.length;f{V.d(et,{EditorToolbar:()=>z,HighlightToolbar:()=>_});var y=V(419);class z{#t=null;#e=null;#s;#n=null;constructor(F){this.#s=F}render(){const F=this.#t=document.createElement("div");F.className="editToolbar",F.setAttribute("role","toolbar"),F.addEventListener("contextmenu",y.noContextMenu),F.addEventListener("pointerdown",z.#r);const C=this.#n=document.createElement("div");C.className="buttons",F.append(C);const T=this.#s.toolbarPosition;if(T){const{style:A}=F,o=this.#s._uiManager.direction==="ltr"?1-T[0]:T[0];A.insetInlineEnd=`${100*o}%`,A.top=`calc(${100*T[1]}% + var(--editor-toolbar-vert-offset))`}return this.#h(),F}static#r(F){F.stopPropagation()}#i(F){this.#s._focusEventsAllowed=!1,F.preventDefault(),F.stopPropagation()}#a(F){this.#s._focusEventsAllowed=!0,F.preventDefault(),F.stopPropagation()}#l(F){F.addEventListener("focusin",this.#i.bind(this),{capture:!0}),F.addEventListener("focusout",this.#a.bind(this),{capture:!0}),F.addEventListener("contextmenu",y.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#h(){const F=document.createElement("button");F.className="delete",F.tabIndex=0,F.setAttribute("data-l10n-id",`pdfjs-editor-remove-${this.#s.editorType}-button`),this.#l(F),F.addEventListener("click",C=>{this.#s._uiManager.delete()}),this.#n.append(F)}get#d(){const F=document.createElement("div");return F.className="divider",F}addAltTextButton(F){this.#l(F),this.#n.prepend(F,this.#d)}addColorPicker(F){this.#e=F;const C=F.renderButton();this.#l(C),this.#n.prepend(C,this.#d)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class _{#t=null;#e=null;#s;constructor(F){this.#s=F}#n(){const F=this.#e=document.createElement("div");F.className="editToolbar",F.setAttribute("role","toolbar"),F.addEventListener("contextmenu",y.noContextMenu);const C=this.#t=document.createElement("div");return C.className="buttons",F.append(C),this.#i(),F}#r(F,C){let T=0,A=0;for(const o of F){const d=o.y+o.height;if(dT){A=u,T=d;continue}C?u>A&&(A=u):u{this.#s.highlightSelection("floating_button")}),this.#t.append(F)}}},830:(dt,et,V)=>{V.d(et,{AnnotationEditorUIManager:()=>u,ColorManager:()=>d,KeyboardManager:()=>o,bindEvents:()=>U,opacityToHex:()=>F});var y=V(292),z=V(419),_=V(362);function U(b,s,g){for(const t of g)s.addEventListener(t,b[t].bind(b))}function F(b){return Math.round(Math.min(255,Math.max(1,255*b))).toString(16).padStart(2,"0")}class C{#t=0;constructor(){}get id(){return`${y.AnnotationEditorPrefix}${this.#t++}`}}class T{#t=(0,y.getUuid)();#e=0;#s=null;static get _isSVGFittingCanvas(){const s='data:image/svg+xml;charset=UTF-8,',t=new OffscreenCanvas(1,3).getContext("2d"),r=new Image;r.src=s;const c=r.decode().then(()=>(t.drawImage(r,0,0,1,1,0,0,1,3),new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]===0));return(0,y.shadow)(this,"_isSVGFittingCanvas",c)}async#n(s,g){this.#s||=new Map;let t=this.#s.get(s);if(t===null)return null;if(t?.bitmap)return t.refCounter+=1,t;try{t||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let r;if(typeof g=="string"?(t.url=g,r=await(0,z.fetchData)(g,"blob")):r=t.file=g,r.type==="image/svg+xml"){const c=T._isSVGFittingCanvas,f=new FileReader,v=new Image,S=new Promise((M,I)=>{v.onload=()=>{t.bitmap=v,t.isSvg=!0,M()},f.onload=async()=>{const O=t.svgUrl=f.result;v.src=await c?`${O}#svgView(preserveAspectRatio(none))`:O},v.onerror=f.onerror=I});f.readAsDataURL(r),await S}else t.bitmap=await createImageBitmap(r);t.refCounter=1}catch(r){console.error(r),t=null}return this.#s.set(s,t),t&&this.#s.set(t.id,t),t}async getFromFile(s){const{lastModified:g,name:t,size:r,type:c}=s;return this.#n(`${g}_${t}_${r}_${c}`,s)}async getFromUrl(s){return this.#n(s,s)}async getFromId(s){this.#s||=new Map;const g=this.#s.get(s);return g?g.bitmap?(g.refCounter+=1,g):g.file?this.getFromFile(g.file):this.getFromUrl(g.url):null}getSvgUrl(s){const g=this.#s.get(s);return g?.isSvg?g.svgUrl:null}deleteId(s){this.#s||=new Map;const g=this.#s.get(s);g&&(g.refCounter-=1,g.refCounter===0&&(g.bitmap=null))}isValidId(s){return s.startsWith(`image_${this.#t}_`)}}class A{#t=[];#e=!1;#s;#n=-1;constructor(s=128){this.#s=s}add({cmd:s,undo:g,post:t,mustExec:r,type:c=NaN,overwriteIfSameType:f=!1,keepUndo:v=!1}){if(r&&s(),this.#e)return;const S={cmd:s,undo:g,post:t,type:c};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(S);return}if(f&&this.#t[this.#n].type===c){v&&(S.undo=this.#t[this.#n].undo),this.#t[this.#n]=S;return}const M=this.#n+1;M===this.#s?this.#t.splice(0,1):(this.#n=M,Mc===g[f]))return d._colorsMapping.get(t);return g}getHexCode(s){const g=this._colors.get(s);return g?y.Util.makeHexColor(...g):s}}class u{#t=null;#e=new Map;#s=new Map;#n=null;#r=null;#i=new A;#a=0;#l=new Set;#h=null;#d=null;#u=new Set;#c=!1;#o=null;#p=null;#g=null;#f=!1;#m=null;#b=new C;#A=!1;#w=!1;#E=null;#L=null;#M=null;#y=y.AnnotationEditorType.NONE;#v=new Set;#S=null;#x=null;#T=null;#F=this.blur.bind(this);#k=this.focus.bind(this);#I=this.copy.bind(this);#R=this.cut.bind(this);#_=this.paste.bind(this);#P=this.keydown.bind(this);#D=this.keyup.bind(this);#G=this.onEditingAction.bind(this);#$=this.onPageChanging.bind(this);#X=this.onScaleChanging.bind(this);#U=this.#nt.bind(this);#B=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#V=[0,0];#O=null;#z=null;#q=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const s=u.prototype,g=f=>f.#z.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&f.hasSomethingToControl(),t=(f,{target:v})=>{if(v instanceof HTMLInputElement){const{type:S}=v;return S!=="text"&&S!=="number"}return!0},r=this.TRANSLATE_SMALL,c=this.TRANSLATE_BIG;return(0,y.shadow)(this,"_keyboardManager",new o([[["ctrl+a","mac+meta+a"],s.selectAll,{checker:t}],[["ctrl+z","mac+meta+z"],s.undo,{checker:t}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],s.redo,{checker:t}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],s.delete,{checker:t}],[["Enter","mac+Enter"],s.addNewEditorFromKeyboard,{checker:(f,{target:v})=>!(v instanceof HTMLButtonElement)&&f.#z.contains(v)&&!f.isEnterHandled}],[[" ","mac+ "],s.addNewEditorFromKeyboard,{checker:(f,{target:v})=>!(v instanceof HTMLButtonElement)&&f.#z.contains(document.activeElement)}],[["Escape","mac+Escape"],s.unselectAll],[["ArrowLeft","mac+ArrowLeft"],s.translateSelectedEditors,{args:[-r,0],checker:g}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],s.translateSelectedEditors,{args:[-c,0],checker:g}],[["ArrowRight","mac+ArrowRight"],s.translateSelectedEditors,{args:[r,0],checker:g}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],s.translateSelectedEditors,{args:[c,0],checker:g}],[["ArrowUp","mac+ArrowUp"],s.translateSelectedEditors,{args:[0,-r],checker:g}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],s.translateSelectedEditors,{args:[0,-c],checker:g}],[["ArrowDown","mac+ArrowDown"],s.translateSelectedEditors,{args:[0,r],checker:g}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],s.translateSelectedEditors,{args:[0,c],checker:g}]]))}constructor(s,g,t,r,c,f,v,S,M){this.#z=s,this.#q=g,this.#n=t,this._eventBus=r,this._eventBus._on("editingaction",this.#G),this._eventBus._on("pagechanging",this.#$),this._eventBus._on("scalechanging",this.#X),this._eventBus._on("rotationchanging",this.#B),this.#rt(),this.#J(),this.#r=c.annotationStorage,this.#o=c.filterFactory,this.#x=f,this.#g=v||null,this.#c=S,this.#M=M||null,this.viewParameters={realScale:z.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}destroy(){this.#Q(),this.#K(),this._eventBus._off("editingaction",this.#G),this._eventBus._off("pagechanging",this.#$),this._eventBus._off("scalechanging",this.#X),this._eventBus._off("rotationchanging",this.#B);for(const s of this.#s.values())s.destroy();this.#s.clear(),this.#e.clear(),this.#u.clear(),this.#t=null,this.#v.clear(),this.#i.destroy(),this.#n?.destroy(),this.#m?.hide(),this.#m=null,this.#p&&(clearTimeout(this.#p),this.#p=null),this.#O&&(clearTimeout(this.#O),this.#O=null),this.#at()}async mlGuess(s){return this.#M?.guess(s)||null}get hasMLManager(){return!!this.#M}get hcmFilter(){return(0,y.shadow)(this,"hcmFilter",this.#x?this.#o.addHCMFilter(this.#x.foreground,this.#x.background):"none")}get direction(){return(0,y.shadow)(this,"direction",getComputedStyle(this.#z).direction)}get highlightColors(){return(0,y.shadow)(this,"highlightColors",this.#g?new Map(this.#g.split(",").map(s=>s.split("=").map(g=>g.trim()))):null)}get highlightColorNames(){return(0,y.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,s=>s.reverse())):null)}setMainHighlightColorPicker(s){this.#L=s}editAltText(s){this.#n?.editAltText(this,s)}onPageChanging({pageNumber:s}){this.#a=s-1}focusMainContainer(){this.#z.focus()}findParent(s,g){for(const t of this.#s.values()){const{x:r,y:c,width:f,height:v}=t.div.getBoundingClientRect();if(s>=r&&s<=r+f&&g>=c&&g<=c+v)return t}return null}disableUserSelect(s=!1){this.#q.classList.toggle("noUserSelect",s)}addShouldRescale(s){this.#u.add(s)}removeShouldRescale(s){this.#u.delete(s)}onScaleChanging({scale:s}){this.commitOrRemove(),this.viewParameters.realScale=s*z.PixelsPerInch.PDF_TO_CSS_UNITS;for(const g of this.#u)g.onScaleChanging()}onRotationChanging({pagesRotation:s}){this.commitOrRemove(),this.viewParameters.rotation=s}#Y({anchorNode:s}){return s.nodeType===Node.TEXT_NODE?s.parentElement:s}highlightSelection(s=""){const g=document.getSelection();if(!g||g.isCollapsed)return;const{anchorNode:t,anchorOffset:r,focusNode:c,focusOffset:f}=g,v=g.toString(),M=this.#Y(g).closest(".textLayer"),I=this.getSelectionBoxes(M);if(I){g.empty(),this.#y===y.AnnotationEditorType.NONE&&(this._eventBus.dispatch("showannotationeditorui",{source:this,mode:y.AnnotationEditorType.HIGHLIGHT}),this.showAllEditors("highlight",!0,!0));for(const O of this.#s.values())if(O.hasTextLayer(M)){O.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:s,boxes:I,anchorNode:t,anchorOffset:r,focusNode:c,focusOffset:f,text:v});break}}}#it(){const s=document.getSelection();if(!s||s.isCollapsed)return;const t=this.#Y(s).closest(".textLayer"),r=this.getSelectionBoxes(t);r&&(this.#m||=new _.HighlightToolbar(this),this.#m.show(t,r,this.direction==="ltr"))}addToAnnotationStorage(s){!s.isEmpty()&&this.#r&&!this.#r.has(s.id)&&this.#r.setValue(s.id,s)}#nt(){const s=document.getSelection();if(!s||s.isCollapsed){this.#S&&(this.#m?.hide(),this.#S=null,this.#C({hasSelectedText:!1}));return}const{anchorNode:g}=s;if(g===this.#S)return;if(!this.#Y(s).closest(".textLayer")){this.#S&&(this.#m?.hide(),this.#S=null,this.#C({hasSelectedText:!1}));return}if(this.#m?.hide(),this.#S=g,this.#C({hasSelectedText:!0}),!(this.#y!==y.AnnotationEditorType.HIGHLIGHT&&this.#y!==y.AnnotationEditorType.NONE)&&(this.#y===y.AnnotationEditorType.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#f=this.isShiftKeyDown,!this.isShiftKeyDown)){const c=f=>{f.type==="pointerup"&&f.button!==0||(window.removeEventListener("pointerup",c),window.removeEventListener("blur",c),f.type==="pointerup"&&this.#W("main_toolbar"))};window.addEventListener("pointerup",c),window.addEventListener("blur",c)}}#W(s=""){this.#y===y.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(s):this.#c&&this.#it()}#rt(){document.addEventListener("selectionchange",this.#U)}#at(){document.removeEventListener("selectionchange",this.#U)}#ot(){window.addEventListener("focus",this.#k),window.addEventListener("blur",this.#F)}#K(){window.removeEventListener("focus",this.#k),window.removeEventListener("blur",this.#F)}blur(){if(this.isShiftKeyDown=!1,this.#f&&(this.#f=!1,this.#W("main_toolbar")),!this.hasSelection)return;const{activeElement:s}=document;for(const g of this.#v)if(g.div.contains(s)){this.#E=[g,s],g._focusEventsAllowed=!1;break}}focus(){if(!this.#E)return;const[s,g]=this.#E;this.#E=null,g.addEventListener("focusin",()=>{s._focusEventsAllowed=!0},{once:!0}),g.focus()}#J(){window.addEventListener("keydown",this.#P),window.addEventListener("keyup",this.#D)}#Q(){window.removeEventListener("keydown",this.#P),window.removeEventListener("keyup",this.#D)}#Z(){document.addEventListener("copy",this.#I),document.addEventListener("cut",this.#R),document.addEventListener("paste",this.#_)}#tt(){document.removeEventListener("copy",this.#I),document.removeEventListener("cut",this.#R),document.removeEventListener("paste",this.#_)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(s){if(s.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;const g=[];for(const t of this.#v){const r=t.serialize(!0);r&&g.push(r)}g.length!==0&&s.clipboardData.setData("application/pdfjs",JSON.stringify(g))}cut(s){this.copy(s),this.delete()}paste(s){s.preventDefault();const{clipboardData:g}=s;for(const c of g.items)for(const f of this.#d)if(f.isHandlingMimeForPasting(c.type)){f.paste(c,this.currentLayer);return}let t=g.getData("application/pdfjs");if(!t)return;try{t=JSON.parse(t)}catch(c){(0,y.warn)(`paste: "${c.message}".`);return}if(!Array.isArray(t))return;this.unselectAll();const r=this.currentLayer;try{const c=[];for(const S of t){const M=r.deserialize(S);if(!M)return;c.push(M)}const f=()=>{for(const S of c)this.#et(S);this.#st(c)},v=()=>{for(const S of c)S.remove()};this.addCommands({cmd:f,undo:v,mustExec:!0})}catch(c){(0,y.warn)(`paste: "${c.message}".`)}}keydown(s){!this.isShiftKeyDown&&s.key==="Shift"&&(this.isShiftKeyDown=!0),this.#y!==y.AnnotationEditorType.NONE&&!this.isEditorHandlingKeyboard&&u._keyboardManager.exec(this,s)}keyup(s){this.isShiftKeyDown&&s.key==="Shift"&&(this.isShiftKeyDown=!1,this.#f&&(this.#f=!1,this.#W("main_toolbar")))}onEditingAction({name:s}){switch(s){case"undo":case"redo":case"delete":case"selectAll":this[s]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#C(s){Object.entries(s).some(([t,r])=>this.#N[t]!==r)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,s)}),this.#y===y.AnnotationEditorType.HIGHLIGHT&&s.hasSelectedEditor===!1&&this.#H([[y.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#H(s){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:s})}setEditingState(s){s?(this.#ot(),this.#Z(),this.#C({isEditing:this.#y!==y.AnnotationEditorType.NONE,isEmpty:this.#j(),hasSomethingToUndo:this.#i.hasSomethingToUndo(),hasSomethingToRedo:this.#i.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#K(),this.#tt(),this.#C({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(s){if(!this.#d){this.#d=s;for(const g of this.#d)this.#H(g.defaultPropertiesToUpdate)}}getId(){return this.#b.id}get currentLayer(){return this.#s.get(this.#a)}getLayer(s){return this.#s.get(s)}get currentPageIndex(){return this.#a}addLayer(s){this.#s.set(s.pageIndex,s),this.#A?s.enable():s.disable()}removeLayer(s){this.#s.delete(s.pageIndex)}updateMode(s,g=null,t=!1){if(this.#y!==s){if(this.#y=s,s===y.AnnotationEditorType.NONE){this.setEditingState(!1),this.#lt();return}this.setEditingState(!0),this.#ht(),this.unselectAll();for(const r of this.#s.values())r.updateMode(s);if(!g&&t){this.addNewEditorFromKeyboard();return}if(g){for(const r of this.#e.values())if(r.annotationElementId===g){this.setSelected(r),r.enterInEditMode();break}}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(s){s!==this.#y&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:s})}updateParams(s,g){if(this.#d){switch(s){case y.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case y.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#L?.updateColor(g);break;case y.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#T||=new Map).set(s,g),this.showAllEditors("highlight",g);break}for(const t of this.#v)t.updateParams(s,g);for(const t of this.#d)t.updateDefaultParams(s,g)}}showAllEditors(s,g,t=!1){for(const c of this.#e.values())c.editorType===s&&c.show(g);(this.#T?.get(y.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==g&&this.#H([[y.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,g]])}enableWaiting(s=!1){if(this.#w!==s){this.#w=s;for(const g of this.#s.values())s?g.disableClick():g.enableClick(),g.div.classList.toggle("waiting",s)}}#ht(){if(!this.#A){this.#A=!0;for(const s of this.#s.values())s.enable();for(const s of this.#e.values())s.enable()}}#lt(){if(this.unselectAll(),this.#A){this.#A=!1;for(const s of this.#s.values())s.disable();for(const s of this.#e.values())s.disable()}}getEditors(s){const g=[];for(const t of this.#e.values())t.pageIndex===s&&g.push(t);return g}getEditor(s){return this.#e.get(s)}addEditor(s){this.#e.set(s.id,s)}removeEditor(s){s.div.contains(document.activeElement)&&(this.#p&&clearTimeout(this.#p),this.#p=setTimeout(()=>{this.focusMainContainer(),this.#p=null},0)),this.#e.delete(s.id),this.unselect(s),(!s.annotationElementId||!this.#l.has(s.annotationElementId))&&this.#r?.remove(s.id)}addDeletedAnnotationElement(s){this.#l.add(s.annotationElementId),s.deleted=!0}isDeletedAnnotationElement(s){return this.#l.has(s)}removeDeletedAnnotationElement(s){this.#l.delete(s.annotationElementId),s.deleted=!1}#et(s){const g=this.#s.get(s.pageIndex);g?g.addOrRebuild(s):(this.addEditor(s),this.addToAnnotationStorage(s))}setActiveEditor(s){this.#t!==s&&(this.#t=s,s&&this.#H(s.propertiesToUpdate))}get#ct(){let s=null;for(s of this.#v);return s}updateUI(s){this.#ct===s&&this.#H(s.propertiesToUpdate)}toggleSelected(s){if(this.#v.has(s)){this.#v.delete(s),s.unselect(),this.#C({hasSelectedEditor:this.hasSelection});return}this.#v.add(s),s.select(),this.#H(s.propertiesToUpdate),this.#C({hasSelectedEditor:!0})}setSelected(s){for(const g of this.#v)g!==s&&g.unselect();this.#v.clear(),this.#v.add(s),s.select(),this.#H(s.propertiesToUpdate),this.#C({hasSelectedEditor:!0})}isSelected(s){return this.#v.has(s)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(s){s.unselect(),this.#v.delete(s),this.#C({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#v.size!==0}get isEnterHandled(){return this.#v.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#i.undo(),this.#C({hasSomethingToUndo:this.#i.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#j()})}redo(){this.#i.redo(),this.#C({hasSomethingToUndo:!0,hasSomethingToRedo:this.#i.hasSomethingToRedo(),isEmpty:this.#j()})}addCommands(s){this.#i.add(s),this.#C({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#j()})}#j(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(const s of this.#e.values())return s.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const s=[...this.#v],g=()=>{for(const r of s)r.remove()},t=()=>{for(const r of s)this.#et(r)};this.addCommands({cmd:g,undo:t,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#st(s){for(const g of this.#v)g.unselect();this.#v.clear();for(const g of s)g.isEmpty()||(this.#v.add(g),g.select());this.#C({hasSelectedEditor:this.hasSelection})}selectAll(){for(const s of this.#v)s.commit();this.#st(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#y!==y.AnnotationEditorType.NONE))&&this.hasSelection){for(const s of this.#v)s.unselect();this.#v.clear(),this.#C({hasSelectedEditor:!1})}}translateSelectedEditors(s,g,t=!1){if(t||this.commitOrRemove(),!this.hasSelection)return;this.#V[0]+=s,this.#V[1]+=g;const[r,c]=this.#V,f=[...this.#v],v=1e3;this.#O&&clearTimeout(this.#O),this.#O=setTimeout(()=>{this.#O=null,this.#V[0]=this.#V[1]=0,this.addCommands({cmd:()=>{for(const S of f)this.#e.has(S.id)&&S.translateInPage(r,c)},undo:()=>{for(const S of f)this.#e.has(S.id)&&S.translateInPage(-r,-c)},mustExec:!1})},v);for(const S of f)S.translateInPage(s,g)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#h=new Map;for(const s of this.#v)this.#h.set(s,{savedX:s.x,savedY:s.y,savedPageIndex:s.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#h)return!1;this.disableUserSelect(!1);const s=this.#h;this.#h=null;let g=!1;for(const[{x:r,y:c,pageIndex:f},v]of s)v.newX=r,v.newY=c,v.newPageIndex=f,g||=r!==v.savedX||c!==v.savedY||f!==v.savedPageIndex;if(!g)return!1;const t=(r,c,f,v)=>{if(this.#e.has(r.id)){const S=this.#s.get(v);S?r._setParentAndPosition(S,c,f):(r.pageIndex=v,r.x=c,r.y=f)}};return this.addCommands({cmd:()=>{for(const[r,{newX:c,newY:f,newPageIndex:v}]of s)t(r,c,f,v)},undo:()=>{for(const[r,{savedX:c,savedY:f,savedPageIndex:v}]of s)t(r,c,f,v)},mustExec:!0}),!0}dragSelectedEditors(s,g){if(this.#h)for(const t of this.#h.keys())t.drag(s,g)}rebuild(s){if(s.parent===null){const g=this.getLayer(s.pageIndex);g?(g.changeParent(s),g.addOrRebuild(s)):(this.addEditor(s),this.addToAnnotationStorage(s),s.rebuild())}else s.parent.addOrRebuild(s)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(s){return this.#t===s}getActive(){return this.#t}getMode(){return this.#y}get imageManager(){return(0,y.shadow)(this,"imageManager",new T)}getSelectionBoxes(s){if(!s)return null;const g=document.getSelection();for(let M=0,I=g.rangeCount;M({x:(I-r)/f,y:1-(M+O-t)/c,width:N/f,height:O/c});break;case"180":v=(M,I,O,N)=>({x:1-(M+O-t)/c,y:1-(I+N-r)/f,width:O/c,height:N/f});break;case"270":v=(M,I,O,N)=>({x:1-(I+N-r)/f,y:(M-t)/c,width:N/f,height:O/c});break;default:v=(M,I,O,N)=>({x:(M-t)/c,y:(I-r)/f,width:O/c,height:N/f});break}const S=[];for(let M=0,I=g.rangeCount;M{V.d(et,{PDFFetchStream:()=>C});var y=V(292),z=V(490);function _(o,d,u){return{method:"GET",headers:o,signal:u.signal,mode:"cors",credentials:d?"include":"same-origin",redirect:"follow"}}function U(o){const d=new Headers;for(const u in o){const b=o[u];b!==void 0&&d.append(u,b)}return d}function F(o){return o instanceof Uint8Array?o.buffer:o instanceof ArrayBuffer?o:((0,y.warn)(`getArrayBuffer - unexpected data format: ${o}`),new Uint8Array(o).buffer)}class C{constructor(d){this.source=d,this.isHttp=/^https?:/i.test(d.url),this.httpHeaders=this.isHttp&&d.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,y.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new T(this),this._fullRequestReader}getRangeReader(d,u){if(u<=this._progressiveDataLength)return null;const b=new A(this,d,u);return this._rangeRequestReaders.push(b),b}cancelAllRequests(d){this._fullRequestReader?.cancel(d);for(const u of this._rangeRequestReaders.slice(0))u.cancel(d)}}class T{constructor(d){this._stream=d,this._reader=null,this._loaded=0,this._filename=null;const u=d.source;this._withCredentials=u.withCredentials||!1,this._contentLength=u.length,this._headersCapability=Promise.withResolvers(),this._disableRange=u.disableRange||!1,this._rangeChunkSize=u.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!u.disableStream,this._isRangeSupported=!u.disableRange,this._headers=U(this._stream.httpHeaders);const b=u.url;fetch(b,_(this._headers,this._withCredentials,this._abortController)).then(s=>{if(!(0,z.validateResponseStatus)(s.status))throw(0,z.createResponseStatusError)(s.status,b);this._reader=s.body.getReader(),this._headersCapability.resolve();const g=c=>s.headers.get(c),{allowRangeRequests:t,suggestedLength:r}=(0,z.validateRangeRequestCapabilities)({getResponseHeader:g,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=t,this._contentLength=r||this._contentLength,this._filename=(0,z.extractFilenameFromHeader)(g),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new y.AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:d,done:u}=await this._reader.read();return u?{value:d,done:u}:(this._loaded+=d.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:F(d),done:!1})}cancel(d){this._reader?.cancel(d),this._abortController.abort()}}class A{constructor(d,u,b){this._stream=d,this._reader=null,this._loaded=0;const s=d.source;this._withCredentials=s.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!s.disableStream,this._abortController=new AbortController,this._headers=U(this._stream.httpHeaders),this._headers.append("Range",`bytes=${u}-${b-1}`);const g=s.url;fetch(g,_(this._headers,this._withCredentials,this._abortController)).then(t=>{if(!(0,z.validateResponseStatus)(t.status))throw(0,z.createResponseStatusError)(t.status,g);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:d,done:u}=await this._reader.read();return u?{value:d,done:u}:(this._loaded+=d.byteLength,this.onProgress?.({loaded:this._loaded}),{value:F(d),done:!1})}cancel(d){this._reader?.cancel(d),this._abortController.abort()}}},10:(dt,et,V)=>{V.d(et,{FontFaceObject:()=>_,FontLoader:()=>z});var y=V(292);class z{#t=new Set;constructor({ownerDocument:F=globalThis.document,styleElement:C=null}){this._document=F,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(F){this.nativeFontFaces.add(F),this._document.fonts.add(F)}removeNativeFontFace(F){this.nativeFontFaces.delete(F),this._document.fonts.delete(F)}insertRule(F){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const C=this.styleElement.sheet;C.insertRule(F,C.cssRules.length)}clear(){for(const F of this.nativeFontFaces)this._document.fonts.delete(F);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:F,_inspectFont:C}){if(!(!F||this.#t.has(F.loadedName))){if((0,y.assert)(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:T,src:A,style:o}=F,d=new FontFace(T,A,o);this.addNativeFontFace(d);try{await d.load(),this.#t.add(T),C?.(F)}catch{(0,y.warn)(`Cannot load system font: ${F.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(d)}return}(0,y.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(F){if(F.attached||F.missingFile&&!F.systemFontInfo)return;if(F.attached=!0,F.systemFontInfo){await this.loadSystemFont(F);return}if(this.isFontLoadingAPISupported){const T=F.createNativeFontFace();if(T){this.addNativeFontFace(T);try{await T.loaded}catch(A){throw(0,y.warn)(`Failed to load font '${T.family}': '${A}'.`),F.disableFontFace=!0,A}}return}const C=F.createFontFaceRule();if(C){if(this.insertRule(C),this.isSyncFontLoadingSupported)return;await new Promise(T=>{const A=this._queueLoadingCallback(T);this._prepareFontLoadEvent(F,A)})}}get isFontLoadingAPISupported(){const F=!!this._document?.fonts;return(0,y.shadow)(this,"isFontLoadingAPISupported",F)}get isSyncFontLoadingSupported(){let F=!1;return(y.isNodeJS||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(F=!0),(0,y.shadow)(this,"isSyncFontLoadingSupported",F)}_queueLoadingCallback(F){function C(){for((0,y.assert)(!A.done,"completeRequest() cannot be called twice."),A.done=!0;T.length>0&&T[0].done;){const o=T.shift();setTimeout(o.callback,0)}}const{loadingRequests:T}=this,A={done:!1,complete:C,callback:F};return T.push(A),A}get _loadTestFont(){const F=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,y.shadow)(this,"_loadTestFont",F)}_prepareFontLoadEvent(F,C){function T(N,B){return N.charCodeAt(B)<<24|N.charCodeAt(B+1)<<16|N.charCodeAt(B+2)<<8|N.charCodeAt(B+3)&255}function A(N,B,q,st){const X=N.substring(0,B),H=N.substring(B+q);return X+st+H}let o,d;const u=this._document.createElement("canvas");u.width=1,u.height=1;const b=u.getContext("2d");let s=0;function g(N,B){if(++s>30){(0,y.warn)("Load test font never loaded."),B();return}if(b.font="30px "+N,b.fillText(".",0,20),b.getImageData(0,0,1,1).data[3]>0){B();return}setTimeout(g.bind(null,N,B))}const t=`lt${Date.now()}${this.loadTestFontId++}`;let r=this._loadTestFont;r=A(r,976,t.length,t);const f=16,v=1482184792;let S=T(r,f);for(o=0,d=t.length-3;o{O.remove(),C.complete()})}}class _{constructor(F,{isEvalSupported:C=!0,disableFontFace:T=!1,ignoreErrors:A=!1,inspectFont:o=null}){this.compiledGlyphs=Object.create(null);for(const d in F)this[d]=F[d];this.isEvalSupported=C!==!1,this.disableFontFace=T===!0,this.ignoreErrors=A===!0,this._inspectFont=o}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let F;if(!this.cssFontInfo)F=new FontFace(this.loadedName,this.data,{});else{const C={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(C.style=`oblique ${this.cssFontInfo.italicAngle}deg`),F=new FontFace(this.cssFontInfo.fontFamily,this.data,C)}return this._inspectFont?.(this),F}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const F=(0,y.bytesToString)(this.data),C=`url(data:${this.mimetype};base64,${btoa(F)});`;let T;if(!this.cssFontInfo)T=`@font-face {font-family:"${this.loadedName}";src:${C}}`;else{let A=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(A+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),T=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${A}src:${C}}`}return this._inspectFont?.(this,C),T}getPathGenerator(F,C){if(this.compiledGlyphs[C]!==void 0)return this.compiledGlyphs[C];let T;try{T=F.get(this.loadedName+"_path_"+C)}catch(A){if(!this.ignoreErrors)throw A;return(0,y.warn)(`getPathGenerator - ignoring character: "${A}".`),this.compiledGlyphs[C]=function(o,d){}}if(this.isEvalSupported&&y.FeatureTest.isEvalSupported){const A=[];for(const o of T){const d=o.args!==void 0?o.args.join(","):"";A.push("c.",o.cmd,"(",d,`); +`)}return this.compiledGlyphs[C]=new Function("c","size",A.join(""))}return this.compiledGlyphs[C]=function(A,o){for(const d of T)d.cmd==="scale"&&(d.args=[o,-o]),A[d.cmd].apply(A,d.args)}}}},62:(dt,et,V)=>{V.d(et,{Metadata:()=>z});var y=V(292);class z{#t;#e;constructor({parsedData:U,rawData:F}){this.#t=U,this.#e=F}getRaw(){return this.#e}get(U){return this.#t.get(U)??null}getAll(){return(0,y.objectFromMap)(this.#t)}has(U){return this.#t.has(U)}}},457:(dt,et,V)=>{V.d(et,{PDFNetworkStream:()=>T});var y=V(292),z=V(490);const _=200,U=206;function F(d){const u=d.response;return typeof u!="string"?u:(0,y.stringToBytes)(u).buffer}class C{constructor(u,b={}){this.url=u,this.isHttp=/^https?:/i.test(u),this.httpHeaders=this.isHttp&&b.httpHeaders||Object.create(null),this.withCredentials=b.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(u,b,s){const g={begin:u,end:b};for(const t in s)g[t]=s[t];return this.request(g)}requestFull(u){return this.request(u)}request(u){const b=new XMLHttpRequest,s=this.currXhrId++,g=this.pendingRequests[s]={xhr:b};b.open("GET",this.url),b.withCredentials=this.withCredentials;for(const t in this.httpHeaders){const r=this.httpHeaders[t];r!==void 0&&b.setRequestHeader(t,r)}return this.isHttp&&"begin"in u&&"end"in u?(b.setRequestHeader("Range",`bytes=${u.begin}-${u.end-1}`),g.expectedStatus=U):g.expectedStatus=_,b.responseType="arraybuffer",u.onError&&(b.onerror=function(t){u.onError(b.status)}),b.onreadystatechange=this.onStateChange.bind(this,s),b.onprogress=this.onProgress.bind(this,s),g.onHeadersReceived=u.onHeadersReceived,g.onDone=u.onDone,g.onError=u.onError,g.onProgress=u.onProgress,b.send(null),s}onProgress(u,b){const s=this.pendingRequests[u];s&&s.onProgress?.(b)}onStateChange(u,b){const s=this.pendingRequests[u];if(!s)return;const g=s.xhr;if(g.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),g.readyState!==4||!(u in this.pendingRequests))return;if(delete this.pendingRequests[u],g.status===0&&this.isHttp){s.onError?.(g.status);return}const t=g.status||_;if(!(t===_&&s.expectedStatus===U)&&t!==s.expectedStatus){s.onError?.(g.status);return}const c=F(g);if(t===U){const f=g.getResponseHeader("Content-Range"),v=/bytes (\d+)-(\d+)\/(\d+)/.exec(f);s.onDone({begin:parseInt(v[1],10),chunk:c})}else c?s.onDone({begin:0,chunk:c}):s.onError?.(g.status)}getRequestXhr(u){return this.pendingRequests[u].xhr}isPendingRequest(u){return u in this.pendingRequests}abortRequest(u){const b=this.pendingRequests[u].xhr;delete this.pendingRequests[u],b.abort()}}class T{constructor(u){this._source=u,this._manager=new C(u.url,{httpHeaders:u.httpHeaders,withCredentials:u.withCredentials}),this._rangeChunkSize=u.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(u){const b=this._rangeRequestReaders.indexOf(u);b>=0&&this._rangeRequestReaders.splice(b,1)}getFullReader(){return(0,y.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new A(this._manager,this._source),this._fullRequestReader}getRangeReader(u,b){const s=new o(this._manager,u,b);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(u){this._fullRequestReader?.cancel(u);for(const b of this._rangeRequestReaders.slice(0))b.cancel(u)}}class A{constructor(u,b){this._manager=u;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=b.url,this._fullRequestId=u.requestFull(s),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=b.disableRange||!1,this._contentLength=b.length,this._rangeChunkSize=b.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 u=this._fullRequestId,b=this._manager.getRequestXhr(u),s=r=>b.getResponseHeader(r),{allowRangeRequests:g,suggestedLength:t}=(0,z.validateRangeRequestCapabilities)({getResponseHeader:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});g&&(this._isRangeSupported=!0),this._contentLength=t||this._contentLength,this._filename=(0,z.extractFilenameFromHeader)(s),this._isRangeSupported&&this._manager.abortRequest(u),this._headersReceivedCapability.resolve()}_onDone(u){if(u&&(this._requests.length>0?this._requests.shift().resolve({value:u.chunk,done:!1}):this._cachedChunks.push(u.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const b of this._requests)b.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(u){this._storedError=(0,z.createResponseStatusError)(u,this._url),this._headersReceivedCapability.reject(this._storedError);for(const b of this._requests)b.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(u){this.onProgress?.({loaded:u.loaded,total:u.lengthComputable?u.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._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0,this._headersReceivedCapability.reject(u);for(const b of this._requests)b.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class o{constructor(u,b,s){this._manager=u;const g={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=u.url,this._requestId=u.requestRange(b,s,g),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(u){const b=u.chunk;this._requests.length>0?this._requests.shift().resolve({value:b,done:!1}):this._queuedChunk=b,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(u){this._storedError=(0,z.createResponseStatusError)(u,this._url);for(const b of this._requests)b.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(u){this.isStreamingSupported||this.onProgress?.({loaded:u.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const b=this._queuedChunk;return this._queuedChunk=null,{value:b,done:!1}}if(this._done)return{value:void 0,done:!0};const u=Promise.withResolvers();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(const b of this._requests)b.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},490:(dt,et,V)=>{V.d(et,{createResponseStatusError:()=>C,extractFilenameFromHeader:()=>F,validateRangeRequestCapabilities:()=>U,validateResponseStatus:()=>T});var y=V(292);function z(A){let o=!0,d=u("filename\\*","i").exec(A);if(d){d=d[1];let f=t(d);return f=unescape(f),f=r(f),f=c(f),s(f)}if(d=g(A),d){const f=c(d);return s(f)}if(d=u("filename","i").exec(A),d){d=d[1];let f=t(d);return f=c(f),s(f)}function u(f,v){return new RegExp("(?:^|;)\\s*"+f+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',v)}function b(f,v){if(f){if(!/^[\x00-\xFF]+$/.test(v))return v;try{const S=new TextDecoder(f,{fatal:!0}),M=(0,y.stringToBytes)(v);v=S.decode(M),o=!1}catch{}}return v}function s(f){return o&&/[\x80-\xff]/.test(f)&&(f=b("utf-8",f),o&&(f=b("iso-8859-1",f))),f}function g(f){const v=[];let S;const M=u("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(S=M.exec(f))!==null;){let[,O,N,B]=S;if(O=parseInt(O,10),O in v){if(O===0)break;continue}v[O]=[N,B]}const I=[];for(let O=0;O{V.a(dt,async(y,z)=>{try{let d=function(v){const S=A.parse(v);return S.protocol==="file:"||S.host?S:/^[a-z]:[/\\]/i.test(v)?A.parse(`file:///${v}`):(S.host||(S.protocol="file:"),S)},g=function(v,S){return{protocol:v.protocol,auth:v.auth,host:v.hostname,port:v.port,path:v.path,method:"GET",headers:S}};V.d(et,{PDFNodeStream:()=>u});var _=V(292),U=V(490);let F,C,T,A;_.isNodeJS&&(F=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[]),C=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[]),T=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[]),A=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[]));const o=/^file:\/\/\/[a-zA-Z]:\//;class u{constructor(S){this.source=S,this.url=d(S.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&S.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,_.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new c(this):new t(this),this._fullRequestReader}getRangeReader(S,M){if(M<=this._progressiveDataLength)return null;const I=this.isFsUrl?new f(this,S,M):new r(this,S,M);return this._rangeRequestReaders.push(I),I}cancelAllRequests(S){this._fullRequestReader?.cancel(S);for(const M of this._rangeRequestReaders.slice(0))M.cancel(S)}}class b{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null;const M=S.source;this._contentLength=M.length,this._loaded=0,this._filename=null,this._disableRange=M.disableRange||!1,this._rangeChunkSize=M.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!M.disableStream,this._isRangeSupported=!M.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){if(!this._readableStream){this._error(S);return}this._readableStream.destroy(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",()=>{this._readCapability.resolve()}),S.on("end",()=>{S.destroy(),this._done=!0,this._readCapability.resolve()}),S.on("error",M=>{this._error(M)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new _.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class s{constructor(S){this._url=S.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const M=S.source;this._isStreamingSupported=!M.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const S=this._readableStream.read();return S===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=S.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(S).buffer,done:!1})}cancel(S){if(!this._readableStream){this._error(S);return}this._readableStream.destroy(S)}_error(S){this._storedError=S,this._readCapability.resolve()}_setReadableStream(S){this._readableStream=S,S.on("readable",()=>{this._readCapability.resolve()}),S.on("end",()=>{S.destroy(),this._done=!0,this._readCapability.resolve()}),S.on("error",M=>{this._error(M)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class t extends b{constructor(S){super(S);const M=I=>{if(I.statusCode===404){const q=new _.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=q,this._headersCapability.reject(q);return}this._headersCapability.resolve(),this._setReadableStream(I);const O=q=>this._readableStream.headers[q.toLowerCase()],{allowRangeRequests:N,suggestedLength:B}=(0,U.validateRangeRequestCapabilities)({getResponseHeader:O,isHttp:S.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=N,this._contentLength=B||this._contentLength,this._filename=(0,U.extractFilenameFromHeader)(O)};this._request=null,this._url.protocol==="http:"?this._request=C.request(g(this._url,S.httpHeaders),M):this._request=T.request(g(this._url,S.httpHeaders),M),this._request.on("error",I=>{this._storedError=I,this._headersCapability.reject(I)}),this._request.end()}}class r extends s{constructor(S,M,I){super(S),this._httpHeaders={};for(const N in S.httpHeaders){const B=S.httpHeaders[N];B!==void 0&&(this._httpHeaders[N]=B)}this._httpHeaders.Range=`bytes=${M}-${I-1}`;const O=N=>{if(N.statusCode===404){const B=new _.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=B;return}this._setReadableStream(N)};this._request=null,this._url.protocol==="http:"?this._request=C.request(g(this._url,this._httpHeaders),O):this._request=T.request(g(this._url,this._httpHeaders),O),this._request.on("error",N=>{this._storedError=N}),this._request.end()}}class c extends b{constructor(S){super(S);let M=decodeURIComponent(this._url.path);o.test(this._url.href)&&(M=M.replace(/^\//,"")),F.promises.lstat(M).then(I=>{this._contentLength=I.size,this._setReadableStream(F.createReadStream(M)),this._headersCapability.resolve()},I=>{I.code==="ENOENT"&&(I=new _.MissingPDFException(`Missing PDF "${M}".`)),this._storedError=I,this._headersCapability.reject(I)})}}class f extends s{constructor(S,M,I){super(S);let O=decodeURIComponent(this._url.path);o.test(this._url.href)&&(O=O.replace(/^\//,"")),this._setReadableStream(F.createReadStream(O,{start:M,end:I-1}))}}z()}catch(F){z(F)}},1)},573:(dt,et,V)=>{V.a(dt,async(y,z)=>{try{V.d(et,{NodeCMapReaderFactory:()=>u,NodeCanvasFactory:()=>d,NodeFilterFactory:()=>o,NodeStandardFontDataFactory:()=>b});var _=V(583),U=V(292);let F,C,T;if(U.isNodeJS){F=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[]);try{C=await Rt(()=>import("./__vite-browser-external-b25bb000.js"),[])}catch{}try{T=await Rt(()=>import("./index-9d5554b1.js"),[])}catch{}}const A=function(s){return F.promises.readFile(s).then(g=>new Uint8Array(g))};class o extends _.BaseFilterFactory{}class d extends _.BaseCanvasFactory{_createCanvas(g,t){return C.createCanvas(g,t)}}class u extends _.BaseCMapReaderFactory{_fetchData(g,t){return A(g).then(r=>({cMapData:r,compressionType:t}))}}class b extends _.BaseStandardFontDataFactory{_fetchData(g){return A(g)}}z()}catch(F){z(F)}},1)},626:(dt,et,V)=>{V.d(et,{OptionalContentConfig:()=>F});var y=V(292),z=V(651);const _=Symbol("INTERNAL");class U{#t=!1;#e=!1;#s=!1;#n=!0;constructor(T,{name:A,intent:o,usage:d}){this.#t=!!(T&y.RenderingIntentFlag.DISPLAY),this.#e=!!(T&y.RenderingIntentFlag.PRINT),this.name=A,this.intent=o,this.usage=d}get visible(){if(this.#s)return this.#n;if(!this.#n)return!1;const{print:T,view:A}=this.usage;return this.#t?A?.viewState!=="OFF":this.#e?T?.printState!=="OFF":!0}_setVisible(T,A,o=!1){T!==_&&(0,y.unreachable)("Internal method `_setVisible` called."),this.#s=o,this.#n=A}}class F{#t=null;#e=new Map;#s=null;#n=null;constructor(T,A=y.RenderingIntentFlag.DISPLAY){if(this.renderingIntent=A,this.name=null,this.creator=null,T!==null){this.name=T.name,this.creator=T.creator,this.#n=T.order;for(const o of T.groups)this.#e.set(o.id,new U(A,o));if(T.baseState==="OFF")for(const o of this.#e.values())o._setVisible(_,!1);for(const o of T.on)this.#e.get(o)._setVisible(_,!0);for(const o of T.off)this.#e.get(o)._setVisible(_,!1);this.#s=this.getHash()}}#r(T){const A=T.length;if(A<2)return!0;const o=T[0];for(let d=1;d0?(0,y.objectFromMap)(this.#e):null}getGroup(T){return this.#e.get(T)||null}getHash(){if(this.#t!==null)return this.#t;const T=new z.MurmurHash3_64;for(const[A,o]of this.#e)T.update(`${A}:${o.visible}`);return this.#t=T.hexdigest()}}},814:(dt,et,V)=>{V.d(et,{cleanupTextLayer:()=>o,renderTextLayer:()=>t,updateTextLayer:()=>r});var y=V(292),z=V(419);const _=1e5,U=30,F=.8,C=new Map;let T=null;function A(){if(!T){const c=document.createElement("canvas");c.className="hiddenCanvasElement",document.body.append(c),T=c.getContext("2d",{alpha:!1})}return T}function o(){T?.canvas.remove(),T=null}function d(c){const f=C.get(c);if(f)return f;const v=A(),S=v.font;v.canvas.width=v.canvas.height=U,v.font=`${U}px ${c}`;const M=v.measureText("");let I=M.fontBoundingBoxAscent,O=Math.abs(M.fontBoundingBoxDescent);if(I){const B=I/(I+O);return C.set(c,B),v.canvas.width=v.canvas.height=0,v.font=S,B}v.strokeStyle="red",v.clearRect(0,0,U,U),v.strokeText("g",0,0);let N=v.getImageData(0,0,U,U).data;O=0;for(let B=N.length-1-3;B>=0;B-=4)if(N[B]>0){O=Math.ceil(B/4/U);break}v.clearRect(0,0,U,U),v.strokeText("A",0,U),N=v.getImageData(0,0,U,U).data,I=0;for(let B=0,q=N.length;B0){I=U-Math.floor(B/4/U);break}if(v.canvas.width=v.canvas.height=0,v.font=S,I){const B=I/(I+O);return C.set(c,B),B}return C.set(c,F),F}function u(c,f,v){const S=document.createElement("span"),M={angle:0,canvasWidth:0,hasText:f.str!=="",hasEOL:f.hasEOL,fontSize:0};c._textDivs.push(S);const I=y.Util.transform(c._transform,f.transform);let O=Math.atan2(I[1],I[0]);const N=v[f.fontName];N.vertical&&(O+=Math.PI/2);const B=c._fontInspectorEnabled&&N.fontSubstitution||N.fontFamily,q=Math.hypot(I[2],I[3]),st=q*d(B);let X,H;O===0?(X=I[4],H=I[5]-st):(X=I[4]+st*Math.sin(O),H=I[5]-st*Math.cos(O));const G="calc(var(--scale-factor)*",Y=S.style;c._container===c._rootContainer?(Y.left=`${(100*X/c._pageWidth).toFixed(2)}%`,Y.top=`${(100*H/c._pageHeight).toFixed(2)}%`):(Y.left=`${G}${X.toFixed(2)}px)`,Y.top=`${G}${H.toFixed(2)}px)`),Y.fontSize=`${G}${q.toFixed(2)}px)`,Y.fontFamily=B,M.fontSize=q,S.setAttribute("role","presentation"),S.textContent=f.str,S.dir=f.dir,c._fontInspectorEnabled&&(S.dataset.fontName=N.fontSubstitutionLoadedName||f.fontName),O!==0&&(M.angle=O*(180/Math.PI));let Q=!1;if(f.str.length>1)Q=!0;else if(f.str!==" "&&f.transform[0]!==f.transform[3]){const K=Math.abs(f.transform[0]),at=Math.abs(f.transform[3]);K!==at&&Math.max(K,at)/Math.min(K,at)>1.5&&(Q=!0)}Q&&(M.canvasWidth=N.vertical?f.height:f.width),c._textDivProperties.set(S,M),c._isReadableStream&&c._layoutText(S)}function b(c){const{div:f,scale:v,properties:S,ctx:M,prevFontSize:I,prevFontFamily:O}=c,{style:N}=f;let B="";if(S.canvasWidth!==0&&S.hasText){const{fontFamily:q}=N,{canvasWidth:st,fontSize:X}=S;(I!==X||O!==q)&&(M.font=`${X*v}px ${q}`,c.prevFontSize=X,c.prevFontFamily=q);const{width:H}=M.measureText(f.textContent);H>0&&(B=`scaleX(${st*v/H})`)}S.angle!==0&&(B=`rotate(${S.angle}deg) ${B}`),B.length>0&&(N.transform=B)}function s(c){if(c._canceled)return;const f=c._textDivs,v=c._capability;if(f.length>_){v.resolve();return}if(!c._isReadableStream)for(const M of f)c._layoutText(M);v.resolve()}class g{constructor({textContentSource:f,container:v,viewport:S,textDivs:M,textDivProperties:I,textContentItemsStr:O}){this._textContentSource=f,this._isReadableStream=f instanceof ReadableStream,this._container=this._rootContainer=v,this._textDivs=M||[],this._textContentItemsStr=O||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=I||new WeakMap,this._canceled=!1,this._capability=Promise.withResolvers(),this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:S.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:A()};const{pageWidth:N,pageHeight:B,pageX:q,pageY:st}=S.rawDims;this._transform=[1,0,0,-1,-q,st+B],this._pageWidth=N,this._pageHeight=B,(0,z.setLayerDimensions)(v,S),this._capability.promise.finally(()=>{this._layoutTextParams=null}).catch(()=>{})}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new y.AbortException("TextLayer task cancelled.")).catch(()=>{}),this._reader=null),this._capability.reject(new y.AbortException("TextLayer task cancelled."))}_processItems(f,v){for(const S of f){if(S.str===void 0){if(S.type==="beginMarkedContentProps"||S.type==="beginMarkedContent"){const M=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),S.id!==null&&this._container.setAttribute("id",`${S.id}`),M.append(this._container)}else S.type==="endMarkedContent"&&(this._container=this._container.parentNode);continue}this._textContentItemsStr.push(S.str),u(this,S,v)}}_layoutText(f){const v=this._layoutTextParams.properties=this._textDivProperties.get(f);if(this._layoutTextParams.div=f,b(this._layoutTextParams),v.hasText&&this._container.append(f),v.hasEOL){const S=document.createElement("br");S.setAttribute("role","presentation"),this._container.append(S)}}_render(){const{promise:f,resolve:v,reject:S}=Promise.withResolvers();let M=Object.create(null);if(this._isReadableStream){const I=()=>{this._reader.read().then(({value:O,done:N})=>{if(N){v();return}Object.assign(M,O.styles),this._processItems(O.items,M),I()},S)};this._reader=this._textContentSource.getReader(),I()}else if(this._textContentSource){const{items:I,styles:O}=this._textContentSource;this._processItems(I,O),v()}else throw new Error('No "textContentSource" parameter specified.');f.then(()=>{M=null,s(this)},this._capability.reject)}}function t(c){const f=new g(c);return f._render(),f}function r({container:c,viewport:f,textDivs:v,textDivProperties:S,mustRotate:M=!0,mustRescale:I=!0}){if(M&&(0,z.setLayerDimensions)(c,{rotation:f.rotation}),I){const O=A(),B={prevFontSize:null,prevFontFamily:null,div:null,scale:f.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:O};for(const q of v)B.properties=S.get(q),B.div=q,b(B)}}},585:(dt,et,V)=>{V.d(et,{PDFDataTransportStream:()=>_});var y=V(292),z=V(419);class _{constructor(T,{disableRange:A=!1,disableStream:o=!1}){(0,y.assert)(T,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:d,initialData:u,progressiveDone:b,contentDispositionFilename:s}=T;if(this._queuedChunks=[],this._progressiveDone=b,this._contentDispositionFilename=s,u?.length>0){const g=u instanceof Uint8Array&&u.byteLength===u.buffer.byteLength?u.buffer:new Uint8Array(u).buffer;this._queuedChunks.push(g)}this._pdfDataRangeTransport=T,this._isStreamingSupported=!o,this._isRangeSupported=!A,this._contentLength=d,this._fullRequestReader=null,this._rangeReaders=[],T.addRangeListener((g,t)=>{this._onReceiveData({begin:g,chunk:t})}),T.addProgressListener((g,t)=>{this._onProgress({loaded:g,total:t})}),T.addProgressiveReadListener(g=>{this._onReceiveData({chunk:g})}),T.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),T.transportReady()}_onReceiveData({begin:T,chunk:A}){const o=A instanceof Uint8Array&&A.byteLength===A.buffer.byteLength?A.buffer:new Uint8Array(A).buffer;if(T===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(o):this._queuedChunks.push(o);else{const d=this._rangeReaders.some(function(u){return u._begin!==T?!1:(u._enqueue(o),!0)});(0,y.assert)(d,"_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 A=this._rangeReaders.indexOf(T);A>=0&&this._rangeReaders.splice(A,1)}getFullReader(){(0,y.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const T=this._queuedChunks;return this._queuedChunks=null,new U(this,T,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(T,A){if(A<=this._progressiveDataLength)return null;const o=new F(this,T,A);return this._pdfDataRangeTransport.requestDataRange(T,A),this._rangeReaders.push(o),o}cancelAllRequests(T){this._fullRequestReader?.cancel(T);for(const A of this._rangeReaders.slice(0))A.cancel(T);this._pdfDataRangeTransport.abort()}}class U{constructor(T,A,o=!1,d=null){this._stream=T,this._done=o||!1,this._filename=(0,z.isPdfFile)(d)?d:null,this._queuedChunks=A||[],this._loaded=0;for(const u of this._queuedChunks)this._loaded+=u.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 A of this._requests)A.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class F{constructor(T,A,o){this._stream=T,this._begin=A,this._end=o,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 o of this._requests)o.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 A=this._queuedChunk;return this._queuedChunk=null,{value:A,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 A of this._requests)A.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},164:(dt,et,V)=>{V.d(et,{GlobalWorkerOptions:()=>y});class y{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(_){if(!(typeof Worker<"u"&&_ instanceof Worker)&&_!==null)throw new Error("Invalid `workerPort` type.");this.#t=_}static get workerSrc(){return this.#e}static set workerSrc(_){if(typeof _!="string")throw new Error("Invalid `workerSrc` type.");this.#e=_}}},284:(dt,et,V)=>{V.d(et,{XfaLayer:()=>z});var y=V(50);class z{static setupStorage(U,F,C,T,A){const o=T.getValue(F,{value:null});switch(C.name){case"textarea":if(o.value!==null&&(U.textContent=o.value),A==="print")break;U.addEventListener("input",d=>{T.setValue(F,{value:d.target.value})});break;case"input":if(C.attributes.type==="radio"||C.attributes.type==="checkbox"){if(o.value===C.attributes.xfaOn?U.setAttribute("checked",!0):o.value===C.attributes.xfaOff&&U.removeAttribute("checked"),A==="print")break;U.addEventListener("change",d=>{T.setValue(F,{value:d.target.checked?d.target.getAttribute("xfaOn"):d.target.getAttribute("xfaOff")})})}else{if(o.value!==null&&U.setAttribute("value",o.value),A==="print")break;U.addEventListener("input",d=>{T.setValue(F,{value:d.target.value})})}break;case"select":if(o.value!==null){U.setAttribute("value",o.value);for(const d of C.children)d.attributes.value===o.value?d.attributes.selected=!0:d.attributes.hasOwnProperty("selected")&&delete d.attributes.selected}U.addEventListener("input",d=>{const u=d.target.options,b=u.selectedIndex===-1?"":u[u.selectedIndex].value;T.setValue(F,{value:b})});break}}static setAttributes({html:U,element:F,storage:C=null,intent:T,linkService:A}){const{attributes:o}=F,d=U instanceof HTMLAnchorElement;o.type==="radio"&&(o.name=`${o.name}-${T}`);for(const[u,b]of Object.entries(o))if(b!=null)switch(u){case"class":b.length&&U.setAttribute(u,b.join(" "));break;case"dataId":break;case"id":U.setAttribute("data-element-id",b);break;case"style":Object.assign(U.style,b);break;case"textContent":U.textContent=b;break;default:(!d||u!=="href"&&u!=="newWindow")&&U.setAttribute(u,b)}d&&A.addLinkAttributes(U,o.href,o.newWindow),C&&o.dataId&&this.setupStorage(U,o.dataId,F,C)}static render(U){const F=U.annotationStorage,C=U.linkService,T=U.xfaHtml,A=U.intent||"display",o=document.createElement(T.name);T.attributes&&this.setAttributes({html:o,element:T,intent:A,linkService:C});const d=A!=="richText",u=U.div;if(u.append(o),U.viewport){const g=`matrix(${U.viewport.transform.join(",")})`;u.style.transform=g}d&&u.setAttribute("class","xfaLayer xfaFont");const b=[];if(T.children.length===0){if(T.value){const g=document.createTextNode(T.value);o.append(g),d&&y.XfaText.shouldBuildText(T.name)&&b.push(g)}return{textDivs:b}}const s=[[T,-1,o]];for(;s.length>0;){const[g,t,r]=s.at(-1);if(t+1===g.children.length){s.pop();continue}const c=g.children[++s.at(-1)[1]];if(c===null)continue;const{name:f}=c;if(f==="#text"){const S=document.createTextNode(c.value);b.push(S),r.append(S);continue}const v=c?.attributes?.xmlns?document.createElementNS(c.attributes.xmlns,f):document.createElement(f);if(r.append(v),c.attributes&&this.setAttributes({html:v,element:c,storage:F,intent:A,linkService:C}),c.children?.length>0)s.push([c,-1,v]);else if(c.value){const S=document.createTextNode(c.value);d&&y.XfaText.shouldBuildText(f)&&b.push(S),v.append(S)}}for(const g of u.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))g.setAttribute("readOnly",!0);return{textDivs:b}}static update(U){const F=`matrix(${U.viewport.transform.join(",")})`;U.div.style.transform=F,U.div.hidden=!1}}},50:(dt,et,V)=>{V.d(et,{XfaText:()=>y});class y{static textContent(_){const U=[],F={items:U,styles:Object.create(null)};function C(T){if(!T)return;let A=null;const o=T.name;if(o==="#text")A=T.value;else if(y.shouldBuildText(o))T?.attributes?.textContent?A=T.attributes.textContent:T.value&&(A=T.value);else return;if(A!==null&&U.push({str:A}),!!T.children)for(const d of T.children)C(d)}return C(_),F}static shouldBuildText(_){return!(_==="textarea"||_==="input"||_==="option"||_==="select")}}},228:(dt,et,V)=>{V.a(dt,async(y,z)=>{try{V.d(et,{AbortException:()=>_.AbortException,AnnotationEditorLayer:()=>T.AnnotationEditorLayer,AnnotationEditorParamsType:()=>_.AnnotationEditorParamsType,AnnotationEditorType:()=>_.AnnotationEditorType,AnnotationEditorUIManager:()=>A.AnnotationEditorUIManager,AnnotationLayer:()=>o.AnnotationLayer,AnnotationMode:()=>_.AnnotationMode,CMapCompressionType:()=>_.CMapCompressionType,ColorPicker:()=>d.ColorPicker,DOMSVGFactory:()=>F.DOMSVGFactory,DrawLayer:()=>u.DrawLayer,FeatureTest:()=>_.FeatureTest,GlobalWorkerOptions:()=>b.GlobalWorkerOptions,ImageKind:()=>_.ImageKind,InvalidPDFException:()=>_.InvalidPDFException,MissingPDFException:()=>_.MissingPDFException,OPS:()=>_.OPS,Outliner:()=>s.Outliner,PDFDataRangeTransport:()=>U.PDFDataRangeTransport,PDFDateString:()=>F.PDFDateString,PDFWorker:()=>U.PDFWorker,PasswordResponses:()=>_.PasswordResponses,PermissionFlag:()=>_.PermissionFlag,PixelsPerInch:()=>F.PixelsPerInch,RenderingCancelledException:()=>F.RenderingCancelledException,UnexpectedResponseException:()=>_.UnexpectedResponseException,Util:()=>_.Util,VerbosityLevel:()=>_.VerbosityLevel,XfaLayer:()=>g.XfaLayer,build:()=>U.build,createValidAbsoluteUrl:()=>_.createValidAbsoluteUrl,fetchData:()=>F.fetchData,getDocument:()=>U.getDocument,getFilenameFromUrl:()=>F.getFilenameFromUrl,getPdfFilenameFromUrl:()=>F.getPdfFilenameFromUrl,getXfaPageViewport:()=>F.getXfaPageViewport,isDataScheme:()=>F.isDataScheme,isPdfFile:()=>F.isPdfFile,noContextMenu:()=>F.noContextMenu,normalizeUnicode:()=>_.normalizeUnicode,renderTextLayer:()=>C.renderTextLayer,setLayerDimensions:()=>F.setLayerDimensions,shadow:()=>_.shadow,updateTextLayer:()=>C.updateTextLayer,version:()=>U.version});var _=V(292),U=V(831),F=V(419),C=V(814),T=V(731),A=V(830),o=V(976),d=V(259),u=V(47),b=V(164),s=V(61),g=V(284),t=y([U]);U=(t.then?(await t)():t)[0];const r="4.1.392",c="fcb76a78d";z()}catch(r){z(r)}})},178:(dt,et,V)=>{V.d(et,{MessageHandler:()=>F});var y=V(292);const z={UNKNOWN:0,DATA:1,ERROR:2},_={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function U(C){switch(C instanceof Error||typeof C=="object"&&C!==null||(0,y.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),C.name){case"AbortException":return new y.AbortException(C.message);case"MissingPDFException":return new y.MissingPDFException(C.message);case"PasswordException":return new y.PasswordException(C.message,C.code);case"UnexpectedResponseException":return new y.UnexpectedResponseException(C.message,C.status);case"UnknownErrorException":return new y.UnknownErrorException(C.message,C.details);default:return new y.UnknownErrorException(C.message,C.toString())}}class F{constructor(T,A,o){this.sourceName=T,this.targetName=A,this.comObj=o,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),this._onComObjOnMessage=d=>{const u=d.data;if(u.targetName!==this.sourceName)return;if(u.stream){this.#e(u);return}if(u.callback){const s=u.callbackId,g=this.callbackCapabilities[s];if(!g)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],u.callback===z.DATA)g.resolve(u.data);else if(u.callback===z.ERROR)g.reject(U(u.reason));else throw new Error("Unexpected callback case");return}const b=this.actionHandler[u.action];if(!b)throw new Error(`Unknown action from worker: ${u.action}`);if(u.callbackId){const s=this.sourceName,g=u.sourceName;new Promise(function(t){t(b(u.data))}).then(function(t){o.postMessage({sourceName:s,targetName:g,callback:z.DATA,callbackId:u.callbackId,data:t})},function(t){o.postMessage({sourceName:s,targetName:g,callback:z.ERROR,callbackId:u.callbackId,reason:U(t)})});return}if(u.streamId){this.#t(u);return}b(u.data)},o.addEventListener("message",this._onComObjOnMessage)}on(T,A){const o=this.actionHandler;if(o[T])throw new Error(`There is already an actionName called "${T}"`);o[T]=A}send(T,A,o){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:T,data:A},o)}sendWithPromise(T,A,o){const d=this.callbackId++,u=Promise.withResolvers();this.callbackCapabilities[d]=u;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:T,callbackId:d,data:A},o)}catch(b){u.reject(b)}return u.promise}sendWithStream(T,A,o,d){const u=this.streamId++,b=this.sourceName,s=this.targetName,g=this.comObj;return new ReadableStream({start:t=>{const r=Promise.withResolvers();return this.streamControllers[u]={controller:t,startCall:r,pullCall:null,cancelCall:null,isClosed:!1},g.postMessage({sourceName:b,targetName:s,action:T,streamId:u,data:A,desiredSize:t.desiredSize},d),r.promise},pull:t=>{const r=Promise.withResolvers();return this.streamControllers[u].pullCall=r,g.postMessage({sourceName:b,targetName:s,stream:_.PULL,streamId:u,desiredSize:t.desiredSize}),r.promise},cancel:t=>{(0,y.assert)(t instanceof Error,"cancel must have a valid reason");const r=Promise.withResolvers();return this.streamControllers[u].cancelCall=r,this.streamControllers[u].isClosed=!0,g.postMessage({sourceName:b,targetName:s,stream:_.CANCEL,streamId:u,reason:U(t)}),r.promise}},o)}#t(T){const A=T.streamId,o=this.sourceName,d=T.sourceName,u=this.comObj,b=this,s=this.actionHandler[T.action],g={enqueue(t,r=1,c){if(this.isCancelled)return;const f=this.desiredSize;this.desiredSize-=r,f>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),u.postMessage({sourceName:o,targetName:d,stream:_.ENQUEUE,streamId:A,chunk:t},c)},close(){this.isCancelled||(this.isCancelled=!0,u.postMessage({sourceName:o,targetName:d,stream:_.CLOSE,streamId:A}),delete b.streamSinks[A])},error(t){(0,y.assert)(t instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,u.postMessage({sourceName:o,targetName:d,stream:_.ERROR,streamId:A,reason:U(t)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:T.desiredSize,ready:null};g.sinkCapability.resolve(),g.ready=g.sinkCapability.promise,this.streamSinks[A]=g,new Promise(function(t){t(s(T.data,g))}).then(function(){u.postMessage({sourceName:o,targetName:d,stream:_.START_COMPLETE,streamId:A,success:!0})},function(t){u.postMessage({sourceName:o,targetName:d,stream:_.START_COMPLETE,streamId:A,reason:U(t)})})}#e(T){const A=T.streamId,o=this.sourceName,d=T.sourceName,u=this.comObj,b=this.streamControllers[A],s=this.streamSinks[A];switch(T.stream){case _.START_COMPLETE:T.success?b.startCall.resolve():b.startCall.reject(U(T.reason));break;case _.PULL_COMPLETE:T.success?b.pullCall.resolve():b.pullCall.reject(U(T.reason));break;case _.PULL:if(!s){u.postMessage({sourceName:o,targetName:d,stream:_.PULL_COMPLETE,streamId:A,success:!0});break}s.desiredSize<=0&&T.desiredSize>0&&s.sinkCapability.resolve(),s.desiredSize=T.desiredSize,new Promise(function(g){g(s.onPull?.())}).then(function(){u.postMessage({sourceName:o,targetName:d,stream:_.PULL_COMPLETE,streamId:A,success:!0})},function(g){u.postMessage({sourceName:o,targetName:d,stream:_.PULL_COMPLETE,streamId:A,reason:U(g)})});break;case _.ENQUEUE:if((0,y.assert)(b,"enqueue should have stream controller"),b.isClosed)break;b.controller.enqueue(T.chunk);break;case _.CLOSE:if((0,y.assert)(b,"close should have stream controller"),b.isClosed)break;b.isClosed=!0,b.controller.close(),this.#s(b,A);break;case _.ERROR:(0,y.assert)(b,"error should have stream controller"),b.controller.error(U(T.reason)),this.#s(b,A);break;case _.CANCEL_COMPLETE:T.success?b.cancelCall.resolve():b.cancelCall.reject(U(T.reason)),this.#s(b,A);break;case _.CANCEL:if(!s)break;new Promise(function(g){g(s.onCancel?.(U(T.reason)))}).then(function(){u.postMessage({sourceName:o,targetName:d,stream:_.CANCEL_COMPLETE,streamId:A,success:!0})},function(g){u.postMessage({sourceName:o,targetName:d,stream:_.CANCEL_COMPLETE,streamId:A,reason:U(g)})}),s.sinkCapability.reject(U(T.reason)),s.isCancelled=!0,delete this.streamSinks[A];break;default:throw new Error("Unexpected stream case")}}async#s(T,A){await Promise.allSettled([T.startCall?.promise,T.pullCall?.promise,T.cancelCall?.promise]),delete this.streamControllers[A]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(dt,et,V)=>{V.d(et,{MurmurHash3_64:()=>U});const y=3285377520,z=4294901760,_=65535;class U{constructor(C){this.h1=C?C&4294967295:y,this.h2=C?C&4294967295:y}update(C){let T,A;if(typeof C=="string"){T=new Uint8Array(C.length*2),A=0;for(let S=0,M=C.length;S>>8,T[A++]=I&255)}}else if(ArrayBuffer.isView(C))T=C.slice(),A=T.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const o=A>>2,d=A-o*4,u=new Uint32Array(T.buffer,0,o);let b=0,s=0,g=this.h1,t=this.h2;const r=3432918353,c=461845907,f=r&_,v=c&_;for(let S=0;S>>17,b=b*c&z|b*v&_,g^=b,g=g<<13|g>>>19,g=g*5+3864292196):(s=u[S],s=s*r&z|s*f&_,s=s<<15|s>>>17,s=s*c&z|s*v&_,t^=s,t=t<<13|t>>>19,t=t*5+3864292196);switch(b=0,d){case 3:b^=T[o*4+2]<<16;case 2:b^=T[o*4+1]<<8;case 1:b^=T[o*4],b=b*r&z|b*f&_,b=b<<15|b>>>17,b=b*c&z|b*v&_,o&1?g^=b:t^=b}this.h1=g,this.h2=t}hexdigest(){let C=this.h1,T=this.h2;return C^=T>>>1,C=C*3981806797&z|C*36045&_,T=T*4283543511&z|((T<<16|C>>>16)*2950163797&z)>>>16,C^=T>>>1,C=C*444984403&z|C*60499&_,T=T*3301882366&z|((T<<16|C>>>16)*3120437893&z)>>>16,C^=T>>>1,(C>>>0).toString(16).padStart(8,"0")+(T>>>0).toString(16).padStart(8,"0")}}},292:(dt,et,V)=>{V.d(et,{AbortException:()=>ht,AnnotationBorderStyleType:()=>t,AnnotationEditorParamsType:()=>d,AnnotationEditorPrefix:()=>A,AnnotationEditorType:()=>o,AnnotationMode:()=>T,AnnotationPrefix:()=>P,AnnotationType:()=>g,BaseException:()=>G,CMapCompressionType:()=>c,FONT_IDENTITY_MATRIX:()=>_,FeatureTest:()=>n,FormatError:()=>lt,IDENTITY_MATRIX:()=>z,ImageKind:()=>s,InvalidPDFException:()=>K,LINE_FACTOR:()=>F,MAX_IMAGE_SIZE_TO_CACHE:()=>U,MissingPDFException:()=>at,OPS:()=>f,PasswordException:()=>Y,PasswordResponses:()=>v,PermissionFlag:()=>u,RenderingIntentFlag:()=>C,TextRenderingMode:()=>b,UnexpectedResponseException:()=>ot,UnknownErrorException:()=>Q,Util:()=>i,VerbosityLevel:()=>r,assert:()=>q,bytesToString:()=>ft,createValidAbsoluteUrl:()=>X,getUuid:()=>R,getVerbosityLevel:()=>I,info:()=>O,isNodeJS:()=>y,normalizeUnicode:()=>E,objectFromMap:()=>m,setVerbosityLevel:()=>M,shadow:()=>H,string32:()=>Z,stringToBytes:()=>ct,unreachable:()=>B,warn:()=>N});const y=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),z=[1,0,0,1,0,0],_=[.001,0,0,.001,0,0],U=1e7,F=1.35,C={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},T={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},A="pdfjs_internal_editor_",o={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},d={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},u={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},s={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},g={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},t={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},r={ERRORS:0,WARNINGS:1,INFOS:5},c={NONE:0,BINARY:1},f={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},v={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let S=r.WARNINGS;function M(L){Number.isInteger(L)&&(S=L)}function I(){return S}function O(L){S>=r.INFOS&&console.log(`Info: ${L}`)}function N(L){S>=r.WARNINGS&&console.log(`Warning: ${L}`)}function B(L){throw new Error(L)}function q(L,x){L||B(x)}function st(L){switch(L?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function X(L,x=null,k=null){if(!L)return null;try{if(k&&typeof L=="string"&&(k.addDefaultProtocol&&L.startsWith("www.")&&L.match(/\./g)?.length>=2&&(L=`http://${L}`),k.tryConvertEncoding))try{L=h(L)}catch{}const D=x?new URL(L,x):new URL(L);if(st(D))return D}catch{}return null}function H(L,x,k,D=!1){return Object.defineProperty(L,x,{value:k,enumerable:!D,configurable:!0,writable:!1}),k}const G=function(){function x(k,D){this.constructor===x&&B("Cannot initialize BaseException."),this.message=k,this.name=D}return x.prototype=new Error,x.constructor=x,x}();class Y extends G{constructor(x,k){super(x,"PasswordException"),this.code=k}}class Q extends G{constructor(x,k){super(x,"UnknownErrorException"),this.details=k}}class K extends G{constructor(x){super(x,"InvalidPDFException")}}class at extends G{constructor(x){super(x,"MissingPDFException")}}class ot extends G{constructor(x,k){super(x,"UnexpectedResponseException"),this.status=k}}class lt extends G{constructor(x){super(x,"FormatError")}}class ht extends G{constructor(x){super(x,"AbortException")}}function ft(L){(typeof L!="object"||L?.length===void 0)&&B("Invalid argument for bytesToString");const x=L.length,k=8192;if(x>24&255,L>>16&255,L>>8&255,L&255)}function m(L){const x=Object.create(null);for(const[k,D]of L)x[k]=D;return x}function l(){const L=new Uint8Array(4);return L[0]=1,new Uint32Array(L.buffer,0,1)[0]===1}function e(){try{return new Function(""),!0}catch{return!1}}class n{static get isLittleEndian(){return H(this,"isLittleEndian",l())}static get isEvalSupported(){return H(this,"isEvalSupported",e())}static get isOffscreenCanvasSupported(){return H(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?H(this,"platform",{isMac:navigator.platform.includes("Mac")}):H(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return H(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const a=Array.from(Array(256).keys(),L=>L.toString(16).padStart(2,"0"));class i{static makeHexColor(x,k,D){return`#${a[x]}${a[k]}${a[D]}`}static scaleMinMax(x,k){let D;x[0]?(x[0]<0&&(D=k[0],k[0]=k[2],k[2]=D),k[0]*=x[0],k[2]*=x[0],x[3]<0&&(D=k[1],k[1]=k[3],k[3]=D),k[1]*=x[3],k[3]*=x[3]):(D=k[0],k[0]=k[1],k[1]=D,D=k[2],k[2]=k[3],k[3]=D,x[1]<0&&(D=k[1],k[1]=k[3],k[3]=D),k[1]*=x[1],k[3]*=x[1],x[2]<0&&(D=k[0],k[0]=k[2],k[2]=D),k[0]*=x[2],k[2]*=x[2]),k[0]+=x[4],k[1]+=x[5],k[2]+=x[4],k[3]+=x[5]}static transform(x,k){return[x[0]*k[0]+x[2]*k[1],x[1]*k[0]+x[3]*k[1],x[0]*k[2]+x[2]*k[3],x[1]*k[2]+x[3]*k[3],x[0]*k[4]+x[2]*k[5]+x[4],x[1]*k[4]+x[3]*k[5]+x[5]]}static applyTransform(x,k){const D=x[0]*k[0]+x[1]*k[2]+k[4],j=x[0]*k[1]+x[1]*k[3]+k[5];return[D,j]}static applyInverseTransform(x,k){const D=k[0]*k[3]-k[1]*k[2],j=(x[0]*k[3]-x[1]*k[2]+k[2]*k[5]-k[4]*k[3])/D,J=(-x[0]*k[1]+x[1]*k[0]+k[4]*k[1]-k[5]*k[0])/D;return[j,J]}static getAxialAlignedBoundingBox(x,k){const D=this.applyTransform(x,k),j=this.applyTransform(x.slice(2,4),k),J=this.applyTransform([x[0],x[3]],k),$=this.applyTransform([x[2],x[1]],k);return[Math.min(D[0],j[0],J[0],$[0]),Math.min(D[1],j[1],J[1],$[1]),Math.max(D[0],j[0],J[0],$[0]),Math.max(D[1],j[1],J[1],$[1])]}static inverseTransform(x){const k=x[0]*x[3]-x[1]*x[2];return[x[3]/k,-x[1]/k,-x[2]/k,x[0]/k,(x[2]*x[5]-x[4]*x[3])/k,(x[4]*x[1]-x[5]*x[0])/k]}static singularValueDecompose2dScale(x){const k=[x[0],x[2],x[1],x[3]],D=x[0]*k[0]+x[1]*k[2],j=x[0]*k[1]+x[1]*k[3],J=x[2]*k[0]+x[3]*k[2],$=x[2]*k[1]+x[3]*k[3],tt=(D+$)/2,it=Math.sqrt((D+$)**2-4*(D*$-J*j))/2,W=tt+it||1,rt=tt-it||1;return[Math.sqrt(W),Math.sqrt(rt)]}static normalizeRect(x){const k=x.slice(0);return x[0]>x[2]&&(k[0]=x[2],k[2]=x[0]),x[1]>x[3]&&(k[1]=x[3],k[3]=x[1]),k}static intersect(x,k){const D=Math.max(Math.min(x[0],x[2]),Math.min(k[0],k[2])),j=Math.min(Math.max(x[0],x[2]),Math.max(k[0],k[2]));if(D>j)return null;const J=Math.max(Math.min(x[1],x[3]),Math.min(k[1],k[3])),$=Math.min(Math.max(x[1],x[3]),Math.max(k[1],k[3]));return J>$?null:[D,J,j,$]}static#t(x,k,D,j,J,$,tt,it,W,rt){if(W<=0||W>=1)return;const nt=1-W,ut=W*W,gt=ut*W,mt=nt*(nt*(nt*x+3*W*k)+3*ut*D)+gt*j,At=nt*(nt*(nt*J+3*W*$)+3*ut*tt)+gt*it;rt[0]=Math.min(rt[0],mt),rt[1]=Math.min(rt[1],At),rt[2]=Math.max(rt[2],mt),rt[3]=Math.max(rt[3],At)}static#e(x,k,D,j,J,$,tt,it,W,rt,nt,ut){if(Math.abs(W)<1e-12){Math.abs(rt)>=1e-12&&this.#t(x,k,D,j,J,$,tt,it,-nt/rt,ut);return}const gt=rt**2-4*nt*W;if(gt<0)return;const mt=Math.sqrt(gt),At=2*W;this.#t(x,k,D,j,J,$,tt,it,(-rt+mt)/At,ut),this.#t(x,k,D,j,J,$,tt,it,(-rt-mt)/At,ut)}static bezierBoundingBox(x,k,D,j,J,$,tt,it,W){return W?(W[0]=Math.min(W[0],x,tt),W[1]=Math.min(W[1],k,it),W[2]=Math.max(W[2],x,tt),W[3]=Math.max(W[3],k,it)):W=[Math.min(x,tt),Math.min(k,it),Math.max(x,tt),Math.max(k,it)],this.#e(x,D,J,tt,k,j,$,it,3*(-x+3*(D-J)+tt),6*(x-2*D+J),3*(D-x),W),this.#e(x,D,J,tt,k,j,$,it,3*(-k+3*(j-$)+it),6*(k-2*j+$),3*(j-k),W),W}}function h(L){return decodeURIComponent(escape(L))}let p=null,w=null;function E(L){return p||(p=/([\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,w=new Map([["ſt","ſt"]])),L.replaceAll(p,(x,k,D)=>k?k.normalize("NFKC"):w.get(D))}function R(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();const L=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(L);else for(let x=0;x<32;x++)L[x]=Math.floor(Math.random()*255);return ft(L)}const P="pdfjs_internal_id_"}},Gt={};function Lt(dt){var et=Gt[dt];if(et!==void 0)return et.exports;var V=Gt[dt]={exports:{}};return Vt[dt](V,V.exports,Lt),V.exports}(()=>{var dt=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",et=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",V=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",y=_=>{_&&_.d<1&&(_.d=1,_.forEach(U=>U.r--),_.forEach(U=>U.r--?U.r++:U()))},z=_=>_.map(U=>{if(U!==null&&typeof U=="object"){if(U[dt])return U;if(U.then){var F=[];F.d=0,U.then(A=>{C[et]=A,y(F)},A=>{C[V]=A,y(F)});var C={};return C[dt]=A=>A(F),C}}var T={};return T[dt]=A=>{},T[et]=U,T});Lt.a=(_,U,F)=>{var C;F&&((C=[]).d=-1);var T=new Set,A=_.exports,o,d,u,b=new Promise((s,g)=>{u=g,d=s});b[et]=A,b[dt]=s=>(C&&s(C),T.forEach(s),b.catch(g=>{})),_.exports=b,U(s=>{o=z(s);var g,t=()=>o.map(c=>{if(c[V])throw c[V];return c[et]}),r=new Promise(c=>{g=()=>c(t),g.r=0;var f=v=>v!==C&&!T.has(v)&&(T.add(v),v&&!v.d&&(g.r++,v.push(g)));o.map(v=>v[dt](f))});return g.r?r:t()},s=>(s?u(b[V]=s):d(A),y(C))),C&&C.d<0&&(C.d=0)}})();Lt.d=(dt,et)=>{for(var V in et)Lt.o(et,V)&&!Lt.o(dt,V)&&Object.defineProperty(dt,V,{enumerable:!0,get:et[V]})};Lt.o=(dt,et)=>Object.prototype.hasOwnProperty.call(dt,et);var pt=Lt(228);pt=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=pt);var jt=pt.AbortException,Yt=pt.AnnotationEditorLayer,Wt=pt.AnnotationEditorParamsType,qt=pt.AnnotationEditorType,Kt=pt.AnnotationEditorUIManager,Jt=pt.AnnotationLayer,Qt=pt.AnnotationMode,Zt=pt.CMapCompressionType,te=pt.ColorPicker,ee=pt.DOMSVGFactory,se=pt.DrawLayer,ie=pt.FeatureTest,ne=pt.GlobalWorkerOptions,re=pt.ImageKind,ae=pt.InvalidPDFException,oe=pt.MissingPDFException,he=pt.OPS,le=pt.Outliner,ce=pt.PDFDataRangeTransport,de=pt.PDFDateString,ue=pt.PDFWorker,fe=pt.PasswordResponses,pe=pt.PermissionFlag,ge=pt.PixelsPerInch,me=pt.RenderingCancelledException,be=pt.UnexpectedResponseException,Ae=pt.Util,ve=pt.VerbosityLevel,ye=pt.XfaLayer,we=pt.build,Se=pt.createValidAbsoluteUrl,xe=pt.fetchData,Ee=pt.getDocument,Te=pt.getFilenameFromUrl,Ce=pt.getPdfFilenameFromUrl,ke=pt.getXfaPageViewport,Fe=pt.isDataScheme,Re=pt.isPdfFile,Pe=pt.noContextMenu,Le=pt.normalizeUnicode,Me=pt.renderTextLayer,Ie=pt.setLayerDimensions,_e=pt.shadow,De=pt.updateTextLayer,Ne=pt.version;export{jt as AbortException,Yt as AnnotationEditorLayer,Wt as AnnotationEditorParamsType,qt as AnnotationEditorType,Kt as AnnotationEditorUIManager,Jt as AnnotationLayer,Qt as AnnotationMode,Zt as CMapCompressionType,te as ColorPicker,ee as DOMSVGFactory,se as DrawLayer,ie as FeatureTest,ne as GlobalWorkerOptions,re as ImageKind,ae as InvalidPDFException,oe as MissingPDFException,he as OPS,le as Outliner,ce as PDFDataRangeTransport,de as PDFDateString,ue as PDFWorker,fe as PasswordResponses,pe as PermissionFlag,ge as PixelsPerInch,me as RenderingCancelledException,be as UnexpectedResponseException,Ae as Util,ve as VerbosityLevel,ye as XfaLayer,we as build,Se as createValidAbsoluteUrl,xe as fetchData,Ee as getDocument,Te as getFilenameFromUrl,Ce as getPdfFilenameFromUrl,ke as getXfaPageViewport,Fe as isDataScheme,Re as isPdfFile,Pe as noContextMenu,Le as normalizeUnicode,Me as renderTextLayer,Ie as setLayerDimensions,_e as shadow,De as updateTextLayer,Ne as version}; diff --git a/dist/assets/pdf-icon-d4c18e5d.svg b/dist/assets/pdf-icon-d4c18e5d.svg new file mode 100644 index 0000000..d64a80f --- /dev/null +++ b/dist/assets/pdf-icon-d4c18e5d.svg @@ -0,0 +1 @@ + pdf-document \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index 84a6795..3bfa50b 100644 --- a/dist/index.html +++ b/dist/index.html @@ -4,8 +4,8 @@ - - + +
    diff --git a/dist/smoothgpt-0.2.zip b/dist/smoothgpt-0.2.zip deleted file mode 100644 index 1828d6d..0000000 Binary files a/dist/smoothgpt-0.2.zip and /dev/null differ diff --git a/dist/workers/pdf.worker.min.mjs b/dist/workers/pdf.worker.min.mjs new file mode 100644 index 0000000..a8b24a3 --- /dev/null +++ b/dist/workers/pdf.worker.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2023 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var e={d:(t,a)=>{for(var r in a)e.o(a,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:a[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__=globalThis.pdfjsWorker={};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],i=1.35,n=.35,s=.25925925925925924,o=1,c=2,l=4,h=8,u=16,d=64,f=256,g="pdfjs_internal_editor_",p=3,m=9,b=13,y=15,w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},x=0,S=4,k=1,C=2,v=3,F=1,O=2,T=3,M=4,D=5,R=6,N=7,E=8,L=9,j=10,_=11,U=12,X=13,q=14,H=15,z=16,W=17,$=20,G="Group",V="R",K=1,J=2,Y=4,Z=16,Q=32,ee=128,te=512,ae=1,re=2,ie=4096,ne=8192,se=32768,oe=65536,ce=131072,le=1048576,he=2097152,ue=8388608,de=16777216,fe=1,ge=2,pe=3,me=4,be=5,ye={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},we={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},xe={O:"PageOpen",C:"PageClose"},Se={ERRORS:0,WARNINGS:1,INFOS:5},ke={NONE:0,BINARY:1},Ae=1,Ce=2,ve=3,Fe=4,Ie=5,Oe=6,Te=7,Me=8,De=9,Be=10,Re=11,Ne=12,Ee=13,Pe=14,Le=15,je=16,_e=17,Ue=18,Xe=19,qe=20,He=21,ze=22,We=23,$e=24,Ge=25,Ve=26,Ke=27,Je=28,Ye=29,Ze=30,Qe=31,et=32,tt=33,at=34,rt=35,it=36,nt=37,st=38,ot=39,ct=40,lt=41,ht=42,ut=43,dt=44,ft=45,gt=46,pt=47,mt=48,bt=49,yt=50,wt=51,xt=52,St=53,kt=54,At=55,Ct=56,vt=57,Ft=58,It=59,Ot=60,Tt=61,Mt=62,Dt=63,Bt=64,Rt=65,Nt=66,Et=67,Pt=68,Lt=69,jt=70,_t=71,Ut=72,Xt=73,qt=74,Ht=75,zt=76,Wt=77,$t=80,Gt=81,Vt=83,Kt=84,Jt=85,Yt=86,Zt=87,Qt=88,ea=89,ta=90,aa=91,ra=1,ia=2;let na=Se.WARNINGS;function getVerbosityLevel(){return na}function info(e){na>=Se.INFOS&&console.log(`Info: ${e}`)}function warn(e){na>=Se.WARNINGS&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,a=null){if(!e)return null;try{if(a&&"string"==typeof e){if(a.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(a.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const r=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(r))return r}catch{}return null}function shadow(e,t,a,r=!1){Object.defineProperty(e,t,{value:a,enumerable:!r,configurable:!0,writable:!1});return a}const sa=function BaseExceptionClosure(){function BaseException(e,t){this.constructor===BaseException&&unreachable("Cannot initialize BaseException.");this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends sa{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends sa{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends sa{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends sa{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends sa{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends sa{constructor(e){super(e,"FormatError")}}class AbortException extends sa{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,a=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac")}):shadow(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const oa=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,a){return`#${oa[e]}${oa[t]}${oa[a]}`}static scaleMinMax(e,t){let a;if(e[0]){if(e[0]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[3];t[3]*=e[3]}else{a=t[0];t[0]=t[1];t[1]=a;a=t[2];t[2]=t[3];t[3]=a;if(e[1]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const a=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/a,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/a]}static getAxialAlignedBoundingBox(e,t){const a=this.applyTransform(e,t),r=this.applyTransform(e.slice(2,4),t),i=this.applyTransform([e[0],e[3]],t),n=this.applyTransform([e[2],e[1]],t);return[Math.min(a[0],r[0],i[0],n[0]),Math.min(a[1],r[1],i[1],n[1]),Math.max(a[0],r[0],i[0],n[0]),Math.max(a[1],r[1],i[1],n[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],a=e[0]*t[0]+e[1]*t[2],r=e[0]*t[1]+e[1]*t[3],i=e[2]*t[0]+e[3]*t[2],n=e[2]*t[1]+e[3]*t[3],s=(a+n)/2,o=Math.sqrt((a+n)**2-4*(a*n-i*r))/2,c=s+o||1,l=s-o||1;return[Math.sqrt(c),Math.sqrt(l)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const a=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(a>r)return null;const i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),n=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>n?null:[a,i,r,n]}static#e(e,t,a,r,i,n,s,o,c,l){if(c<=0||c>=1)return;const h=1-c,u=c*c,d=u*c,f=h*(h*(h*e+3*c*t)+3*u*a)+d*r,g=h*(h*(h*i+3*c*n)+3*u*s)+d*o;l[0]=Math.min(l[0],f);l[1]=Math.min(l[1],g);l[2]=Math.max(l[2],f);l[3]=Math.max(l[3],g)}static#t(e,t,a,r,i,n,s,o,c,l,h,u){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,a,r,i,n,s,o,-h/l,u);return}const d=l**2-4*h*c;if(d<0)return;const f=Math.sqrt(d),g=2*c;this.#e(e,t,a,r,i,n,s,o,(-l+f)/g,u);this.#e(e,t,a,r,i,n,s,o,(-l-f)/g,u)}static bezierBoundingBox(e,t,a,r,i,n,s,o,c){if(c){c[0]=Math.min(c[0],e,s);c[1]=Math.min(c[1],t,o);c[2]=Math.max(c[2],e,s);c[3]=Math.max(c[3],t,o)}else c=[Math.min(e,s),Math.min(t,o),Math.max(e,s),Math.max(t,o)];this.#t(e,a,i,s,t,r,n,o,3*(3*(a-i)-e+s),6*(e-2*a+i),3*(a-e),c);this.#t(e,a,i,s,t,r,n,o,3*(3*(r-n)-t+o),6*(t-2*r+n),3*(r-t),c);return c}}const ca=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const a=new TextDecoder(t,{fatal:!0}),r=stringToBytes(e),i=a.decode(r);return i.includes("")?i.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):i}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let a=0,r=e.length;a{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:a=!1}){const r=new Dict(e),i=new Map;for(const e of t)if(e instanceof Dict)for(const[t,r]of Object.entries(e._map)){let e=i.get(t);if(void 0===e){e=[];i.set(t,e)}else if(!(a&&r instanceof Dict))continue;e.push(r)}for(const[t,a]of i){if(1===a.length||!(a[0]instanceof Dict)){r._map[t]=a[0];continue}const i=new Dict(e);for(const e of a)for(const[t,a]of Object.entries(e._map))void 0===i._map[t]&&(i._map[t]=a);i.size>0&&(r._map[t]=i)}i.clear();return r.size>0?r:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=pa[e];if(t)return t;const a=/^(\d+)R(\d*)$/.exec(e);return a&&"0"!==a[1]?pa[e]=new Ref(parseInt(a[1]),a[2]?parseInt(a[2]):0):null}static get(e,t){const a=0===t?`${e}R`:`${e}R${t}`;return pa[a]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{constructor(){this.constructor===BaseStream&&unreachable("Cannot initialize BaseStream.")}get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,a=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ba=/^[1-9]\.\d$/;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends sa{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends sa{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends sa{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends sa{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let a=0;for(let r=0;r0,"The number should be a positive integer.");const a=[];let r;for(;e>=1e3;){e-=1e3;a.push("M")}r=e/100|0;e%=100;a.push(ya[r]);r=e/10|0;e%=10;a.push(ya[10+r]);a.push(ya[20+e]);const i=a.join("");return t?i.toLowerCase():i}function log2(e){return e<=0?0:Math.ceil(Math.log2(e))}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const a=e.match(t);return a?{name:a[1],pos:parseInt(a[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let a=0;for(let r=0,i=e.length;r126||35===i||40===i||41===i||60===i||62===i||91===i||93===i||123===i||125===i||47===i||37===i){a"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,a,r){if(!e)return;let i=null;if(e instanceof Ref){if(r.has(e))return;i=e;r.put(i);e=t.fetch(e)}if(Array.isArray(e))for(const i of e)_collectJS(i,t,a,r);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let r;t instanceof BaseStream?r=t.getString():"string"==typeof t&&(r=t);r&&=stringToPDFString(r).replaceAll("\0","");r&&a.push(r)}_collectJS(e.getRaw("Next"),t,a,r)}i&&r.remove(i)}function collectActions(e,t,a){const r=Object.create(null),i=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(i)for(let t=i.length-1;t>=0;t--){const n=i[t];if(n instanceof Dict)for(const t of n.getKeys()){const i=a[t];if(!i)continue;const s=[];_collectJS(n.getRaw(t),e,s,new RefSet);s.length>0&&(r[i]=s)}}if(t.has("A")){const a=[];_collectJS(t.get("A"),e,a,new RefSet);a.length>0&&(r.Action=a)}return objectSize(r)>0?r:null}const wa={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,a=e.length;t55295&&(a<57344||a>65533)&&t++;yield a}}function encodeToXmlString(e){const t=[];let a=0;for(let r=0,i=e.length;r55295&&(i<57344||i>65533)&&r++;a=r+1}}if(0===t.length)return e;a: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:a,fontWeight:r,italicAngle:i}=e;if(!validateFontName(a,!0))return!1;const n=r?r.toString():"";e.fontWeight=t.has(n)?n:"400";const s=parseFloat(i);e.italicAngle=isNaN(s)||s<-90||s>90?"14":i.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);if(t?.[2]){const e=t[2];let a=!1;"true"===t[3]&&"app.launchURL"===t[1]&&(a=!0);return{url:e,newWindow:a}}return null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[a,r]of e){if(!a.startsWith(g))continue;let e=t.get(r.pageIndex);if(!e){e=[];t.set(r.pageIndex,e)}e.push(r)}return t.size>0?t:null}function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}function stringToUTF16HexString(e){const t=[];for(let a=0,r=e.length;a>8&255).toString(16).padStart(2,"0"),(255&r).toString(16).padStart(2,"0"))}return t.join("")}function stringToUTF16String(e,t=!1){const a=[];t&&a.push("þÿ");for(let t=0,r=e.length;t>8&255),String.fromCharCode(255&r))}return a.join("")}function getRotationMatrix(e,t,a){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,a];case 270:return[0,-1,1,0,0,a];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,a,r){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+a||this.bytes.length;this.dict=r}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e)return t.subarray(a,r);let i=a+e;i>r&&(i=r);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,a=null){return new Stream(this.bytes.buffer,e,t,a)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,a){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=a;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,a=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=a;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const a=Math.floor(e/this.chunkSize);if(a>this.numChunks)return;const r=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let i=a;i=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e){r>this.progressiveDataLength&&this.ensureRange(a,r);return t.subarray(a,r)}let i=a+e;i>r&&(i=r);i>this.progressiveDataLength&&this.ensureRange(a,i);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,a=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),a=Math.floor((this.end-1)/e)+1,r=[];for(let e=t;e{const readChunk=({value:n,done:s})=>{try{if(s){const t=arrayBuffersToBytes(r);r=null;e(t);return}i+=n.byteLength;a.isStreamingSupported&&this.onProgress({loaded:i});r.push(n);a.read().then(readChunk,t)}catch(e){t(e)}};a.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,a=new Set;this._chunksNeededByRequest.set(t,a);for(const t of e)this.stream.hasChunk(t)||a.add(t);if(0===a.size)return Promise.resolve();const r=Promise.withResolvers();this._promisesByRequest.set(t,r);const i=[];for(const e of a){let a=this._requestsByChunk.get(e);if(!a){a=[];this._requestsByChunk.set(e,a);i.push(e)}a.push(t)}if(i.length>0){const e=this.groupChunks(i);for(const t of e){const e=t.beginChunk*this.chunkSize,a=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,a).catch(r.reject)}}return r.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const a=this.getBeginChunk(e),r=this.getEndChunk(t),i=[];for(let e=a;e=0&&r+1!==n){t.push({beginChunk:a,endChunk:r+1});a=n}i+1===e.length&&t.push({beginChunk:a,endChunk:n+1});r=n}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,a=void 0===e.begin,r=a?this.progressiveDataLength:e.begin,i=r+t.byteLength,n=Math.floor(r/this.chunkSize),s=i0||o.push(a)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(s);Number.isInteger(e)&&this._requestChunks([e])}for(const e of o){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.constructor===ColorSpace&&unreachable("Cannot initialize ColorSpace.");this.name=e;this.numComps=t}getRgb(e,t){const a=new Uint8ClampedArray(3);this.getRgbItem(e,t,a,0);return a}getRgbItem(e,t,a,r){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,a,r,i,n,s){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,a,r,i,n,s,o,c){const l=t*a;let h=null;const u=1<u&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=s<=8?new Uint8Array(u):new Uint16Array(u);for(let e=0;e=.99554525?1:this.#p(0,1,1.055*e**(1/2.4)-.055)}#p(e,t,a){return Math.max(e,Math.min(t,a))}#m(e){return e<0?-this.#m(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#h}#b(e,t,a){if(0===e[0]&&0===e[1]&&0===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=this.#m(0),i=(1-r)/(1-this.#m(e[0])),n=1-i,s=(1-r)/(1-this.#m(e[1])),o=1-s,c=(1-r)/(1-this.#m(e[2])),l=1-c;a[0]=t[0]*i+n;a[1]=t[1]*s+o;a[2]=t[2]*c+l}#y(e,t,a){if(1===e[0]&&1===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=a;this.#u(CalRGBCS.#r,t,r);const i=CalRGBCS.#o;this.#d(e,r,i);this.#u(CalRGBCS.#i,i,a)}#w(e,t,a){const r=a;this.#u(CalRGBCS.#r,t,r);const i=CalRGBCS.#o;this.#f(e,r,i);this.#u(CalRGBCS.#i,i,a)}#a(e,t,a,r,i){const n=this.#p(0,1,e[t]*i),s=this.#p(0,1,e[t+1]*i),o=this.#p(0,1,e[t+2]*i),c=1===n?1:n**this.GR,l=1===s?1:s**this.GG,h=1===o?1:o**this.GB,u=this.MXA*c+this.MXB*l+this.MXC*h,d=this.MYA*c+this.MYB*l+this.MYC*h,f=this.MZA*c+this.MZB*l+this.MZC*h,g=CalRGBCS.#c;g[0]=u;g[1]=d;g[2]=f;const p=CalRGBCS.#l;this.#y(this.whitePoint,g,p);const m=CalRGBCS.#c;this.#b(this.blackPoint,p,m);const b=CalRGBCS.#l;this.#w(CalRGBCS.#s,m,b);const y=CalRGBCS.#c;this.#u(CalRGBCS.#n,b,y);a[r]=255*this.#g(y[0]);a[r+1]=255*this.#g(y[1]);a[r+2]=255*this.#g(y[2])}getRgbItem(e,t,a,r){this.#a(e,t,a,r,1)}getRgbBuffer(e,t,a,r,i,n,s){const o=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#x(e){return e>=6/29?e**3:108/841*(e-4/29)}#S(e,t,a,r){return a+e*(r-a)/t}#a(e,t,a,r,i){let n=e[t],s=e[t+1],o=e[t+2];if(!1!==a){n=this.#S(n,a,0,100);s=this.#S(s,a,this.amin,this.amax);o=this.#S(o,a,this.bmin,this.bmax)}s>this.amax?s=this.amax:sthis.bmax?o=this.bmax:o>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,a){let r=0;for(let i=a;i>=0;i--){r+=e[i]+t[i];e[i]=255&r;r>>=8}}function incHex(e,t){let a=1;for(let r=t;r>=0&&a>0;r--){a+=e[r];e[r]=255&a;a>>=8}}const xa=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const a=this.readByte();if(a<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&a);t=t<<7|127&a}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let a;const r=this.tmpBuf;let i=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");a=!(128&e);r[i++]=127&e}while(!a);let n=t,s=0,o=0;for(;n>=0;){for(;o<8&&r.length>0;){s|=r[--i]<>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const a=1&e[t]?255:0;let r=0;for(let i=0;i<=t;i++){r=(1&r)<<8|e[i];e[i]=r>>1^a}}readString(){const e=this.readNumber(),t=new Array(e);for(let a=0;a=0;){const e=d>>5;if(7===e){switch(31&d){case 0:r.readString();break;case 1:n=r.readString()}continue}const a=!!(16&d),i=15&d;if(i+1>xa)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const f=1,g=r.readNumber();switch(e){case 0:r.readHex(s,i);r.readHexNumber(o,i);addHex(o,s,i);t.addCodespaceRange(i+1,hexToInt(s,i),hexToInt(o,i));for(let e=1;er&&(a=r)}else{for(;!this.eof;)this.readBlock();a=this.bufferLength}this.pos=a;return this.buffer.subarray(t,a)}reset(){this.pos=0}makeSubStream(e,t,a=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const a=e+t;for(;this.bufferLength<=a&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,a)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){let a=0;for(const t of e)a+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(a);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let a;try{a=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const r=this.bufferLength,i=r+a.length;this.ensureBuffer(i).set(a,r);this.bufferLength=i}getBaseStreams(){const e=[];for(const t of this.streams){const a=t.getBaseStreams();a&&e.push(...a)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const a=this.bufferLength;let r,i;if(122===t){r=this.ensureBuffer(a+4);for(i=0;i<4;++i)r[a+i]=0;this.bufferLength+=4}else{const n=this.input;n[0]=t;for(i=1;i<5;++i){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();n[i]=t;if(-1===t||126===t)break}r=this.ensureBuffer(a+i-1);this.bufferLength+=i-1;if(i<5){for(;i<5;++i)n[i]=117;this.eof=!0}let s=0;for(i=0;i<5;++i)s=85*s+(n[i]-33);for(i=3;i>=0;--i){r[a+i]=255&s;s>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,a=this.ensureBuffer(this.bufferLength+t);let r=this.bufferLength,i=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(i<0)i=e;else{a[r++]=i<<4|e;i=-1}}if(i>=0&&this.eof){a[r++]=i<<4;i=-1}this.firstDigit=i;this.bufferLength=r}}const ka=-1,Aa=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Ca=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],va=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Fa=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Ia=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Oa=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if(!e||"function"!=typeof e.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let a;for(;0===(a=this._lookBits(12));)this._eatBits(1);1===a&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,a=this.columns;let r,i,n,s,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let n,o,c;if(this.nextLine2D){for(s=0;t[s]=64);do{o+=c=this._getWhiteCode()}while(c>=64)}else{do{n+=c=this._getWhiteCode()}while(c>=64);do{o+=c=this._getBlackCode()}while(c>=64)}this._addPixels(t[this.codingPos]+n,i);t[this.codingPos]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]=64);else do{n+=c=this._getWhiteCode()}while(c>=64);this._addPixels(t[this.codingPos]+n,i);i^=1}}let l=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){n=this._lookBits(12);if(this.eoline)for(;n!==ka&&1!==n;){this._eatBits(1);n=this._lookBits(12)}else for(;0===n;){this._eatBits(1);n=this._lookBits(12)}if(1===n){this._eatBits(12);l=!0}else n===ka&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&l&&this.byteAlign){n=this._lookBits(12);if(1===n){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(s=0;s<4;++s){n=this._lookBits(12);1!==n&&info("bad rtc code: "+n);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){n=this._lookBits(13);if(n===ka){this.eof=!0;return-1}if(n>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&n)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]n){o<<=n;1&this.codingPos||(o|=255>>8-n);this.outputBits-=n;n=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);n-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){o<<=n;n=0}}}while(n)}this.black&&(o^=255);return o}_addPixels(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}this.codingPos=r}_addPixelsNeg(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}else if(e0&&e=i){const t=a[e-i];if(t[0]===r){this._eatBits(r);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Aa[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Aa);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return ka}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===ka)return 1;e=t>>5==0?Ca[t]:va[t>>3];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,va);if(e[0])return e[1];e=this._findTableCode(11,12,Ca);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===ka)return 1;t=e>>7==0?Fa[e]:e>>9==0&&e>>7!=0?Ia[(e>>1)-64]:Oa[e>>7];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Oa);if(e[0])return e[1];e=this._findTableCode(7,12,Ia,64);if(e[0])return e[1];e=this._findTableCode(10,13,Fa);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,a){super(t);this.str=e;this.dict=e.dict;a instanceof Dict||(a=Dict.empty);const r={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(r,{K:a.get("K"),EndOfLine:a.get("EndOfLine"),EncodedByteAlign:a.get("EncodedByteAlign"),Columns:a.get("Columns"),Rows:a.get("Rows"),EndOfBlock:a.get("EndOfBlock"),BlackIs1:a.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Ta=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ma=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Da=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Ba=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ra=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const a=e.getByte(),r=e.getByte();if(-1===a||-1===r)throw new FormatError(`Invalid header in flate stream: ${a}, ${r}`);if(8!=(15&a))throw new FormatError(`Unknown compression method in flate stream: ${a}, ${r}`);if(((a<<8)+r)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${a}, ${r}`);if(32&r)throw new FormatError(`FDICT bit set in flate stream: ${a}, ${r}`);this.codeSize=0;this.codeBuf=0}getBits(e){const t=this.str;let a,r=this.codeSize,i=this.codeBuf;for(;r>e;this.codeSize=r-=e;return a}getCode(e){const t=this.str,a=e[0],r=e[1];let i,n=this.codeSize,s=this.codeBuf;for(;n>16,l=65535&o;if(c<1||n>c;this.codeSize=n-c;return l}generateHuffmanTable(e){const t=e.length;let a,r=0;for(a=0;ar&&(r=e[a]);const i=1<>=1}for(a=e;a>=1;if(0===n){let t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}let r=t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}r|=t<<8;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}i|=t<<8;if(i!==(65535&~r)&&(0!==r||0!==i))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const n=this.bufferLength,s=n+r;e=this.ensureBuffer(s);this.bufferLength=s;if(0===r)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(r);e.set(t,n);t.length0;)h[o++]=f}r=this.generateHuffmanTable(h.subarray(0,e));i=this.generateHuffmanTable(h.subarray(e,l))}}e=this.buffer;let s=e?e.length:0,o=this.bufferLength;for(;;){let a=this.getCode(r);if(a<256){if(o+1>=s){e=this.ensureBuffer(o+1);s=e.length}e[o++]=a;continue}if(256===a){this.bufferLength=o;return}a-=257;a=Ma[a];let n=a>>16;n>0&&(n=this.getBits(n));t=(65535&a)+n;a=this.getCode(i);a=Da[a];n=a>>16;n>0&&(n=this.getBits(n));const c=(65535&a)+n;if(o+t>=s){e=this.ensureBuffer(o+t);s=e.length}for(let a=0;a>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let a=e[t]>>1,r=1&e[t];const i=Na[a],n=i.qe;let s,o=this.a-n;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(0==(32768&o));this.a=o;e[t]=a<<1|r;return s}}class Jbig2Error extends sa{constructor(e){super(`JBIG2 error: ${e}`,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,a){this.data=e;this.start=t;this.end=a}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}const Ea=2**31-1,Pa=-(2**31);function decodeInteger(e,t,a){const r=e.getContexts(t);let i=1;function readBits(e){let t=0;for(let n=0;n>>0}const n=readBits(1),s=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===n?o=s:s>0&&(o=-s);return o>=Pa&&o<=Ea?o:null}function decodeIAID(e,t,a){const r=e.getContexts("IAID");let i=1;for(let e=0;e=v&&E=F){q=q<<1&m;for(p=0;p=0&&j=0){_=D[L][j];_&&(q|=_<=e?l<<=1:l=l<<1|S[o][c]}for(f=0;f=w||c<0||c>=y?l<<=1:l=l<<1|r[o][c]}const g=k.readBit(C,l);t[s]=g}}return S}function decodeTextRegion(e,t,a,r,i,n,s,o,c,l,h,u,d,f,g,p,m,b,y){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const w=[];let x,S;for(x=0;x1&&(i=e?y.readBits(b):decodeInteger(C,"IAIT",k));const n=s*v+i,F=e?f.symbolIDTable.decode(y):decodeIAID(C,k,c),O=t&&(e?y.readBit():decodeInteger(C,"IARI",k));let T=o[F],M=T[0].length,D=T.length;if(O){const e=decodeInteger(C,"IARDW",k),t=decodeInteger(C,"IARDH",k);M+=e;D+=t;T=decodeRefinement(M,D,g,T,(e>>1)+decodeInteger(C,"IARDX",k),(t>>1)+decodeInteger(C,"IARDY",k),!1,p,m)}let R=0;l?1&u?R=D-1:r+=D-1:u>1?r+=M-1:R=M-1;const N=n-(1&u?0:D-1),E=r-(2&u?M-1:0);let L,j,_;if(l)for(L=0;L>5&7;const c=[31&s];let l=t+6;if(7===s){o=536870911&readUint32(e,l-1);l+=3;let t=o+7>>3;c[0]=e[l++];for(;--t>0;)c.push(e[l++])}else if(5===s||6===s)throw new Jbig2Error("invalid referred-to flags");a.retainBits=c;let h=4;a.number<=256?h=1:a.number<=65536&&(h=2);const u=[];let d,f;for(d=0;d>>24&255;n[3]=t.height>>16&255;n[4]=t.height>>8&255;n[5]=255&t.height;for(d=l,f=e.length;d>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;l+=2;if(!e.huffman){c=0===e.template?4:1;s=[];for(o=0;o>2&3;h.stripSize=1<>4&3;h.transposed=!!(64&u);h.combinationOperator=u>>7&3;h.defaultPixelValue=u>>9&1;h.dsOffset=u<<17>>27;h.refinementTemplate=u>>15&1;if(h.huffman){const e=readUint16(r,l);l+=2;h.huffmanFS=3&e;h.huffmanDS=e>>2&3;h.huffmanDT=e>>4&3;h.huffmanRefinementDW=e>>6&3;h.huffmanRefinementDH=e>>8&3;h.huffmanRefinementDX=e>>10&3;h.huffmanRefinementDY=e>>12&3;h.huffmanRefinementSizeSelector=!!(16384&e)}if(h.refinement&&!h.refinementTemplate){s=[];for(o=0;o<2;o++){s.push({x:readInt8(r,l),y:readInt8(r,l+1)});l+=2}h.refinementAt=s}h.numberOfSymbolInstances=readUint32(r,l);l+=4;n=[h,a.referredTo,r,l,i];break;case 16:const d={},f=r[l++];d.mmr=!!(1&f);d.template=f>>1&3;d.patternWidth=r[l++];d.patternHeight=r[l++];d.maxPatternIndex=readUint32(r,l);l+=4;n=[d,a.number,r,l,i];break;case 22:case 23:const g={};g.info=readRegionSegmentInformation(r,l);l+=qa;const p=r[l++];g.mmr=!!(1&p);g.template=p>>1&3;g.enableSkip=!!(8&p);g.combinationOperator=p>>4&7;g.defaultPixelValue=p>>7&1;g.gridWidth=readUint32(r,l);l+=4;g.gridHeight=readUint32(r,l);l+=4;g.gridOffsetX=4294967295&readUint32(r,l);l+=4;g.gridOffsetY=4294967295&readUint32(r,l);l+=4;g.gridVectorX=readUint16(r,l);l+=2;g.gridVectorY=readUint16(r,l);l+=2;n=[g,a.referredTo,r,l,i];break;case 38:case 39:const m={};m.info=readRegionSegmentInformation(r,l);l+=qa;const b=r[l++];m.mmr=!!(1&b);m.template=b>>1&3;m.prediction=!!(8&b);if(!m.mmr){c=0===m.template?4:1;s=[];for(o=0;o>2&1;y.combinationOperator=w>>3&3;y.requiresBuffer=!!(32&w);y.combinationOperatorOverride=!!(64&w);n=[y];break;case 49:case 50:case 51:case 62:break;case 53:n=[a.number,r,l,i];break;default:throw new Jbig2Error(`segment type ${a.typeName}(${a.type}) is not implemented`)}const h="on"+a.typeName;h in t&&t[h].apply(t,n)}function processSegments(e,t){for(let a=0,r=e.length;a>3,a=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&a.fill(255);this.buffer=a}drawBitmap(e,t){const a=this.currentPageInfo,r=e.width,i=e.height,n=a.width+7>>3,s=a.combinationOperatorOverride?e.combinationOperator:a.combinationOperator,o=this.buffer,c=128>>(7&e.x);let l,h,u,d,f=e.y*n+(e.x>>3);switch(s){case 0:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;case 2:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;default:throw new Jbig2Error(`operator ${s} is not supported`)}}onImmediateGenericRegion(e,t,a,r){const i=e.info,n=new DecodingContext(t,a,r),s=decodeBitmap(e.mmr,i.width,i.height,e.template,e.prediction,null,e.at,n);this.drawBitmap(i,s)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,a,r,i,n){let s,o;if(e.huffman){s=function getSymbolDictionaryHuffmanTables(e,t,a){let r,i,n,s,o=0;switch(e.huffmanDHSelector){case 0:case 1:r=getStandardTable(e.huffmanDHSelector+4);break;case 3:r=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:i=getStandardTable(e.huffmanDWSelector+2);break;case 3:i=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){n=getCustomHuffmanTable(o,t,a);o++}else n=getStandardTable(1);s=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,a):getStandardTable(1);return{tableDeltaHeight:r,tableDeltaWidth:i,tableBitmapSize:n,tableAggregateInstances:s}}(e,a,this.customTables);o=new Reader(r,i,n)}let c=this.symbols;c||(this.symbols=c={});const l=[];for(const e of a){const t=c[e];t&&l.push(...t)}const h=new DecodingContext(r,i,n);c[t]=function decodeSymbolDictionary(e,t,a,r,i,n,s,o,c,l,h,u){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const d=[];let f=0,g=log2(a.length+r);const p=h.decoder,m=h.contextCache;let b,y;if(e){b=getStandardTable(1);y=[];g=Math.max(g,1)}for(;d.length1)w=decodeTextRegion(e,t,r,f,0,i,1,a.concat(d),g,0,0,1,0,n,c,l,h,0,u);else{const e=decodeIAID(m,p,g),t=decodeInteger(m,"IARDX",p),i=decodeInteger(m,"IARDY",p);w=decodeRefinement(r,f,c,e=32){let a,r,s;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");r=i.readBits(2)+3;a=n[e-1].prefixLength;break;case 33:r=i.readBits(3)+3;a=0;break;case 34:r=i.readBits(7)+11;a=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(s=0;s=0;m--){T=e?decodeMMRBitmap(O,c,l,!0):decodeBitmap(!1,c,l,a,!1,null,v,g);F[m]=T}for(M=0;M=0;b--){R^=F[b][M][D];N|=R<>8;j=u+M*d-D*f>>8;if(L>=0&&L+S<=r&&j>=0&&j+k<=i)for(m=0;m=i)){U=p[t];_=E[m];for(b=0;b=0&&e>1&7),c=1+(r>>4&7),l=[];let h,u,d=i;do{h=s.readBits(o);u=s.readBits(c);l.push(new HuffmanLine([d,h,u,0]));d+=1<>t&1;if(t<=0)this.children[a]=new HuffmanTreeNode(e);else{let r=this.children[a];r||(this.children[a]=r=new HuffmanTreeNode(null));r.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,a=e.length;t0&&this.rootNode.buildTree(a,a.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let a=0;for(let r=0;r=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,a=0;for(t=e-1;t>=0;t--)a|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,a){let r=0;for(let i=0,n=t.length;i>a&1;a--}}if(r&&!o){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;s>>24|t<<8|4278190080;a[r+2]=t>>>16|i<<16|4278190080;a[r+3]=i>>>8|4278190080}for(let t=4*s,i=e.length;t>>8|255;a[r+2]=t<<16|i>>>16|255;a[r+3]=i<<8|255}for(let t=4*s,i=e.length;t>3,u=7&r,d=e.length;a=new Uint32Array(a.buffer);let f=0;for(let r=0;r0&&!e[n-1];)n--;const s=[{children:[],index:0}];let o,c=s[0];for(a=0;a0;)c=s.pop();c.index++;s.push(c);for(;s.length<=a;){s.push(o={children:[],index:0});c.children[c.index]=o.children;c=o}i++}if(a+10){g--;return f>>g&1}f=e[t++];if(255===f){const r=e[t++];if(r){if(220===r&&l){const r=readUint16(e,t+=2);t+=2;if(r>0&&r!==a.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",r)}else if(217===r){if(l){const e=y*(8===a.precision?8:0);if(e>0&&Math.round(a.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(f<<8|r).toString(16)}`)}}g=7;return f>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){p--;return}let a=n;const r=s;for(;a<=r;){const r=decodeHuffman(e.huffmanTableAC),i=15&r,n=r>>4;if(0===i){if(n<15){p=receive(n)+(1<>4;if(0===i)if(l<15){p=receive(l)+(1<>4;if(0===r){if(n<15)break;i+=16;continue}i+=n;const s=za[i];e.blockData[t+s]=receiveAndExtend(r);i++}};let O,T=0;const M=1===w?r[0].blocksPerLine*r[0].blocksPerColumn:h*a.mcusPerColumn;let D,R;for(;T<=M;){const a=i?Math.min(M-T,i):M;if(a>0){for(S=0;S0?"unexpected":"excessive"} MCU data, current marker is: ${O.invalid}`);t=O.offset}if(!(O.marker>=65488&&O.marker<=65495))break;t+=2}return t-d}function quantizeAndInverse(e,t,a){const r=e.quantizationTable,i=e.blockData;let n,s,o,c,l,h,u,d,f,g,p,m,b,y,w,x,S;if(!r)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){f=i[t+e];g=i[t+e+1];p=i[t+e+2];m=i[t+e+3];b=i[t+e+4];y=i[t+e+5];w=i[t+e+6];x=i[t+e+7];f*=r[e];if(0!=(g|p|m|b|y|w|x)){g*=r[e+1];p*=r[e+2];m*=r[e+3];b*=r[e+4];y*=r[e+5];w*=r[e+6];x*=r[e+7];n=Ya*f+128>>8;s=Ya*b+128>>8;o=p;c=w;l=Za*(g-x)+128>>8;d=Za*(g+x)+128>>8;h=m<<4;u=y<<4;n=n+s+1>>1;s=n-s;S=o*Ja+c*Ka+128>>8;o=o*Ka-c*Ja+128>>8;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Va+d*Ga+2048>>12;l=l*Ga-d*Va+2048>>12;d=S;S=h*$a+u*Wa+2048>>12;h=h*Wa-u*$a+2048>>12;u=S;a[e]=n+d;a[e+7]=n-d;a[e+1]=s+u;a[e+6]=s-u;a[e+2]=o+h;a[e+5]=o-h;a[e+3]=c+l;a[e+4]=c-l}else{S=Ya*f+512>>10;a[e]=S;a[e+1]=S;a[e+2]=S;a[e+3]=S;a[e+4]=S;a[e+5]=S;a[e+6]=S;a[e+7]=S}}for(let e=0;e<8;++e){f=a[e];g=a[e+8];p=a[e+16];m=a[e+24];b=a[e+32];y=a[e+40];w=a[e+48];x=a[e+56];if(0!=(g|p|m|b|y|w|x)){n=Ya*f+2048>>12;s=Ya*b+2048>>12;o=p;c=w;l=Za*(g-x)+2048>>12;d=Za*(g+x)+2048>>12;h=m;u=y;n=4112+(n+s+1>>1);s=n-s;S=o*Ja+c*Ka+2048>>12;o=o*Ka-c*Ja+2048>>12;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Va+d*Ga+2048>>12;l=l*Ga-d*Va+2048>>12;d=S;S=h*$a+u*Wa+2048>>12;h=h*Wa-u*$a+2048>>12;u=S;f=n+d;x=n-d;g=s+u;w=s-u;p=o+h;y=o-h;m=c+l;b=c-l;f<16?f=0:f>=4080?f=255:f>>=4;g<16?g=0:g>=4080?g=255:g>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;b<16?b=0:b>=4080?b=255:b>>=4;y<16?y=0:y>=4080?y=255:y>>=4;w<16?w=0:w>=4080?w=255:w>>=4;x<16?x=0:x>=4080?x=255:x>>=4;i[t+e]=f;i[t+e+8]=g;i[t+e+16]=p;i[t+e+24]=m;i[t+e+32]=b;i[t+e+40]=y;i[t+e+48]=w;i[t+e+56]=x}else{S=Ya*f+8192>>14;S=S<-2040?0:S>=2024?255:S+2056>>4;i[t+e]=S;i[t+e+8]=S;i[t+e+16]=S;i[t+e+24]=S;i[t+e+32]=S;i[t+e+40]=S;i[t+e+48]=S;i[t+e+56]=S}}}function buildComponentData(e,t){const a=t.blocksPerLine,r=t.blocksPerColumn,i=new Int16Array(64);for(let e=0;e=r)return null;const n=readUint16(e,t);if(n>=65472&&n<=65534)return{invalid:null,marker:n,offset:t};let s=readUint16(e,i);for(;!(s>=65472&&s<=65534);){if(++i>=r)return null;s=readUint16(e,i)}return{invalid:n.toString(16),marker:s,offset:i}}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}parse(e,{dnlScanLines:t=null}={}){function readDataBlock(){const t=readUint16(e,i);i+=2;let a=i+t-2;const r=findNextFileMarker(e,a,i);if(r?.invalid){warn("readDataBlock - incorrect length, current marker is: "+r.invalid);a=r.offset}const n=e.subarray(i,a);i+=n.length;return n}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),a=Math.ceil(e.scanLines/8/e.maxV);for(const r of e.components){const i=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/e.maxH),n=Math.ceil(Math.ceil(e.scanLines/8)*r.v/e.maxV),s=t*r.h,o=64*(a*r.v)*(s+1);r.blockData=new Int16Array(o);r.blocksPerLine=i;r.blocksPerColumn=n}e.mcusPerLine=t;e.mcusPerColumn=a}let a,r,i=0,n=null,s=null,o=0;const c=[],l=[],h=[];let u=readUint16(e,i);i+=2;if(65496!==u)throw new JpegError("SOI not found");u=readUint16(e,i);i+=2;e:for(;65497!==u;){let d,f,g;switch(u){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const p=readDataBlock();65504===u&&74===p[0]&&70===p[1]&&73===p[2]&&70===p[3]&&0===p[4]&&(n={version:{major:p[5],minor:p[6]},densityUnits:p[7],xDensity:p[8]<<8|p[9],yDensity:p[10]<<8|p[11],thumbWidth:p[12],thumbHeight:p[13],thumbData:p.subarray(14,14+3*p[12]*p[13])});65518===u&&65===p[0]&&100===p[1]&&111===p[2]&&98===p[3]&&101===p[4]&&(s={version:p[5]<<8|p[6],flags0:p[7]<<8|p[8],flags1:p[9]<<8|p[10],transformCode:p[11]});break;case 65499:const m=readUint16(e,i);i+=2;const b=m+i-2;let y;for(;i>4==0)for(f=0;f<64;f++){y=za[f];a[y]=e[i++]}else{if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(f=0;f<64;f++){y=za[f];a[y]=readUint16(e,i);i+=2}}c[15&t]=a}break;case 65472:case 65473:case 65474:if(a)throw new JpegError("Only single frame JPEGs supported");i+=2;a={};a.extended=65473===u;a.progressive=65474===u;a.precision=e[i++];const w=readUint16(e,i);i+=2;a.scanLines=t||w;a.samplesPerLine=readUint16(e,i);i+=2;a.components=[];a.componentIds={};const x=e[i++];let S=0,k=0;for(d=0;d>4,n=15&e[i+1];S>4==0?h:l)[15&t]=buildHuffmanTable(a,n)}break;case 65501:i+=2;r=readUint16(e,i);i+=2;break;case 65498:const v=1==++o&&!t;i+=2;const F=e[i++],O=[];for(d=0;d>4];n.huffmanTableAC=l[15&s];O.push(n)}const T=e[i++],M=e[i++],D=e[i++];try{const t=decodeScan(e,i,a,O,r,T,M,D>>4,15&D,v);i+=t}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break e}throw t}break;case 65500:i+=4;break;case 65535:255!==e[i]&&i--;break;default:const R=findNextFileMarker(e,i-2,i-3);if(R?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+R.invalid);i=R.offset;break}if(!R||i>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break e}throw new JpegError("JpegImage.parse - unknown marker: "+u.toString(16))}u=readUint16(e,i);i+=2}if(!a)throw new JpegError("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine;this.height=a.scanLines;this.jfif=n;this.adobe=s;this.components=[];for(const e of a.components){const t=c[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/a.maxH,scaleY:e.v/a.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,a=!1){const r=this.width/e,i=this.height/t;let n,s,o,c,l,h,u,d,f,g,p,m=0;const b=this.components.length,y=e*t*b,w=new Uint8ClampedArray(y),x=new Uint32Array(e),S=4294967288;let k;for(u=0;u>8)+C[f+1];return w}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,a,r;for(let i=0,n=e.length;i4)throw new JpegError("Unsupported color mode");const n=this._getLinearizedBlockData(e,t,i);if(1===this.numComponents&&(a||r)){const e=n.length*(a?4:3),t=new Uint8ClampedArray(e);let r=0;if(a)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let a=0,r=e.length;a>24&255,n>>16&255,n>>8&255,255&n)}).`)}o&&(a+=s)}}parseImageProperties(e){let t=e.getByte();for(;t>=0;){const a=t;t=e.getByte();if(65361===(a<<8|t)){e.skip(4);const t=e.getInt32()>>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0;e.skip(16);const n=e.getUint16();this.width=t-r;this.height=a-i;this.componentsCount=n;this.bitsPerComponent=8;return}}throw new JpxError("No size marker found in JPX stream")}parseCodestream(e,t,a){const r={};let i=!1;try{let n=t;for(;n+1>5;o=[];for(;a>3;t.mu=0}else{t.epsilon=e[a]>>3;t.mu=(7&e[a])<<8|e[a+1];a+=2}o.push(t)}p.SPqcds=o;if(r.mainHeader)r.QCD=p;else{r.currentTile.QCD=p;r.currentTile.QCC=[]}break;case 65373:u=readUint16(e,n);const m={};a=n+2;let b;if(r.SIZ.Csiz<257)b=e[a++];else{b=readUint16(e,a);a+=2}s=e[a++];switch(31&s){case 0:c=8;l=!0;break;case 1:c=16;l=!1;break;case 2:c=16;l=!0;break;default:throw new Error("Invalid SQcd value "+s)}m.noQuantization=8===c;m.scalarExpounded=l;m.guardBits=s>>5;o=[];for(;a>3;t.mu=0}else{t.epsilon=e[a]>>3;t.mu=(7&e[a])<<8|e[a+1];a+=2}o.push(t)}m.SPqcds=o;r.mainHeader?r.QCC[b]=m:r.currentTile.QCC[b]=m;break;case 65362:u=readUint16(e,n);const y={};a=n+2;const w=e[a++];y.entropyCoderWithCustomPrecincts=!!(1&w);y.sopMarkerUsed=!!(2&w);y.ephMarkerUsed=!!(4&w);y.progressionOrder=e[a++];y.layersCount=readUint16(e,a);a+=2;y.multipleComponentTransform=e[a++];y.decompositionLevelsCount=e[a++];y.xcb=2+(15&e[a++]);y.ycb=2+(15&e[a++]);const x=e[a++];y.selectiveArithmeticCodingBypass=!!(1&x);y.resetContextProbabilities=!!(2&x);y.terminationOnEachCodingPass=!!(4&x);y.verticallyStripe=!!(8&x);y.predictableTermination=!!(16&x);y.segmentationSymbolUsed=!!(32&x);y.reversibleTransformation=e[a++];if(y.entropyCoderWithCustomPrecincts){const t=[];for(;a>4})}y.precinctsSizes=t}const S=[];y.selectiveArithmeticCodingBypass&&S.push("selectiveArithmeticCodingBypass");y.terminationOnEachCodingPass&&S.push("terminationOnEachCodingPass");y.verticallyStripe&&S.push("verticallyStripe");y.predictableTermination&&S.push("predictableTermination");if(S.length>0){i=!0;warn(`JPX: Unsupported COD options (${S.join(", ")}).`)}if(r.mainHeader)r.COD=y;else{r.currentTile.COD=y;r.currentTile.COC=[]}break;case 65424:u=readUint16(e,n);h={};h.index=readUint16(e,n+2);h.length=readUint32(e,n+4);h.dataEnd=h.length+n-2;h.partIndex=e[n+8];h.partsCount=e[n+9];r.mainHeader=!1;if(0===h.partIndex){h.COD=r.COD;h.COC=r.COC.slice(0);h.QCD=r.QCD;h.QCC=r.QCC.slice(0)}r.currentTile=h;break;case 65427:h=r.currentTile;if(0===h.partIndex){initializeTile(r,h.index);buildPackets(r)}u=h.dataEnd-n;parseTilePackets(r,e,n,u);break;case 65363:warn("JPX: Codestream code 0xFF53 (COC) is not implemented.");case 65365:case 65367:case 65368:case 65380:u=readUint16(e,n);break;default:throw new Error("Unknown codestream code: "+t.toString(16))}n+=u}}catch(e){if(i||this.failOnCorruptedImage)throw new JpxError(e.message);warn(`JPX: Trying to recover from: "${e.message}".`)}this.tiles=function transformComponents(e){const t=e.SIZ,a=e.components,r=t.Csiz,i=[];for(let t=0,n=e.tiles.length;t>2);c[b++]=e+m>>h;c[b++]=e>>h;c[b++]=e+p>>h}else for(d=0;d>h;c[b++]=g-.34413*p-.71414*m>>h;c[b++]=g+1.772*p>>h}if(e)for(d=0,b=3;d>h}else for(let e=0;e>h;b+=r}}i.push(l)}return i}(r);this.width=r.SIZ.Xsiz-r.SIZ.XOsiz;this.height=r.SIZ.Ysiz-r.SIZ.YOsiz;this.componentsCount=r.SIZ.Csiz}}function calculateComponentDimensions(e,t){e.x0=Math.ceil(t.XOsiz/e.XRsiz);e.x1=Math.ceil(t.Xsiz/e.XRsiz);e.y0=Math.ceil(t.YOsiz/e.YRsiz);e.y1=Math.ceil(t.Ysiz/e.YRsiz);e.width=e.x1-e.x0;e.height=e.y1-e.y0}function calculateTileGrids(e,t){const a=e.SIZ,r=[];let i;const n=Math.ceil((a.Xsiz-a.XTOsiz)/a.XTsiz),s=Math.ceil((a.Ysiz-a.YTOsiz)/a.YTsiz);for(let e=0;e0?Math.min(r.xcb,i.PPx-1):Math.min(r.xcb,i.PPx);i.ycb_=a>0?Math.min(r.ycb,i.PPy-1):Math.min(r.ycb,i.PPy);return i}function buildPrecincts(e,t,a){const r=1<t.trx0?Math.ceil(t.trx1/r)-Math.floor(t.trx0/r):0,l=t.try1>t.try0?Math.ceil(t.try1/i)-Math.floor(t.try0/i):0,h=c*l;t.precinctParameters={precinctWidth:r,precinctHeight:i,numprecinctswide:c,numprecinctshigh:l,numprecincts:h,precinctWidthInSubband:s,precinctHeightInSubband:o}}function buildCodeblocks(e,t,a){const r=a.xcb_,i=a.ycb_,n=1<>r,c=t.tby0>>i,l=t.tbx1+n-1>>r,h=t.tby1+s-1>>i,u=t.resolution.precinctParameters,d=[],f=[];let g,p,m,b;for(p=c;pe.cbxMax&&(e.cbxMax=g);pe.cbyMax&&(e.cbyMax=p)}else f[b]=e={cbxMin:g,cbyMin:p,cbxMax:g,cbyMax:p};m.precinct=e}t.codeblockParameters={codeblockWidth:r,codeblockHeight:i,numcodeblockwide:l-o+1,numcodeblockhigh:h-c+1};t.codeblocks=d;t.precincts=f}function createPacket(e,t,a){const r=[],i=e.subbands;for(let e=0,a=i.length;ee.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[c],a=t.precinctParameters.numprecincts;for(;he.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[o],a=t.precinctParameters.numprecincts;for(;he.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[o],a=t.precinctParameters.numprecincts;if(!(l>=a)){for(;s=0;--e){const a=t.resolutions[e],r=g*a.precinctParameters.precinctWidth,i=g*a.precinctParameters.precinctHeight;h=Math.min(h,r);u=Math.min(u,i);d=Math.max(d,a.precinctParameters.numprecinctswide);f=Math.max(f,a.precinctParameters.numprecinctshigh);l[e]={width:r,height:i};g<<=1}a=Math.min(a,h);r=Math.min(r,u);i=Math.max(i,d);n=Math.max(n,f);s[o]={resolutions:l,minWidth:h,minHeight:u,maxNumWide:d,maxNumHigh:f}}return{components:s,minWidth:a,minHeight:r,maxNumWide:i,maxNumHigh:n}}function buildPackets(e){const t=e.SIZ,a=e.currentTile.index,r=e.tiles[a],i=t.Csiz;for(let e=0;e>>s&(1<0;){const e=i.shift();s=e.codeblock;void 0===s.data&&(s.data=[]);s.data.push({data:t,start:a+n,end:a+n+e.dataLength,codingpasses:e.codingpasses});n+=e.dataLength}}return n}function copyCoefficients(e,t,a,r,i,n,s,o,c){const l=r.tbx0,h=r.tby0,u=r.tbx1-r.tbx0,d=r.codeblocks,f="H"===r.type.charAt(0)?1:0,g="H"===r.type.charAt(1)?t:0;for(let a=0,p=d.length;a=n?_:_*(1<0?1-e:0)}const g=t.subbands[r],p=Qa[g.type];copyCoefficients(n,a,0,g,f?1:2**(d+p-s)*(1+i/2048),l+s-1,f,h,u)}p.push({width:a,height:i,items:n})}const b=g.calculate(p,r.tcx0,r.tcy0);return{left:r.tcx0,top:r.tcy0,width:b.width,height:b.height,items:b.items}}function initializeTile(e,t){const a=e.SIZ.Csiz,r=e.tiles[t];for(let t=0;t>=1;t>>=1;r++}r--;a=this.levels[r];a.items[a.index]=i;this.currentLevel=r;delete this.value}incrementValue(){const e=this.levels[this.currentLevel];e.items[e.index]++}nextLevel(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];e--;if(e<0){this.value=a;return!1}this.currentLevel=e;t=this.levels[e];t.items[t.index]=a;return!0}}class InclusionTree{constructor(e,t,a){const r=log2(Math.max(e,t))+1;this.levels=[];for(let i=0;ia){this.currentLevel=r;this.propagateValues();return!1}e>>=1;t>>=1;r++}this.currentLevel=r-1;return!0}incrementValue(e){const t=this.levels[this.currentLevel];t.items[t.index]=e+1;this.propagateValues()}propagateValues(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];for(;--e>=0;){t=this.levels[e];t.items[t.index]=a}}nextLevel(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];t.items[t.index]=255;e--;if(e<0)return!1;this.currentLevel=e;t=this.levels[e];t.items[t.index]=a;return!0}}class BitModel{static UNIFORM_CONTEXT=17;static RUNLENGTH_CONTEXT=18;static LLAndLHContextsLabel=new Uint8Array([0,5,8,0,3,7,8,0,4,7,8,0,0,0,0,0,1,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8]);static HLContextLabel=new Uint8Array([0,3,4,0,5,7,7,0,8,8,8,0,0,0,0,0,1,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8]);static HHContextLabel=new Uint8Array([0,1,2,0,1,2,2,0,2,2,2,0,0,0,0,0,3,4,5,0,4,5,5,0,5,5,5,0,0,0,0,0,6,7,7,0,7,7,7,0,7,7,7,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8]);constructor(e,t,a,r,i){this.width=e;this.height=t;let n;n="HH"===a?BitModel.HHContextLabel:"HL"===a?BitModel.HLContextLabel:BitModel.LLAndLHContextsLabel;this.contextLabelTable=n;const s=e*t;this.neighborsSignificance=new Uint8Array(s);this.coefficentsSign=new Uint8Array(s);let o;o=i>14?new Uint32Array(s):i>6?new Uint16Array(s):new Uint8Array(s);this.coefficentsMagnitude=o;this.processingFlags=new Uint8Array(s);const c=new Uint8Array(s);if(0!==r)for(let e=0;e0,o=t+10){c=a-i;s&&(r[c-1]+=16);o&&(r[c+1]+=16);r[c]+=4}if(e+1=a)break;s[d]&=-2;if(r[d]||!n[d])continue;const g=c[n[d]];if(e.readBit(o,g)){const e=this.decodeSignBit(t,u,d);i[d]=e;r[d]=1;this.setNeighborsSignificance(t,u,d);s[d]|=2}l[d]++;s[d]|=1}}}decodeSignBit(e,t,a){const r=this.width,i=this.height,n=this.coefficentsMagnitude,s=this.coefficentsSign;let o,c,l,h,u,d;h=t>0&&0!==n[a-1];if(t+10&&0!==n[a-r];if(e+1=0){u=9+o;d=this.decoder.readBit(this.contexts,u)}else{u=9-o;d=1^this.decoder.readBit(this.contexts,u)}return d}runMagnitudeRefinementPass(){const e=this.decoder,t=this.width,a=this.height,r=this.coefficentsMagnitude,i=this.neighborsSignificance,n=this.contexts,s=this.bitsDecoded,o=this.processingFlags,c=t*a,l=4*t;for(let a,h=0;h>1;let i,n,s,o;const c=-1.586134342059924,l=-.052980118572961,h=.882911075530934,u=.443506852043971,d=1.230174104914001;i=(t|=0)-3;for(n=r+4;n--;i+=2)e[i]*=.8128930661159609;i=t-2;s=u*e[i-1];for(n=r+3;n--;i+=2){o=u*e[i+1];e[i]=d*e[i]-s-o;if(!n--)break;i+=2;s=u*e[i+1];e[i]=d*e[i]-s-o}i=t-1;s=h*e[i-1];for(n=r+2;n--;i+=2){o=h*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=h*e[i+1];e[i]-=s+o}i=t;s=l*e[i-1];for(n=r+1;n--;i+=2){o=l*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=l*e[i+1];e[i]-=s+o}if(0!==r){i=t+1;s=c*e[i-1];for(n=r;n--;i+=2){o=c*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=c*e[i+1];e[i]-=s+o}}}}class ReversibleTransform extends Transform{filter(e,t,a){const r=a>>1;let i,n;for(i=t|=0,n=r+1;n--;i+=2)e[i]-=e[i-1]+e[i+1]+2>>2;for(i=t+1,n=r;n--;i+=2)e[i]+=e[i-1]+e[i+1]>>1}}class JpxStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=a}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(){if(this.eof)return;const e=new JpxImage;e.parse(this.bytes);const t=e.width,a=e.height,r=e.componentsCount,i=e.tiles.length;if(1===i)this.buffer=e.tiles[0].items;else{const n=new Uint8ClampedArray(t*a*r);for(let a=0;a>>t&(1<0;if(e<256){d[0]=e;f=1}else{if(!(e>=258)){if(256===e){h=9;s=258;f=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){d[t]=o[a];a=l[a]}}else d[f++]=d[0]}if(i){l[s]=u;c[s]=c[u]+1;o[s]=d[0];s++;h=s+n&s+n-1?h:0|Math.min(Math.log(s+n)/.6931471805599453+1,12)}u=e;g+=f;if(r15))throw new FormatError(`Unsupported predictor: ${r}`);this.readBlock=2===r?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const i=this.colors=a.get("Colors")||1,n=this.bits=a.get("BPC","BitsPerComponent")||8,s=this.columns=a.get("Columns")||1;this.pixBytes=i*n+7>>3;this.rowBytes=s*i*n+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,a=this.ensureBuffer(t+e),r=this.bits,i=this.colors,n=this.str.getBytes(e);this.eof=!n.length;if(this.eof)return;let s,o=0,c=0,l=0,h=0,u=t;if(1===r&&1===i)for(s=0;s>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;a[u++]=e}else if(8===r){for(s=0;s>8&255;a[u++]=255&e}}else{const e=new Uint8Array(i+1),u=(1<>l-r)&u;l-=r;c=c<=8){a[f++]=c>>h-8&255;h-=8}}h>0&&(a[f++]=(c<<8-h)+(o&(1<<8-h)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,a=this.str.getByte(),r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;const i=this.bufferLength,n=this.ensureBuffer(i+e);let s=n.subarray(i-e,i);0===s.length&&(s=new Uint8Array(e));let o,c,l,h=i;switch(a){case 0:for(o=0;o>1)+r[o];for(;o>1)+r[o]&255;h++}break;case 4:for(o=0;o0){const e=this.str.getBytes(r);t.set(e,a);a+=r}}else{r=257-r;const i=e[1];t=this.ensureBuffer(a+r+1);for(let e=0;e>")&&this.buf1!==da;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===da)break;r.set(t,this.getObj(e))}if(this.buf1===da){if(this.recoveryMode)return r;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(r,e):r;this.shift();return r;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,a=e.pos;let r,i,n=0;for(;-1!==(r=e.getByte());)if(0===n)n=69===r?1:0;else if(1===n)n=73===r?2:0;else if(32===r||10===r||13===r){i=e.pos;const a=e.peekBytes(15),s=a.length;if(0===s)break;for(let e=0;e127))){n=0;break}}if(2!==n)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(a.slice()),t);o._hexStringWarn=()=>{};let c=0;for(;;){const e=o.getObj();if(e===da){n=0;break}if(e instanceof Cmd){const a=t[e.cmd];if(!a){n=0;break}if(a.variableArgs?c<=a.numArgs:c===a.numArgs)break;c=0}else c++}if(2===n)break}else n=0;if(-1===r){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(i){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-i))}}let s=4;e.skip(-s);r=e.peekByte();e.skip(s);isWhiteSpace(r)||s--;return e.pos-s-a}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let a,r,i=!1;for(;-1!==(a=e.getByte());)if(255===a){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:i=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:r=e.getUint16();r>2?e.skip(r-2):e.skip(-2)}if(i)break}const n=e.pos-t;if(-1===a){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-n);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return n}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte());)if(126===a){const t=e.pos;a=e.peekByte();for(;isWhiteSpace(a);){e.skip();a=e.peekByte()}if(62===a){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const r=e.pos-t;if(-1===a){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte())&&62!==a;);const r=e.pos-t;if(-1===a){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}inlineStreamSkipEI(e){let t,a=0;for(;-1!==(t=e.getByte());)if(0===a)a=69===t?1:0;else if(1===a)a=73===t?2:0;else if(2===a)break}makeInlineImage(e){const t=this.lexer,a=t.stream,r=Object.create(null);let i;for(;!isCmd(this.buf1,"ID")&&this.buf1!==da;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===da)break;r[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(i=a.pos-t.beginInlineImagePos);const n=this.xref.fetchIfRef(r.F||r.Filter);let s;if(n instanceof Name)s=n.name;else if(Array.isArray(n)){const e=this.xref.fetchIfRef(n[0]);e instanceof Name&&(s=e.name)}const o=a.pos;let c,l;switch(s){case"DCT":case"DCTDecode":c=this.findDCTDecodeInlineStreamEnd(a);break;case"A85":case"ASCII85Decode":c=this.findASCII85DecodeInlineStreamEnd(a);break;case"AHx":case"ASCIIHexDecode":c=this.findASCIIHexDecodeInlineStreamEnd(a);break;default:c=this.findDefaultInlineStreamEnd(a)}if(c<1e3&&i>0){const e=a.pos;a.pos=t.beginInlineImagePos;l=function getInlineImageCacheKey(e){const t=[],a=e.length;let r=0;for(;r=r){a.pos+=s;return a.pos-e}s++}a.pos+=n}return-1}makeStream(e,t){const a=this.lexer;let r=a.stream;a.skipToNextLine();const i=r.pos-1;let n=e.get("Length");if(!Number.isInteger(n)){info(`Bad length "${n&&n.toString()}" in stream.`);n=0}r.pos=i+n;a.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{const e=new Uint8Array([101,110,100,115,116,114,101,97,109]);let t=this._findStreamLength(i,e);if(t<0){const a=1;for(let n=1;n<=a;n++){const a=e.length-n,s=e.slice(0,a),o=this._findStreamLength(i,s);if(o>=0){if(!isWhiteSpace(r.peekBytes(a+1)[a]))break;info(`Found "${bytesToString(s)}" when searching for endstream command.`);t=o;break}}if(t<0)throw new FormatError("Missing endstream command.")}n=t;a.nextChar();this.shift();this.shift()}this.shift();r=r.makeSubStream(i,n,e);t&&(r=t.createStream(r,n));r=this.filter(r,e,n);r.dict=e;return r}filter(e,t,a){let r=t.get("F","Filter"),i=t.get("DP","DecodeParms");if(r instanceof Name){Array.isArray(i)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,r.name,a,i)}let n=a;if(Array.isArray(r)){const t=r,a=i;for(let s=0,o=t.length;s=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,a=0,r=1;if(45===e){r=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){a=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let i=e-48,n=0,s=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const r=e-48;if(t)n=10*n+r;else{0!==a&&(a*=10);i=10*i+r}}else if(46===e){if(0!==a)break;a=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){s=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==a&&(i/=a);t&&(i*=10**(s*n));return r*i}getString(){let e=1,t=!1;const a=this.strBuf;a.length=0;let r=this.nextChar();for(;;){let i=!1;switch(0|r){case-1:warn("Unterminated string");t=!0;break;case 40:++e;a.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else a.push(")");break;case 92:r=this.nextChar();switch(r){case-1:warn("Unterminated string");t=!0;break;case 110:a.push("\n");break;case 114:a.push("\r");break;case 116:a.push("\t");break;case 98:a.push("\b");break;case 102:a.push("\f");break;case 92:case 40:case 41:a.push(String.fromCharCode(r));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&r;r=this.nextChar();i=!0;if(r>=48&&r<=55){e=(e<<3)+(15&r);r=this.nextChar();if(r>=48&&r<=55){i=!1;e=(e<<3)+(15&r)}}a.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:a.push(String.fromCharCode(r))}break;default:a.push(String.fromCharCode(r))}if(t)break;i||(r=this.nextChar())}return a.join("")}getName(){let e,t;const a=this.strBuf;a.length=0;for(;(e=this.nextChar())>=0&&!er[e];)if(35===e){e=this.nextChar();if(er[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");a.push("#");break}const r=toHexDigit(e);if(-1!==r){t=e;e=this.nextChar();const i=toHexDigit(e);if(-1===i){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);a.push("#",String.fromCharCode(t));if(er[e])break;a.push(String.fromCharCode(e));continue}a.push(String.fromCharCode(r<<4|i))}else a.push("#",String.fromCharCode(e))}else a.push(String.fromCharCode(e));a.length>127&&warn(`Name token is longer than allowed by the spec: ${a.length}`);return Name.get(a.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t,a,r=this.currentChar,i=!0;this._hexStringNumWarn=0;for(;;){if(r<0){warn("Unterminated hex string");break}if(62===r){this.nextChar();break}if(1!==er[r]){if(i){t=toHexDigit(r);if(-1===t){this._hexStringWarn(r);r=this.nextChar();continue}}else{a=toHexDigit(r);if(-1===a){this._hexStringWarn(r);r=this.nextChar();continue}e.push(String.fromCharCode(t<<4|a))}i=!i;r=this.nextChar()}else r=this.nextChar()}return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return da;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==er[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let a=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(a)}}const r=this.knownCommands;let i=void 0!==r?.[a];for(;(t=this.nextChar())>=0&&!er[t];){const e=a+String.fromCharCode(t);if(i&&void 0===r[e])break;if(128===a.length)throw new FormatError(`Command token too long: ${a.length}`);a=e;i=void 0!==r?.[a]}if("true"===a)return!0;if("false"===a)return!1;if("null"===a)return null;"BI"===a&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(a)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,a=!1){const r=e.get(t);if(Number.isInteger(r)&&(a?r>=0:r>0))return r;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),a=t.getObj(),r=t.getObj(),i=t.getObj(),n=t.getObj();let s,o;if(!(Number.isInteger(a)&&Number.isInteger(r)&&isCmd(i,"obj")&&n instanceof Dict&&"number"==typeof(s=n.get("Linearized"))&&s>0))return null;if((o=getInt(n,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let a;if(Array.isArray(t)&&(2===(a=t.length)||4===a)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:getInt(n,"O"),endFirst:getInt(n,"E"),numPages:getInt(n,"N"),mainXRefEntriesOffset:getInt(n,"T"),pageFirst:n.has("P")?getInt(n,"P",!0):0}}}const tr=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ar=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,a){this.codespaceRanges[e-1].push(t,a);this.numCodespaceRanges++}mapCidRange(e,t,a){if(t-e>ar)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=a++}mapBfRange(e,t,a){if(t-e>ar)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const r=a.length-1;for(;e<=t;){this._map[e++]=a;const t=a.charCodeAt(r)+1;t>255?a=a.substring(0,r-1)+String.fromCharCode(a.charCodeAt(r-1)+1)+"\0":a=a.substring(0,r)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,a){if(t-e>ar)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const r=a.length;let i=0;for(;e<=t&&i>>0;const s=i[n];for(let e=0,t=s.length;e=t&&r<=i){a.charcode=r;a.length=n+1;return}}}a.charcode=0;a.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let a=0,r=t.length;a=i&&e<=n)return a+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,a){unreachable("should not call mapCidRange")}mapBfRange(e,t,a){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,a){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let a=0;a>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endbfchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=a;e.mapOne(r,i)}}function parseBfRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endbfrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();if(Number.isInteger(a)||"string"==typeof a){const t=Number.isInteger(a)?String.fromCharCode(a):a;e.mapBfRange(r,i,t)}else{if(!isCmd(a,"["))break;{a=t.getObj();const n=[];for(;!isCmd(a,"]")&&a!==da;){n.push(a);a=t.getObj()}e.mapBfRangeToArray(r,i,n)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcidchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectInt(a);const i=a;e.mapOne(r,i)}}function parseCidRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcidrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();expectInt(a);const n=a;e.mapCidRange(r,i,n)}}function parseCodespaceRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcodespacerange"))return;if("string"!=typeof a)break;const r=strToInt(a);a=t.getObj();if("string"!=typeof a)break;const i=strToInt(a);e.addCodespaceRange(a.length,r,i)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const a=t.getObj();Number.isInteger(a)&&(e.vertical=!!a)}function parseCMapName(e,t){const a=t.getObj();a instanceof Name&&(e.name=a.name)}async function parseCMap(e,t,a,r){let i,n;e:for(;;)try{const a=t.getObj();if(a===da)break;if(a instanceof Name){"WMode"===a.name?parseWMode(e,t):"CMapName"===a.name&&parseCMapName(e,t);i=a}else if(a instanceof Cmd)switch(a.cmd){case"endcmap":break e;case"usecmap":i instanceof Name&&(n=i.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!r&&n&&(r=n);return r?extendCMap(e,a,r):e}async function extendCMap(e,t,a){e.useCMap=await createBuiltInCMap(a,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let a=0;aextendCMap(i,t,e)));if(r===ke.NONE){const e=new Lexer(new Stream(a));return parseCMap(i,e,t,null)}throw new Error(`Invalid CMap "compressionType" value: ${r}`)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:a}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const r=await parseCMap(new CMap,new Lexer(e),t,a);return r.isIdentityCMap?createBuiltInCMap(r.name,t):r}throw new Error("Encoding required.")}}const rr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],ir=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],nr=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],sr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],or=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],cr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],lr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],hr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],ur=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],dr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return hr;case"StandardEncoding":return lr;case"MacRomanEncoding":return cr;case"SymbolSetEncoding":return ur;case"ZapfDingbatsEncoding":return dr;case"ExpertEncoding":return sr;case"MacExpertEncoding":return or;default:return null}}const fr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],gr=391,pr=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],mr=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,a){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!a}parse(){const e=this.properties,t=new CFF;this.cff=t;const a=this.parseHeader(),r=this.parseIndex(a.endPos),i=this.parseIndex(r.endPos),n=this.parseIndex(i.endPos),s=this.parseIndex(n.endPos),o=this.parseDict(i.obj.get(0)),c=this.createDict(CFFTopDict,o,t.strings);t.header=a.obj;t.names=this.parseNameIndex(r.obj);t.strings=this.parseStringIndex(n.obj);t.topDict=c;t.globalSubrIndex=s.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=c.hasName("ROS");const l=c.getByName("CharStrings"),h=this.parseIndex(l).obj,u=c.getByName("FontMatrix");u&&(e.fontMatrix=u);const d=c.getByName("FontBBox");if(d){e.ascent=Math.max(d[3],d[1]);e.descent=Math.min(d[1],d[3]);e.ascentScaled=!0}let f,g;if(t.isCIDFont){const e=this.parseIndex(c.getByName("FDArray")).obj;for(let a=0,r=e.count;a=t)throw new FormatError("Invalid CFF header");if(0!==a){info("cff data is shifted");e=e.subarray(a);this.bytes=e}const r=e[0],i=e[1],n=e[2],s=e[3];return{obj:new CFFHeader(r,i,n,s),endPos:n}}parseDict(e){let t=0;function parseOperand(){let a=e[t++];if(30===a)return function parseFloatOperand(){let a="";const r=15,i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],n=e.length;for(;t>4,o=15&n;if(s===r)break;a+=i[s];if(o===r)break;a+=i[o]}return parseFloat(a)}();if(28===a){a=e[t++];a=(a<<24|e[t++]<<16)>>16;return a}if(29===a){a=e[t++];a=a<<8|e[t++];a=a<<8|e[t++];a=a<<8|e[t++];return a}if(a>=32&&a<=246)return a-139;if(a>=247&&a<=250)return 256*(a-247)+e[t++]+108;if(a>=251&&a<=254)return-256*(a-251)-e[t++]-108;warn('CFFParser_parseDict: "'+a+'" is a reserved command.');return NaN}let a=[];const r=[];t=0;const i=e.length;for(;t10)return!1;let i=e.stackSize;const n=e.stack;let s=t.length;for(let o=0;o>16;o+=2;i++}else if(14===c){if(i>=4){i-=4;if(this.seacAnalysisEnabled){e.seac=n.slice(i,i+4);return!1}}l=pr[c]}else if(c>=32&&c<=246){n[i]=c-139;i++}else if(c>=247&&c<=254){n[i]=c<251?(c-247<<8)+t[o]+108:-(c-251<<8)-t[o]-108;o++;i++}else if(255===c){n[i]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;i++}else if(19===c||20===c){e.hints+=i>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}o+=e.hints+7>>3;i%=2;l=pr[c]}else{if(10===c||29===c){const t=10===c?a:r;if(!t){l=pr[c];warn("Missing subrsIndex for "+l.id);return!1}let s=32768;t.count<1240?s=107:t.count<33900&&(s=1131);const o=n[--i]+s;if(o<0||o>=t.count||isNaN(o)){l=pr[c];warn("Out of bounds subrIndex for "+l.id);return!1}e.stackSize=i;e.callDepth++;if(!this.parseCharString(e,t.get(o),a,r))return!1;e.callDepth--;i=e.stackSize;continue}if(11===c){e.stackSize=i;return!0}if(0===c&&o===t.length){t[o-1]=14;l=pr[14]}else{if(9===c){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}l=pr[c]}}if(l){if(l.stem){e.hints+=i>>1;if(3===c||23===c)e.hasVStems=!0;else if(e.hasVStems&&(1===c||18===c)){warn("CFF stem hints are in wrong order");t[o-1]=1===c?3:23}}if("min"in l&&!e.undefStack&&i=2&&l.stem?i%=2:i>1&&warn("Found too many parameters for stack-clearing command");i>0&&(e.width=n[i-1])}if("stackDelta"in l){"stackFn"in l&&l.stackFn(n,i);i+=l.stackDelta}else if(l.stackClearing)i=0;else if(l.resetStack){i=0;e.undefStack=!1}else if(l.undefStack){i=0;e.undefStack=!0;e.firstStackClearing=!1}}}s=i.length){warn("Invalid fd index for glyph index.");u=!1}if(u){f=i[e].privateDict;d=f.subrsIndex}}else t&&(d=t);u&&(u=this.parseCharString(h,c,d,a));if(null!==h.width){const e=f.getByName("nominalWidthX");o[l]=e+h.width}else{const e=f.getByName("defaultWidthX");o[l]=e}null!==h.seac&&(s[l]=h.seac);u||e.set(l,new Uint8Array([14]))}return{charStrings:e,seacs:s,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const a=t[0],r=t[1];if(0===a||r>=this.bytes.length){this.emptyPrivateDictionary(e);return}const i=r+a,n=this.bytes.subarray(r,i),s=this.parseDict(n),o=this.createDict(CFFPrivateDict,s,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const c=o.getByName("Subrs"),l=r+c;if(0===c||l>=this.bytes.length){this.emptyPrivateDictionary(e);return}const h=this.parseIndex(l);o.subrsIndex=h.obj}parseCharsets(e,t,a,r){if(0===e)return new CFFCharset(!0,wr.ISO_ADOBE,rr);if(1===e)return new CFFCharset(!0,wr.EXPERT,ir);if(2===e)return new CFFCharset(!0,wr.EXPERT_SUBSET,nr);const i=this.bytes,n=e,s=i[e++],o=[r?0:".notdef"];let c,l,h;t-=1;switch(s){case 0:for(h=0;h=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,a,r){this.major=e;this.minor=t;this.hdrSize=a;this.offSize=r}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?fr[e]:e-gr<=this.strings.length?this.strings[e-gr]:fr[0]}getSID(e){let t=fr.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+gr:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const a of t)if(isNaN(a)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const a=this.types[e];"num"!==a&&"sid"!==a&&"offset"!==a||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const a of e){const e=Array.isArray(a[0])?(a[0][0]<<8)+a[0][1]:a[0];t.keyToNameMap[e]=a[1];t.nameToKeyMap[a[1]]=e;t.types[e]=a[2];t.defaults[e]=a[3];t.opcodes[e]=Array.isArray(a[0])?a[0]:[a[0]];t.order.push(e)}return t}}const br=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(br))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const yr=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(yr))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const wr={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,a,r){this.predefined=e;this.format=t;this.charset=a;this.raw=r}}class CFFEncoding{constructor(e,t,a,r){this.predefined=e;this.format=t;this.encoding=a;this.raw=r}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,a){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const r=a.data,i=this.offsets[e];for(let e=0,a=t.length;e>24&255;r[s]=l>>16&255;r[o]=l>>8&255;r[c]=255&l}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},a=this.compileHeader(e.header);t.add(a);const r=this.compileNameIndex(e.names);t.add(r);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const a of e.fdArray){let e=t.slice(0);a.hasName("FontMatrix")&&(e=Util.transform(e,a.getByName("FontMatrix")));a.setByName("FontMatrix",e)}}const i=e.topDict.getByName("XUID");i?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let n=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(n.output);const s=n.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const c=this.compileIndex(e.globalSubrIndex);t.add(c);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)s.setEntryLocation("Encoding",[e.encoding.format],t);else{const a=this.compileEncoding(e.encoding);s.setEntryLocation("Encoding",[t.length],t);t.add(a)}const l=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);s.setEntryLocation("charset",[t.length],t);t.add(l);const h=this.compileCharStrings(e.charStrings);s.setEntryLocation("CharStrings",[t.length],t);t.add(h);if(e.isCIDFont){s.setEntryLocation("FDSelect",[t.length],t);const a=this.compileFDSelect(e.fdSelect);t.add(a);n=this.compileTopDicts(e.fdArray,t.length,!0);s.setEntryLocation("FDArray",[t.length],t);t.add(n.output);const r=n.trackers;this.compilePrivateDicts(e.fdArray,r,t)}this.compilePrivateDicts([e.topDict],[s],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const a=CFFCompiler.EncodeFloatRegExp.exec(t);if(a){const r=parseFloat("1e"+((a[2]?+a[2]:0)+a[1].length));t=(Math.round(e*r)/r).toString()}let r,i,n="";for(r=0,i=t.length;r=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const a of e){const e=Math.min(a.length,127);let r=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");r[t]=e}r=r.join("");""===r&&(r="Bad_Font_Name");t.add(stringToBytes(r))}return this.compileIndex(t)}compileTopDicts(e,t,a){const r=[];let i=new CFFIndex;for(const n of e){if(a){n.removeByName("CIDFontVersion");n.removeByName("CIDFontRevision");n.removeByName("CIDFontType");n.removeByName("CIDCount");n.removeByName("UIDBase")}const e=new CFFOffsetTracker,s=this.compileDict(n,e);r.push(e);i.add(s);e.offset(t)}i=this.compileIndex(i,r);return{trackers:r,output:i}}compilePrivateDicts(e,t,a){for(let r=0,i=e.length;r>8&255,255&n]);else{i=new Uint8Array(1+2*n);i[0]=0;let t=0;const r=e.charset.length;let s=!1;for(let n=1;n>8&255;i[n+1]=255&o}}return this.compileTypedArray(i)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let a,r;switch(t){case 0:a=new Uint8Array(1+e.fdSelect.length);a[0]=t;for(r=0;r>8&255,255&i,n];for(r=1;r>8&255,255&r,t);n=t}}const o=(s.length-3)/3;s[1]=o>>8&255;s[2]=255&o;s.push(r>>8&255,255&r);a=new Uint8Array(s)}return this.compileTypedArray(a)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const a=e.objects,r=a.length;if(0===r)return[0,0];const i=[r>>8&255,255&r];let n,s,o=1;for(n=0;n>8&255,255&c):3===s?i.push(c>>16&255,c>>8&255,255&c):i.push(c>>>24&255,c>>16&255,c>>8&255,255&c);a[n]&&(c+=a[n].length)}for(n=0;n=5&&t<=7))return-1;r=e.substring(1)}if(r===r.toUpperCase()){a=parseInt(r,16);if(a>=0)return a}}return-1}const Ar=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const a=Ar[t];for(let r=0,i=a.length;r=a[r]&&e<=a[r+1])return t}for(let t=0,a=Ar.length;t=a[r]&&e<=a[r+1])return t}return-1}const Cr=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),vr=new Map;const Fr=!0,Ir=1,Or=2,Tr=4,Mr=32,Dr=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const a=getUnicodeForGlyph(e,t);if(-1!==a)for(const e in t)if(t[e]===a)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,a){const r=Object.create(null);let i,n,s;const o=!!(e.flags&Tr);if(e.isInternalFont){s=t;for(n=0;n=0?i:0}}else if(e.baseEncodingName){s=getEncoding(e.baseEncodingName);for(n=0;n=0?i:0}}else if(o)for(n in t)r[n]=t[n];else{s=lr;for(n=0;n=0?i:0}}const c=e.differences;let l;if(c)for(n in c){const e=c[n];i=a.indexOf(e);if(-1===i){l||(l=xr());const t=recoverGlyphName(e,l);t!==e&&(i=a.indexOf(t))}r[n]=i>=0?i:0}return r}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Rr=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),Nr=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Er=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Pr=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),Lr=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),jr=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),_r=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Ur=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Rr()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Rr()[t]||Er()[t]||Pr()[t]||Lr()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].charCodeAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const a in t)if(t[a]===e)return 0|a;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,a=this.lastChar;t<=a;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const a=new CFFParser(e,t,Fr);this.cff=a.parse();this.cff.duplicateFirstGlyph();const r=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=r.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:a,cMap:r}=t,i=e.charset.charset;let n,s;if(t.composite){let t,o;if(a?.length>0){t=Object.create(null);for(let e=0,r=a.length;e=0){const r=a[t];r&&(i[e]=r)}}i.length>0&&(this.properties.builtInEncoding=i)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let a=32768;t<1240?a=107:t<33900&&(a=1131);return a}function parseCmap(e,t,a){const r=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),i=getUint16(e,t+r);let n,s,o;if(4===i){getUint16(e,t+r+2);const a=getUint16(e,t+r+6)>>1;s=t+r+14;n=[];for(o=0;o>1;a0;)h.push({flags:n})}for(a=0;a>1;y=!0;break;case 4:s+=i.pop();moveTo(n,s);y=!0;break;case 5:for(;i.length>0;){n+=i.shift();s+=i.shift();lineTo(n,s)}break;case 6:for(;i.length>0;){n+=i.shift();lineTo(n,s);if(0===i.length)break;s+=i.shift();lineTo(n,s)}break;case 7:for(;i.length>0;){s+=i.shift();lineTo(n,s);if(0===i.length)break;n+=i.shift();lineTo(n,s)}break;case 8:for(;i.length>0;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 10:m=i.pop();b=null;if(a.isCFFCIDFont){const e=a.fdSelect.getFDIndex(r);if(e>=0&&eMath.abs(s-t)?n+=i.shift():s+=i.shift();bezierCurveTo(l,u,h,d,n,s);break;default:throw new FormatError(`unknown operator: 12 ${w}`)}break;case 14:if(i.length>=4){const e=i.pop(),r=i.pop();s=i.pop();n=i.pop();t.push({cmd:"save"},{cmd:"translate",args:[n,s]});let o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[e]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId);t.push({cmd:"restore"});o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[r]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId)}return;case 19:case 20:o+=i.length>>1;c+=o+7>>3;y=!0;break;case 21:s+=i.pop();n+=i.pop();moveTo(n,s);y=!0;break;case 22:n+=i.pop();moveTo(n,s);y=!0;break;case 24:for(;i.length>2;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}n+=i.shift();s+=i.shift();lineTo(n,s);break;case 25:for(;i.length>6;){n+=i.shift();s+=i.shift();lineTo(n,s)}l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s);break;case 26:i.length%2&&(n+=i.shift());for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h;s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 27:i.length%2&&(s+=i.shift());for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d;bezierCurveTo(l,u,h,d,n,s)}break;case 28:i.push((e[c]<<24|e[c+1]<<16)>>16);c+=2;break;case 29:m=i.pop()+a.gsubrsBias;b=a.gsubrs[m];b&&parse(b);break;case 30:for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;case 31:for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;default:if(w<32)throw new FormatError(`unknown operator: ${w}`);if(w<247)i.push(w-139);else if(w<251)i.push(256*(w-247)+e[c++]+108);else if(w<255)i.push(256*-(w-251)-e[c++]-108);else{i.push((e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3])/65536);c+=4}}y&&(i.length=0)}}(e)}const Xr=[];class CompiledFont{constructor(e){this.constructor===CompiledFont&&unreachable("Cannot initialize CompiledFont.");this.fontMatrix=e;this.compiledGlyphs=Object.create(null);this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(e){const{charCode:t,glyphId:a}=lookupCmap(this.cmap,e);let r=this.compiledGlyphs[a];if(!r)try{r=this.compileGlyph(this.glyphs[a],a);this.compiledGlyphs[a]=r}catch(e){this.compiledGlyphs[a]=Xr;void 0===this.compiledCharCodeToGlyphId[t]&&(this.compiledCharCodeToGlyphId[t]=a);throw e}void 0===this.compiledCharCodeToGlyphId[t]&&(this.compiledCharCodeToGlyphId[t]=a);return r}compileGlyph(e,t){if(!e||0===e.length||14===e[0])return Xr;let a=this.fontMatrix;if(this.isCFFCIDFont){const e=this.fdSelect.getFDIndex(t);if(e>=0&&e2*getUint16(e,t)}const n=[];let s=i(t,0);for(let a=r;ae+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),a=e>131070,r=a?4:2,i=new DataView(new ArrayBuffer((this.glyphs.length+1)*r));a?i.setUint32(0,0):i.setUint16(0,0);let n=0,s=0;for(const e of this.glyphs){n+=e.write(n,t);n=n+3&-4;s+=r;a?i.setUint32(s,n):i.setUint16(s,n>>1)}return{isLocationLong:a,loca:new Uint8Array(i.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,a=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const a=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const a of this.composites)e+=a.write(e,t);return e-a}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const a of this.composites)a.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:a,xMax:r,yMax:i}){this.numberOfContours=e;this.xMin=t;this.yMin=a;this.xMax=r;this.yMax=i}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:a}){this.xCoordinates=t;this.yCoordinates=a;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,a){const r=[];for(let i=0;i255?e+=2:o>0&&(e+=1);t=n;o=Math.abs(s-a);o>255?e+=2:o>0&&(e+=1);a=s}}return e}write(e,t){const a=e,r=[],i=[],n=[];let s=0,o=0;for(const a of this.contours){for(let e=0,t=a.xCoordinates.length;e=0?18:2;r.push(e)}else r.push(l)}s=c;const h=a.yCoordinates[e];l=h-o;if(0===l){t|=32;i.push(0)}else{const e=Math.abs(l);if(e<=255){t|=l>=0?36:4;i.push(e)}else i.push(l)}o=h;n.push(t)}t.setUint16(e,r.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const a of n)t.setUint8(e++,a);for(let a=0,i=r.length;a=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const a=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-a}scale(e,t){}}function writeInt16(e,t,a){e[t]=a>>8&255;e[t+1]=255&a}function writeInt32(e,t,a){e[t]=a>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}function writeData(e,t,a){if(a instanceof Uint8Array)e.set(a,t);else if("string"==typeof a)for(let r=0,i=a.length;ra;){a<<=1;r++}const i=a*t;return{range:i,entry:r,rangeShift:t*e-i}}toArray(){let e=this.sfnt;const t=this.tables,a=Object.keys(t);a.sort();const r=a.length;let i,n,s,o,c,l=12+16*r;const h=[l];for(i=0;i>>0;h.push(l)}const u=new Uint8Array(l);for(i=0;i>>0}writeInt32(u,l+4,e);writeInt32(u,l+8,h[i]);writeInt32(u,l+12,t[c].length);l+=16}return u}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const zr=[4],Wr=[5],$r=[6],Gr=[7],Vr=[8],Kr=[12,35],Jr=[14],Yr=[21],Zr=[22],Qr=[30],ei=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,a){const r=e.length;let i,n,s,o=!1;for(let c=0;cr)return!0;const i=r-e;for(let e=i;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);a?this.stack.splice(i,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,a){if(a>=e.length)return new Uint8Array(0);let r,i,n=0|t;for(r=0;r>8;n=52845*(t+n)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,a){if(t){const t=e.getBytes(),a=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(a?decrypt(t,55665,4):function decryptAscii(e,t,a){let r=0|t;const i=e.length,n=new Uint8Array(i>>>1);let s,o;for(s=0,o=0;s>8;r=52845*(e+r)+22719&65535}}return n.slice(a,o)}(t,55665,4))}this.seacAnalysisEnabled=!!a;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let a="";do{a+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return a}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,a=[],r=[],i=Object.create(null);i.lenIV=4;const n={subrs:[],charstrings:[],properties:{privateData:i}};let s,o,c,l;for(;null!==(s=this.getToken());)if("/"===s){s=this.getToken();switch(s){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){s=this.getToken();if(null===s||"end"===s)break;if("/"!==s)continue;const e=this.getToken();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const a=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s?this.getToken():"/"===s&&this.prevChar();r.push({glyph:e,encoded:a})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const r=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s&&this.getToken();a[e]=r}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":n.properties.privateData[s]=this.readNumberArray();break;case"StdHW":case"StdVW":n.properties.privateData[s]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":n.properties.privateData[s]=this.readNumber();break;case"ExpansionFactor":n.properties.privateData[s]=this.readNumber()||.06;break;case"ForceBold":n.properties.privateData[s]=this.readBoolean()}}for(const{encoded:t,glyph:i}of r){const r=new Type1CharString,s=r.convert(t,a,this.seacAnalysisEnabled);let o=r.output;s&&(o=[14]);const c={glyphName:i,charstring:o,width:r.width,lsb:r.lsb,seac:r.seac};".notdef"===i?n.charstrings.unshift(c):n.charstrings.push(c);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(i);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=r.width)}}return n}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const a=this.readNumberArray();e.fontMatrix=a;break;case"Encoding":const r=this.getToken();let i;if(/^\d+$/.test(r)){i=[];const e=0|parseInt(r,10);this.getToken();for(let a=0;a=i){s+=a;for(;s=0&&(r[e]=i)}}return type1FontGlyphMapping(e,r,a)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let a=0,r=e.length;a0;e--)t[e]-=t[e-1];f.setByName(e,t)}n.topDict.privateDict=f;const p=new CFFIndex;for(h=0,u=r.length;h0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,a,r,i,n,s,o,c){this.originalCharCode=e;this.fontChar=t;this.unicode=a;this.accent=r;this.width=i;this.vmetric=n;this.operatorListId=s;this.isSpace=o;this.isInFont=c}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=vr.get(e);if(t)return t;const a=e.match(Cr),r={isWhitespace:!!a?.[1],isZeroWidthDiacritic:!!a?.[2],isInvisibleFormatMark:!!a?.[3]};vr.set(e,r);return r}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,a){e[t+1]=a;e[t]=a>>>8}function signedInt16(e,t){const a=(e<<8)+t;return 32768&a?a-65536:a}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:a,composite:r}){let i,n;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))i=r?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))i=r?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))i=r?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(r){i="CIDFontType0";n="CIDFontType0C"}else{i="MMType1"===t?"MMType1":"Type1";n="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");i=t;n=a}return[i,n]}function applyStandardFontGlyphMap(e,t){for(const a in t)e[+a]=t[a]}function buildToFontChar(e,t,a){const r=[];let i;for(let a=0,n=e.length;ah){c++;if(c>=ti.length){warn("Ran out of space in font private use area.");break}l=ti[c][0];h=ti[c][1]}const g=l++;0===f&&(f=a);let p=r.get(d);"string"==typeof p&&(p=p.codePointAt(0));if(p&&!(u=p,ti[0][0]<=u&&u<=ti[0][1]||ti[1][0]<=u&&u<=ti[1][1])&&!o.has(f)){n.set(p,f);o.add(f)}i[g]=f;s[d]=g}var u;return{toFontChar:s,charCodeToGlyphId:i,toUnicodeExtraMap:n,nextAvailableFontCharCode:l}}function createCmapTable(e,t,a){const r=function getRanges(e,t,a){const r=[];for(const t in e)e[t]>=a||r.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,i]of t)i>=a||r.push({fontCharCode:e,glyphId:i});0===r.length&&r.push({fontCharCode:0,glyphId:0});r.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const i=[],n=r.length;for(let e=0;e65535?2:1;let n,s,o,c,l="\0\0"+string16(i)+"\0\0"+string32(4+8*i);for(n=r.length-1;n>=0&&!(r[n][0]<=65535);--n);const h=n+1;r[n][0]<65535&&65535===r[n][1]&&(r[n][1]=65534);const u=r[n][1]<65535?1:0,d=h+u,f=OpenTypeFileBuilder.getSearchParams(d,2);let g,p,m,b,y="",w="",x="",S="",k="",C=0;for(n=0,s=h;n0){w+="ÿÿ";y+="ÿÿ";x+="\0";S+="\0\0"}const v="\0\0"+string16(2*d)+string16(f.range)+string16(f.entry)+string16(f.rangeShift)+w+"\0\0"+y+x+S+k;let F="",O="";if(i>1){l+="\0\0\n"+string32(4+8*i+4+v.length);F="";for(n=0,s=r.length;ne||!c)&&(c=e);l 123 are reserved for internal usage");o|=1<65535&&(l=65535)}else{c=0;l=255}const u=e.bbox||[0,0,0,0],d=a.unitsPerEm||1/(e.fontMatrix||r)[0],f=e.ascentScaled?1:d/ai,g=a.ascent||Math.round(f*(e.ascent||u[3]));let p=a.descent||Math.round(f*(e.descent||u[1]));p>0&&e.descent>0&&u[1]<0&&(p=-p);const m=a.yMax||g,b=-a.yMin||-p;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(i)+string32(n)+string32(s)+string32(o)+"*21*"+string16(e.italicAngle?1:0)+string16(c||e.firstChar)+string16(l||e.lastChar)+string16(g)+string16(p)+"\0d"+string16(m)+string16(b)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(c||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const a=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],r=[];let i,n,s,o,c;for(i=0,n=a.length;i0;if((s||o)&&"CIDFontType2"===a&&this.cidEncoding.startsWith("Identity-")){const a=e.cidToGidMap,r=[];applyStandardFontGlyphMap(r,jr());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(r,_r()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(r,Ur());if(a){for(const e in r){const t=r[e];void 0!==a[t]&&(r[+e]=a[t])}a.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const i=r[e];void 0===a[i]&&(r[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){r[+e]=t}));this.toFontChar=r;this.toUnicode=new ToUnicodeMap(r)}else if(/Symbol/i.test(r))this.toFontChar=buildToFontChar(ur,xr(),this.differences);else if(/Dingbats/i.test(r))this.toFontChar=buildToFontChar(dr,Sr(),this.differences);else if(s){const e=buildToFontChar(this.defaultEncoding,xr(),this.differences);"CIDFontType2"!==a||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,a){e[+t]=a}));this.toFontChar=e}else{const e=xr(),a=[];this.toUnicode.forEach(((t,r)=>{if(!this.composite){const a=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==a&&(r=a)}a[+t]=r}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(a,jr());this.toFontChar=a}amendFallbackToUnicode(e);this.loadedName=r.split("-",1)[0]}checkAndRepair(e,t,a){const r=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const a=Object.create(null);a["OS/2"]=null;a.cmap=null;a.head=null;a.hhea=null;a.hmtx=null;a.maxp=null;a.name=null;a.post=null;for(let i=0;i>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0,n=e.pos;e.pos=e.start||0;e.skip(r);const s=e.getBytes(i);e.pos=n;if("head"===t){s[8]=s[9]=s[10]=s[11]=0;s[17]|=32}return{tag:t,checksum:a,length:i,offset:r,data:s}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,a,r,i,n){const s={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||a>e.length||a-t<=12)return s;const o=e.subarray(t,a),c=signedInt16(o[2],o[3]),l=signedInt16(o[4],o[5]),h=signedInt16(o[6],o[7]),u=signedInt16(o[8],o[9]);if(c>h){writeSignedInt16(o,2,h);writeSignedInt16(o,6,c)}if(l>u){writeSignedInt16(o,4,u);writeSignedInt16(o,8,l)}const d=signedInt16(o[0],o[1]);if(d<0){if(d<-1)return s;r.set(o,i);s.length=o.length;return s}let f,g=10,p=0;for(f=0;fo.length)return s;if(!n&&b>0){r.set(o.subarray(0,m),i);r.set([0,0],i+m);r.set(o.subarray(y,x),i+m+2);x-=b;o.length-x>3&&(x=x+3&-4);s.length=x;return s}if(o.length-x>3){x=x+3&-4;r.set(o.subarray(0,x),i);s.length=x;return s}r.set(o,i);s.length=o.length;return s}function readNameTable(e){const a=(t.start||0)+e.offset;t.pos=a;const r=[[],[]],i=[],n=e.length,s=a+n;if(0!==t.getUint16()||n<6)return[r,i];const o=t.getUint16(),c=t.getUint16();let l,h;for(l=0;ls)continue;t.pos=n;const o=e.name;if(e.encoding){let a="";for(let r=0,i=e.length;r0&&(l+=e-1)}}else{if(m||y){warn("TT: nested FDEFs not allowed");p=!0}m=!0;u=l;s=d.pop();t.functionsDefined[s]={data:c,i:l}}else if(!m&&!y){s=d.at(-1);if(isNaN(s))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[s]=!0;if(s in t.functionsStackDeltas){const e=d.length+t.functionsStackDeltas[s];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}d.length=e}else if(s in t.functionsDefined&&!g.includes(s)){f.push({data:c,i:l,stackTop:d.length-1});g.push(s);o=t.functionsDefined[s];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}c=o.data;l=o.i}}}if(!m&&!y){let t=0;e<=142?t=i[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){r=d.pop();isNaN(r)||(t=2*-r)}for(;t<0&&d.length>0;){d.pop();t++}for(;t>0;){d.push(NaN);t--}}}t.tooComplexToFollowFunctions=p;const w=[c];l>c.length&&w.push(new Uint8Array(l-c.length));if(u>h){warn("TT: complementing a missing function tail");w.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let a,r,i=0;for(a=0,r=t.length;a>>0,n=[];for(let t=0;t>>0);const s={ttcTag:t,majorVersion:a,minorVersion:r,numFonts:i,offsetTable:n};switch(a){case 1:return s;case 2:s.dsigTag=e.getInt32()>>>0;s.dsigLength=e.getInt32()>>>0;s.dsigOffset=e.getInt32()>>>0;return s}throw new FormatError(`Invalid TrueType Collection majorVersion: ${a}.`)}(e),i=t.split("+");let n;for(let s=0;s0||!(a.cMap instanceof IdentityCMap));if("OTTO"===n.version&&!t||!s.head||!s.hhea||!s.maxp||!s.post){c=new Stream(s["CFF "].data);o=new CFFFont(c,a);adjustWidths(a);return this.convert(e,o,a)}delete s.glyf;delete s.loca;delete s.fpgm;delete s.prep;delete s["cvt "];this.isOpenType=!0}if(!s.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+s.maxp.offset;let h=t.getInt32();const u=t.getUint16();if(65536!==h&&20480!==h){if(6===s.maxp.length)h=20480;else{if(!(s.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');h=65536}!function writeUint32(e,t,a){e[t+3]=255&a;e[t+2]=a>>>8;e[t+1]=a>>>16;e[t]=a>>>24}(s.maxp.data,0,h)}if(a.scaleFactors?.length===u&&l){const{scaleFactors:e}=a,t=int16(s.head.data[50],s.head.data[51]),r=new GlyfTable({glyfTable:s.glyf.data,isGlyphLocationsLong:t,locaTable:s.loca.data,numGlyphs:u});r.scale(e);const{glyf:i,loca:n,isLocationLong:o}=r.write();s.glyf.data=i;s.loca.data=n;if(o!==!!t){s.head.data[50]=0;s.head.data[51]=o?1:0}const c=s.hmtx.data;for(let t=0;t>8&255;c[a+1]=255&r;writeSignedInt16(c,a+2,Math.round(e[t]*signedInt16(c[a+2],c[a+3])))}}let d=u+1,f=!0;if(d>65535){f=!1;d=u;warn("Not enough space in glyfs to duplicate first glyph.")}let g=0,p=0;if(h>=65536&&s.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){s.maxp.data[14]=0;s.maxp.data[15]=2}t.pos+=4;g=t.getUint16();t.pos+=4;p=t.getUint16()}s.maxp.data[4]=d>>8;s.maxp.data[5]=255&d;const m=function sanitizeTTPrograms(e,t,a,r){const i={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,i);t&&sanitizeTTProgram(t,i);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let a=0,r=e.functionsUsed.length;at){warn("TT: invalid function id: "+a);e.hintsValid=!1;return}if(e.functionsUsed[a]&&!e.functionsDefined[a]){warn("TT: undefined function: "+a);e.hintsValid=!1;return}}}(i,r);if(a&&1&a.length){const e=new Uint8Array(a.length+1);e.set(a.data);a.data=e}return i.hintsValid}(s.fpgm,s.prep,s["cvt "],g);if(!m){delete s.fpgm;delete s.prep;delete s["cvt "]}!function sanitizeMetrics(e,t,a,r,i,n){if(!t){a&&(a.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const s=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==s){if(!(2&int16(r.data[44],r.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>i){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${i}).`);o=i;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const c=i-o-(a.length-4*o>>1);if(c>0){const e=new Uint8Array(a.length+2*c);e.set(a.data);if(n){e[a.length]=a.data[2];e[a.length+1]=a.data[3]}a.data=e}}(t,s.hhea,s.hmtx,s.head,d,f);if(!s.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,a){const r=e.data,i=function int32(e,t,a,r){return(e<<24)+(t<<16)+(a<<8)+r}(r[0],r[1],r[2],r[3]);if(i>>16!=1){info("Attempting to fix invalid version in head table: "+i);r[0]=0;r[1]=1;r[2]=0;r[3]=0}const n=int16(r[50],r[51]);if(n<0||n>1){info("Attempting to fix invalid indexToLocFormat in head table: "+n);const e=t+1;if(a===e<<1){r[50]=0;r[51]=0}else{if(a!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+n);r[50]=0;r[51]=1}}}(s.head,u,l?s.loca.length:0);let b=Object.create(null);if(l){const e=int16(s.head.data[50],s.head.data[51]),t=function sanitizeGlyphLocations(e,t,a,r,i,n,s){let o,c,l;if(r){o=4;c=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};l=function fontItemEncodeLong(e,t,a){e[t]=a>>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}}else{o=2;c=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};l=function fontItemEncode(e,t,a){e[t]=a>>9&255;e[t+1]=a>>1&255}}const h=n?a+1:a,u=o*(1+h),d=new Uint8Array(u);d.set(e.data.subarray(0,u));e.data=d;const f=t.data,g=f.length,p=new Uint8Array(g);let m,b;const y=[];for(m=0,b=0;mg&&(e=g);y.push({index:m,offset:e,endOffset:0})}y.sort(((e,t)=>e.offset-t.offset));for(m=0;me.index-t.index));for(m=0;ms&&(s=e.sizeOfInstructions);S+=t;l(d,b,S)}if(0===S){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(m=0,b=o;ma+S)t.data=p.subarray(0,a+S);else{t.data=new Uint8Array(a+S);t.data.set(p.subarray(0,S))}t.data.set(p.subarray(0,a),S);l(e.data,d.length-o,S+a)}else t.data=p.subarray(0,S);return{missingGlyphs:x,maxSizeOfInstructions:s}}(s.loca,s.glyf,u,e,m,f,p);b=t.missingGlyphs;if(h>=65536&&s.maxp.length>=32){s.maxp.data[26]=t.maxSizeOfInstructions>>8;s.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!s.hhea)throw new FormatError('Required "hhea" table is not found');if(0===s.hhea.data[10]&&0===s.hhea.data[11]){s.hhea.data[10]=255;s.hhea.data[11]=255}const y={unitsPerEm:int16(s.head.data[18],s.head.data[19]),yMax:signedInt16(s.head.data[42],s.head.data[43]),yMin:signedInt16(s.head.data[38],s.head.data[39]),ascent:signedInt16(s.hhea.data[4],s.hhea.data[5]),descent:signedInt16(s.hhea.data[6],s.hhea.data[7]),lineGap:signedInt16(s.hhea.data[8],s.hhea.data[9])};this.ascent=y.ascent/y.unitsPerEm;this.descent=y.descent/y.unitsPerEm;this.lineGap=y.lineGap/y.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;s.post&&function readPostScriptTable(e,a,r){const i=(t.start||0)+e.offset;t.pos=i;const n=i+e.length,s=t.getInt32();t.skip(28);let o,c,l=!0;switch(s){case 65536:o=Dr;break;case 131072:const e=t.getUint16();if(e!==r){l=!1;break}const i=[];for(c=0;c=32768){l=!1;break}i.push(e)}if(!l)break;const h=[],u=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let i=-1;t?i=r:void 0!==e[r]&&(i=e[r]);i>=0&&i>>0;let h=!1;if(o?.platformId!==i||o?.encodingId!==n){if(0!==i||0!==n&&1!==n&&3!==n)if(1===i&&0===n)h=!0;else if(3!==i||1!==n||!r&&o){if(a&&3===i&&0===n){h=!0;let a=!0;if(e>3;e.push(r);a=Math.max(r,a)}const r=[];for(let e=0;e<=a;e++)r.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let a=0;a<256;a++)if(0===e[a]){t.pos=r[0].idRangePos+2*a;f=t.getUint16();u.push({charCode:a,glyphId:f})}else{const i=r[e[a]];for(d=0;d>1;t.skip(6);const a=[];let r;for(r=0;r>1)-(e-r);i.offsetIndex=s;o=Math.max(o,s+i.end-i.start+1)}else i.offsetIndex=-1}const c=[];for(d=0;d>>0;for(d=0;d>>0,a=t.getInt32()>>>0;let r=t.getInt32()>>>0;for(let t=e;t<=a;t++)u.push({charCode:t,glyphId:r++})}}}u.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);w[t]=e.glyphId}else for(const e of n)w[e.charCode]=e.glyphId;if(a.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!c&&void 0!==w[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const r=a.glyphNames.indexOf(t);r>0&&hasGlyph(r)&&(w[e]=r)}}0===w.length&&(w[0]=0);let x=d-1;f||(x=0);if(!a.cssFontInfo){const e=adjustMapping(w,hasGlyph,x,this.toUnicode);this.toFontChar=e.toFontChar;s.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,d)};s["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const a=t.getUint16();t.skip(60);const r=t.getUint16();if(a<4&&768&r)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(s["OS/2"],t)||(s["OS/2"]={tag:"OS/2",data:createOS2Table(a,e.charCodeToGlyphId,y)})}if(!l)try{c=new Stream(s["CFF "].data);o=new CFFParser(c,a,Fr).parse();o.duplicateFirstGlyph();const e=new CFFCompiler(o);s["CFF "].data=e.compile()}catch{warn("Failed to compile font "+a.loadedName)}if(s.name){const[t,r]=readNameTable(s.name);s.name.data=createNameTable(e,t);this.psName=t[0][6]||null;a.composite||function adjustTrueTypeToUnicode(e,t,a){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===a.length)return;if(e.defaultEncoding===hr)return;for(const e of a)if(!isWinNameRecord(e))return;const r=hr,i=[],n=xr();for(const e in r){const t=r[e];if(""===t)continue;const a=n[t];void 0!==a&&(i[e]=String.fromCharCode(a))}i.length>0&&e.toUnicode.amend(i)}(a,this.isSymbolicFont,r)}else s.name={tag:"name",data:createNameTable(this.name)};const S=new OpenTypeFileBuilder(n.version);for(const e in s)S.addTable(e,s[e].data);return S.toArray()}convert(e,t,a){a.fixedPitch=!1;a.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const a=[],r=xr();for(const i in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[i]))continue;const n=getUnicodeForGlyph(t[i],r);-1!==n&&(a[i]=String.fromCharCode(n))}a.length>0&&e.toUnicode.amend(a)}(a,a.builtInEncoding);let i=1;t instanceof CFFFont&&(i=t.numGlyphs-1);const n=t.getGlyphMapping(a);let s=null,o=n,c=null;if(!a.cssFontInfo){s=adjustMapping(n,t.hasGlyphId.bind(t),i,this.toUnicode);this.toFontChar=s.toFontChar;o=s.charCodeToGlyphId;c=s.toUnicodeExtraMap}const l=t.numGlyphs;function getCharCodes(e,t){let a=null;for(const r in e)t===e[r]&&(a||=[]).push(0|r);return a}function createCharCode(e,t){for(const a in e)if(t===e[a])return 0|a;s.charCodeToGlyphId[s.nextAvailableFontCharCode]=t;return s.nextAvailableFontCharCode++}const h=t.seacs;if(s&&h?.length){const e=a.fontMatrix||r,i=t.getCharset(),o=Object.create(null);for(let t in h){t|=0;const a=h[t],r=lr[a[2]],c=lr[a[3]],l=i.indexOf(r),u=i.indexOf(c);if(l<0||u<0)continue;const d={x:a[0]*e[0]+a[1]*e[2]+e[4],y:a[0]*e[1]+a[1]*e[3]+e[5]},f=getCharCodes(n,t);if(f)for(const e of f){const t=s.charCodeToGlyphId,a=createCharCode(t,l),r=createCharCode(t,u);o[e]={baseFontCharCode:a,accentFontCharCode:r,accentOffset:d}}}a.seacMap=o}const u=1/(a.fontMatrix||r)[0],d=new OpenTypeFileBuilder("OTTO");d.addTable("CFF ",t.data);d.addTable("OS/2",createOS2Table(a,o));d.addTable("cmap",createCmapTable(o,c,l));d.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(u)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(a.descent)+"ÿ"+safeString16(a.ascent)+string16(a.italicAngle?2:0)+"\0\0\0\0\0\0\0");d.addTable("hhea","\0\0\0"+safeString16(a.ascent)+safeString16(a.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(a.capHeight)+safeString16(Math.tan(a.italicAngle)*a.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(l));d.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,a=t.cff?t.cff.widths:null;let r="\0\0\0\0";for(let t=1,i=l;t=65520&&e<=65535?0:e>=62976&&e<=63743?kr()[e]||e:173===e?45:e}(a)}this.isType3Font&&(i=a);let h=null;if(this.seacMap?.[e]){l=!0;const t=this.seacMap[e];a=t.baseFontCharCode;h={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let u="";"number"==typeof a&&(a<=1114111?u=String.fromCodePoint(a):warn(`charToGlyph - invalid fontCharCode: ${a}`));n=new fonts_Glyph(e,u,c,h,r,o,i,t,l);return this._glyphCache[e]=n}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const a=Object.create(null),r=e.length;let i=0;for(;it.length%2==1,r=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let i=0,n=e.length;i55295&&(n<57344||n>65533)&&i++;if(this.toUnicode){const e=r(n);if(-1!==e){if(hasCurrentBufErrors()){t.push(a.join(""));a.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)a.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(a.join(""));a.length=0}a.push(String.fromCodePoint(n))}t.push(a.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const ni=2,si=3,oi=4,ci=5,li=6,hi=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,a,r,i){const n=e instanceof BaseStream?e.dict:e,s=n.get("ShadingType");try{switch(s){case ni:case si:return new RadialAxialShading(n,t,a,r,i);case oi:case ci:case li:case hi:return new MeshShading(e,t,a,r,i);default:throw new FormatError("Unsupported ShadingType: "+s)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;constructor(){this.constructor===BaseShading&&unreachable("Cannot initialize BaseShading.")}getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,a,r,i){super();this.coordsArr=e.getArray("Coords");this.shadingType=e.get("ShadingType");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:a,pdfFunctionFactory:r,localColorSpaceCache:i}),s=e.getArray("BBox");this.bbox=Array.isArray(s)&&4===s.length?Util.normalizeRect(s):null;let o=0,c=1;if(e.has("Domain")){const t=e.getArray("Domain");o=t[0];c=t[1]}let l=!1,h=!1;if(e.has("Extend")){const t=e.getArray("Extend");l=t[0];h=t[1]}if(!(this.shadingType!==si||l&&h)){const[e,t,a,r,i,n]=this.coordsArr,s=Math.hypot(e-r,t-i);a<=n+s&&n<=a+s&&warn("Unsupported radial gradient.")}this.extendStart=l;this.extendEnd=h;const u=e.getRaw("Function"),d=r.createFromArray(u),f=(c-o)/840,g=this.colorStops=[];if(o>=c||f<=0){info("Bad shading domain.");return}const p=new Float32Array(n.numComps),m=new Float32Array(1);let b,y=0;m[0]=o;d(m,0,p,0);let w=n.getRgb(p,0);const x=Util.makeHexColor(w[0],w[1],w[2]);g.push([0,x]);let S=1;m[0]=o+f;d(m,0,p,0);let k=n.getRgb(p,0),C=k[0]-w[0]+1,v=k[1]-w[1]+1,F=k[2]-w[2]+1,O=k[0]-w[0]-1,T=k[1]-w[1]-1,M=k[2]-w[2]-1;for(let e=2;e<840;e++){m[0]=o+e*f;d(m,0,p,0);b=n.getRgb(p,0);const t=e-y;C=Math.min(C,(b[0]-w[0]+1)/t);v=Math.min(v,(b[1]-w[1]+1)/t);F=Math.min(F,(b[2]-w[2]+1)/t);O=Math.max(O,(b[0]-w[0]-1)/t);T=Math.max(T,(b[1]-w[1]-1)/t);M=Math.max(M,(b[2]-w[2]-1)/t);if(!(O<=C&&T<=v&&M<=F)){const e=Util.makeHexColor(k[0],k[1],k[2]);g.push([S/840,e]);C=b[0]-k[0]+1;v=b[1]-k[1]+1;F=b[2]-k[2]+1;O=b[0]-k[0]-1;T=b[1]-k[1]-1;M=b[2]-k[2]-1;y=S;w=k}S=e;k=b}const D=Util.makeHexColor(k[0],k[1],k[2]);g.push([1,D]);let R="transparent";if(e.has("Background")){b=n.getRgb(e.get("Background"),0);R=Util.makeHexColor(b[0],b[1],b[2])}if(!l){g.unshift([0,R]);g[1][0]+=BaseShading.SMALL_NUMBER}if(!h){g.at(-1)[0]-=BaseShading.SMALL_NUMBER;g.push([1,R])}this.colorStops=g}getIR(){const e=this.coordsArr,t=this.shadingType;let a,r,i,n,s;if(t===ni){r=[e[0],e[1]];i=[e[2],e[3]];n=null;s=null;a="axial"}else if(t===si){r=[e[0],e[1]];i=[e[3],e[4]];n=e[2];s=e[5];a="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",a,this.bbox,this.colorStops,r,i,n,s]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const a=t.numComps;this.tmpCompsBuf=new Float32Array(a);const r=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(r):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,a=this.bufferLength;if(32===e){if(0===a)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>a)>>>0}if(8===e&&0===a)return this.stream.getByte();for(;a>a}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),a=this.readBits(e),r=this.context.decode,i=e<32?1/((1<n?n:e;t=t>s?s:t;a=ae*i[t])):a;let s,o=-2;const c=[];for(const[e,t]of r.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===o+1){s.push(n[t]);o+=1}else{o=e;s=[n[t]];c.push(e,s)}return c}(e),a=new Dict(null);a.set("BaseFont",Name.get(e));a.set("Type",Name.get("Font"));a.set("Subtype",Name.get("CIDFontType2"));a.set("Encoding",Name.get("Identity-H"));a.set("CIDToGIDMap",Name.get("Identity"));a.set("W",t);a.set("FirstChar",t[0]);a.set("LastChar",t.at(-2)+t.at(-1).length-1);const r=new Dict(null);a.set("FontDescriptor",r);const i=new Dict(null);i.set("Ordering","Identity");i.set("Registry","Adobe");i.set("Supplement",0);a.set("CIDSystemInfo",i);return a}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(tn.LBRACE);this.parseBlock();this.expect(tn.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(tn.NUMBER))this.operators.push(this.prev.value);else if(this.accept(tn.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(tn.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(tn.RBRACE);if(this.accept(tn.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(tn.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const a=this.operators.length;this.parseBlock();this.expect(tn.RBRACE);this.expect(tn.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=a;this.operators[e+1]="jz"}}}}const tn={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(tn.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(tn.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(tn.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(tn.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(tn.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return da;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(tn.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const a=this.strBuf;a.length=0;a[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)a.push(String.fromCharCode(t));const r=a.join("");switch(r.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(r)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const a=parseFloat(t.join(""));if(isNaN(a))throw new FormatError(`Invalid floating point number: ${a}`);return a}}class BaseLocalCache{constructor(e){this.constructor===BaseLocalCache&&unreachable("Cannot initialize BaseLocalCache.");this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,a){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,a){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get _byteSize(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get _cacheLimitReached(){return!(this._imageCache.size>c)*h;l&=(1<a?e=a:e0&&(d=n[u-1]);let f=r[1];u>1,l=i.length>>1,h=new PostScriptEvaluator(o),u=Object.create(null);let d=8192;const f=new Float32Array(l);return function constructPostScriptFn(e,t,a,r){let i,s,o="";const g=f;for(i=0;ie&&(s=e)}m[i]=s}if(d>0){d--;u[o]=m}a.set(m,r)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let a=t.length-e,r=e-1;r>=0;r--,a++)t.push(t[a])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const a=this.stack,r=a.length-e,i=a.length-1,n=r+(t-Math.floor(t/e)*e);for(let e=r,t=i;e0?t.push(s<>o);break;case"ceiling":s=t.pop();t.push(Math.ceil(s));break;case"copy":s=t.pop();t.copy(s);break;case"cos":s=t.pop();t.push(Math.cos(s%360/180*Math.PI));break;case"cvi":s=0|t.pop();t.push(s);break;case"cvr":break;case"div":o=t.pop();s=t.pop();t.push(s/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();s=t.pop();t.push(s===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();s=t.pop();t.push(s**o);break;case"false":t.push(!1);break;case"floor":s=t.pop();t.push(Math.floor(s));break;case"ge":o=t.pop();s=t.pop();t.push(s>=o);break;case"gt":o=t.pop();s=t.pop();t.push(s>o);break;case"idiv":o=t.pop();s=t.pop();t.push(s/o|0);break;case"index":s=t.pop();t.index(s);break;case"le":o=t.pop();s=t.pop();t.push(s<=o);break;case"ln":s=t.pop();t.push(Math.log(s));break;case"log":s=t.pop();t.push(Math.log10(s));break;case"lt":o=t.pop();s=t.pop();t.push(s=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,a){const r=[],i=[],n=t.length>>1,s=a.length>>1;let o,c,l,h,u,d,f,g,p=0;for(let e=0;et.min){o.unshift("Math.max(",n,", ");o.push(")")}if(s4){r=!0;t=0}else{r=!1;t=1}const c=[];for(n=0;n=0&&"ET"===sn[e];--e)sn[e]="EN";for(let e=n+1;e0&&(t=sn[n-1]);let a=u;e+1g&&isOdd(g)&&(m=g)}for(g=p;g>=m;--g){let e=-1;for(n=0,s=c.length;n=0){reverseValues(nn,e,n);e=-1}}else e<0&&(e=n);e>=0&&reverseValues(nn,e,c.length)}for(n=0,s=nn.length;n"!==e||(nn[n]="")}return createBidiText(nn.join(""),r)}const on={style:"normal",weight:"normal"},cn={style:"normal",weight:"bold"},ln={style:"italic",weight:"normal"},hn={style:"italic",weight:"bold"},un=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:on,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:cn,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:ln,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:hn,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:on,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:cn,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:ln,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:hn,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:on,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:cn,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:ln,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:hn,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:on,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:cn,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:ln,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:hn,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:on,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:cn,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:ln,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:hn,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:on}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),dn=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:a,fallback:r,style:i,ultimate:n},s,o,c=!0,l=!0,h=""){const u={style:null,ultimate:null};if(t){const e=h?` ${h}`:"";for(const a of t)s.push(`local(${a}${e})`)}if(e){const t=un.get(e),n=h||function getStyleToAppend(e){switch(e){case cn:return"Bold";case ln:return"Italic";case hn:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(i);Object.assign(u,generateFont(t,s,o,c&&!r,l&&!a,n))}i&&(u.style=i);n&&(u.ultimate=n);if(c&&r){const e=un.get(r),{ultimate:t}=generateFont(e,s,o,c,l&&!a,h);u.ultimate||=t}l&&a&&o&&s.push(`url(${o}${a})`);return u}function getFontSubstitution(e,t,a,r,i){if(r.startsWith("InvalidPDFjsFont_"))return null;const n=r=normalizeFontName(r);let s=e.get(n);if(s)return s;let o=un.get(r);if(!o)for(const[e,t]of dn)if(r.startsWith(e)){r=`${t}${r.substring(e.length)}`;o=un.get(r);break}let c=!1;if(!o){o=un.get(i);c=!0}const l=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(r)){e.set(n,null);return null}const t=/bold/gi.test(r),a=/oblique|italic/gi.test(r),i=t&&a&&hn||t&&cn||a&&ln||on;s={css:`"${getFamilyName(r)}",${l}`,guessFallback:!0,loadedName:l,baseFontName:r,src:`local(${r})`,style:i};e.set(n,s);return s}const h=[];c&&validateFontName(r)&&h.push(`local(${r})`);const{style:u,ultimate:d}=generateFont(o,h,a),f=null===d,g=f?"":`,${d}`;s={css:`"${getFamilyName(r)}",${l}${g}`,guessFallback:f,loadedName:l,baseFontName:r,src:h.join(","),style:u};e.set(n,s);return s}class ImageResizer{constructor(e,t){this._imgData=e;this._isMask=t}static needsToBeResized(e,t){if(e<=this._goodSquareLength&&t<=this._goodSquareLength)return!1;const{MAX_DIM:a}=this;if(e>a||t>a)return!0;const r=e*t;if(this._hasMaxArea)return r>this.MAX_AREA;if(r(this.MAX_AREA=this._goodSquareLength**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(ImageResizer._goodSquareLength,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setMaxArea(e){this._hasMaxArea||(this.MAX_AREA=e>>2)}static _areGoodDims(e,t){try{const a=new OffscreenCanvas(e,t),r=a.getContext("2d");r.fillRect(0,0,1,1);const i=r.getImageData(0,0,1,1).data[3];a.width=a.height=1;return 0!==i}catch{return!1}}static _guessMax(e,t,a,r){for(;e+a+1>3,s=a+3&-4;if(a!==s){const e=new Uint8Array(s*t);let r=0;for(let n=0,o=t*a;n>>8;t[a++]=255&i}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();a=t.byteLength}const r=a>>2,i=a-4*r,n=new Uint32Array(t.buffer,0,r);let s=0,o=0,c=this.h1,l=this.h2;const h=3432918353,u=461845907,d=11601,f=13715;for(let e=0;e>>17;s=s*u&gn|s*f&pn;c^=s;c=c<<13|c>>>19;c=5*c+3864292196}else{o=n[e];o=o*h&gn|o*d&pn;o=o<<15|o>>>17;o=o*u&gn|o*f&pn;l^=o;l=l<<13|l>>>19;l=5*l+3864292196}s=0;switch(i){case 3:s^=t[4*r+2]<<16;case 2:s^=t[4*r+1]<<8;case 1:s^=t[4*r];s=s*h&gn|s*d&pn;s=s<<15|s>>>17;s=s*u&gn|s*f&pn;1&r?c^=s:l^=s}this.h1=c;this.h2=l}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&gn|36045*e&pn;t=4283543511*t&gn|(2950163797*(t<<16|e>>>16)&gn)>>>16;e^=t>>>1;e=444984403*e&gn|60499*e&pn;t=3301882366*t&gn|(3120437893*(t<<16|e>>>16)&gn)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,a,r,i){let n=e;for(let e=0,a=t.length-1;e1e3){l=Math.max(l,d);f+=u+2;d=0;u=0}h.push({transform:t,x:d,y:f,w:a.width,h:a.height});d+=a.width+2;u=Math.max(u,a.height)}const g=Math.max(l,d)+1,p=f+u+1,m=new Uint8Array(g*p*4),b=g<<2;for(let e=0;e=0;){t[n-4]=t[n];t[n-3]=t[n+1];t[n-2]=t[n+2];t[n-1]=t[n+3];t[n+a]=t[n+a-4];t[n+a+1]=t[n+a-3];t[n+a+2]=t[n+a-2];t[n+a+3]=t[n+a-1];n-=b}}const y={width:g,height:p};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(g,p);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(m.buffer),g,p),0,0);y.bitmap=e.transferToImageBitmap();y.data=null}else{y.kind=v;y.data=m}a.splice(n,4*c,Zt);r.splice(n,4*c,[y,h]);return n+1}));addState(mn,[Be,Ne,Vt,Re],null,(function iterateImageMaskGroup(e,t){const a=e.fnArray,r=(t-(e.iCurr-3))%4;switch(r){case 0:return a[t]===Be;case 1:return a[t]===Ne;case 2:return a[t]===Vt;case 3:return a[t]===Re}throw new Error(`iterateImageMaskGroup - invalid pos: ${r}`)}),(function foundImageMaskGroup(e,t){const a=e.fnArray,r=e.argsArray,i=e.iCurr,n=i-3,s=i-2,o=i-1;let c=Math.floor((t-n)/4);if(c<10)return t-(t-n)%4;let l,h,u=!1;const d=r[o][0],f=r[s][0],g=r[s][1],p=r[s][2],m=r[s][3];if(g===p){u=!0;l=s+4;let e=o+4;for(let t=1;t=4&&a[n-4]===a[s]&&a[n-3]===a[o]&&a[n-2]===a[c]&&a[n-1]===a[l]&&r[n-4][0]===h&&r[n-4][1]===u){d++;f-=5}let g=f+4;for(let e=1;e=a)break}r=(r||mn)[e[t]];if(r&&!Array.isArray(r)){n.iCurr=t;t++;if(!r.checkFn||(0,r.checkFn)(n)){i=r;r=null}else r=null}else t++}this.state=r;this.match=i;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&f?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===Re||e===et))&&this.flush()}addImageOps(e,t,a){void 0!==a&&this.addOp(jt,["OC",a]);this.addOp(e,t);void 0!==a&&this.addOp(_t,[])}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(Ae,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,a=e.length;tr&&(e=r);return e}function resizeImageMask(e,t,a,r,i,n){const s=i*n;let o;o=t<=8?new Uint8Array(s):t<=16?new Uint16Array(s):new Uint32Array(s);const c=a/i,l=r/n;let h,u,d,f,g=0;const p=new Uint16Array(i),m=a;for(h=0;h0&&Number.isInteger(a.height)&&a.height>0&&(a.width!==d||a.height!==f)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");d=a.width;f=a.height}if(d<1||f<1)throw new FormatError(`Invalid image width: ${d} or height: ${f}`);this.width=d;this.height=f;this.interpolate=l.get("I","Interpolate");this.imageMask=l.get("IM","ImageMask")||!1;this.matte=l.get("Matte")||!1;let g=a.bitsPerComponent;if(!g){g=l.get("BPC","BitsPerComponent");if(!g){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);g=1}}this.bpc=g;if(!this.imageMask){let i=l.getRaw("CS")||l.getRaw("ColorSpace");if(!i){info("JPX images (which do not require color spaces)");switch(a.numComps){case 1:i=Name.get("DeviceGray");break;case 3:i=Name.get("DeviceRGB");break;case 4:i=Name.get("DeviceCMYK");break;default:throw new Error(`JPX images with ${a.numComps} color components not supported.`)}}this.colorSpace=ColorSpace.parse({cs:i,xref:e,resources:r?t:null,pdfFunctionFactory:o,localColorSpaceCache:c});this.numComps=this.colorSpace.numComps}this.decode=l.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,g)||s&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*a,o=e.byteLength;let c,l;if(!r||i&&!(s===o))if(i){c=new Uint8Array(s);c.set(e);c.fill(255,o)}else c=new Uint8Array(e);else c=e;if(i)for(l=0;l>7&1;s[d+1]=u>>6&1;s[d+2]=u>>5&1;s[d+3]=u>>4&1;s[d+4]=u>>3&1;s[d+5]=u>>2&1;s[d+6]=u>>1&1;s[d+7]=1&u;d+=8}if(d>=1}}}}else{let a=0;u=0;for(d=0,h=n;d>r;i<0?i=0:i>l&&(i=l);s[d]=i;u&=(1<s[r+1]){t=255;break}}o[h]=t}}}if(o)for(h=0,d=3,u=t*r;h>3,h=t&&ImageResizer.needsToBeResized(a,r);if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===c?e=k:"DeviceRGB"!==this.colorSpace.name||8!==c||this.needsDecode||(e=C);if(e&&!this.smask&&!this.mask&&a===s&&r===o){const n=this.getImageBytes(o*l,{});if(t)return h?ImageResizer.createImage({data:n,kind:e,width:a,height:r,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,s,o,n);i.kind=e;i.data=n;if(this.needsDecode){assert(e===k,"PDFImage.createImageData: The image must be grayscale.");const t=i.data;for(let e=0,a=t.length;e>3,s=this.getImageBytes(r*n,{internal:!0}),o=this.getComponents(s);let c,l;if(1===i){l=a*r;if(this.needsDecode)for(c=0;c0&&e.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedu){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let d;o.has("OC")&&(d=await this.parseMarkedContentProps(o.get("OC"),e));let f,g;if(o.get("IM","ImageMask")||!1){const e=o.get("I","Interpolate"),a=l+7>>3,s=t.getBytes(a*h),u=o.getArray("D","Decode");if(this.parsingType3Font){f=PDFImage.createRawMask({imgArray:s,width:l,height:h,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:u?.[0]>0,interpolate:e});f.cached=!!i;g=[f];r.addImageOps(Vt,g,d);if(i){const e={fn:Vt,args:g,optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}f=await PDFImage.createMask({imgArray:s,width:l,height:h,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:u?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(f.isSingleOpaquePixel){r.addImageOps(ta,[],d);if(i){const e={fn:ta,args:[],optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}const p=`mask_${this.idFactory.createObjId()}`;r.addDependency(p);f.dataLen=f.bitmap?f.width*f.height*4:f.data.length;this._sendImgData(p,f);g=[{data:p,width:f.width,height:f.height,interpolate:f.interpolate,count:1}];r.addImageOps(Vt,g,d);if(i){const e={fn:Vt,args:g,optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}if(a&&!o.has("SMask")&&!o.has("Mask")&&l+h<200){try{const i=new PDFImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:s});f=await i.createImageData(!0,!1);r.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;r.addImageOps(Yt,[f],d)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let p=`img_${this.idFactory.createObjId()}`,m=!1;if(this.parsingType3Font)p=`${this.idFactory.getDocId()}_type3_${p}`;else if(i&&c){m=this.globalImageCache.shouldCache(c,this.pageIndex);if(m){assert(!a,"Cannot cache an inline image globally.");p=`${this.idFactory.getDocId()}_${p}`}}r.addDependency(p);g=[p,l,h];r.addImageOps(Jt,g,d);if(m&&l*h>25e4){const e=await this.handler.sendWithPromise("commonobj",[p,"CopyLocalImage",{imageRef:c}]);if(e){this.globalImageCache.setData(c,{objId:p,fn:Jt,args:g,optionalContent:d,byteSize:0});this.globalImageCache.addByteSize(c,e);return}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:s}).then((async e=>{f=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);f.dataLen=f.bitmap?f.width*f.height*4:f.data.length;f.ref=c;m&&this.globalImageCache.addByteSize(c,f.dataLen);return this._sendImgData(p,f,m)})).catch((e=>{warn(`Unable to decode image "${p}": "${e}".`);return this._sendImgData(p,null,m)}));if(i){const e={fn:Jt,args:g,optionalContent:d};n.set(i,c,e);if(c){this._regionalImageCache.set(null,c,e);m&&this.globalImageCache.setData(c,{objId:p,fn:Jt,args:g,optionalContent:d,byteSize:0})}}}handleSMask(e,t,a,r,i,n){const s=e.get("G"),o={subtype:e.get("S").name,backdrop:e.get("BC")},c=e.get("TR");if(isPDFFunction(c)){const e=this._pdfFunctionFactory.create(c),t=new Uint8Array(256),a=new Float32Array(1);for(let r=0;r<256;r++){a[0]=r/255;e(a,0,a,0);t[r]=255*a[0]|0}o.transferMap=t}return this.buildFormXObject(t,s,o,a,r,i.state.clone(),n)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const a=[];let r=0,i=0;for(const e of t){const t=this.xref.fetchIfRef(e);r++;if(isName(t,"Identity")){a.push(null);continue}if(!isPDFFunction(t))return null;const n=this._pdfFunctionFactory.create(t),s=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;n(o,0,o,0);s[e]=255*o[0]|0}a.push(s);i++}return 1!==r&&4!==r||0===i?null:a}handleTilingType(e,t,a,r,i,n,s,o){const c=new OperatorList,l=Dict.merge({xref:this.xref,dictArray:[i.get("Resources"),a]});return this.getOperatorList({stream:r,task:s,resources:l,operatorList:c}).then((function(){const a=c.getIR(),r=getTilingPatternIR(a,i,t);n.addDependencies(c.dependencies);n.addOp(e,r);i.objId&&o.set(null,i.objId,{operatorListIR:a,dict:i})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,a,r,i,n,s=null,o=null){const c=t?.[0]instanceof Name?t[0].name:null;let l=await this.loadFont(c,a,e,s,o);if(l.font.isType3Font)try{await l.loadType3Data(this,e,i);r.addDependencies(l.type3Dependencies)}catch(e){l=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:l.font,evaluatorOptions:this.options})}n.font=l.font;l.send(this.handler);return l.loadedName}handleText(e,t){const a=t.font,r=a.charsToGlyphs(e);if(a.data){(!!(t.textRenderingMode&S)||"Pattern"===t.fillColorSpace.name||a.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(a,r,this.handler,this.options)}return r}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:a,cacheKey:r,task:i,stateManager:n,localGStateCache:s,localColorSpaceCache:o}){const c=t.objId;let l=!0;const h=[];let u=Promise.resolve();for(const r of t.getKeys()){const s=t.get(r);switch(r){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":h.push([r,s]);break;case"Font":l=!1;u=u.then((()=>this.handleSetFont(e,null,s[0],a,i,n.state).then((function(e){a.addDependency(e);h.push([r,[e,s[1]]])}))));break;case"BM":h.push([r,normalizeBlendMode(s)]);break;case"SMask":if(isName(s,"None")){h.push([r,!1]);break}if(s instanceof Dict){l=!1;u=u.then((()=>this.handleSMask(s,e,a,i,n,o)));h.push([r,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(s);h.push([r,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+r);break;default:info("Unknown graphic state operator "+r)}}await u;h.length>0&&a.addOp(De,[h]);l&&s.set(r,c,h)}loadFont(e,t,a,r=null,i=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let n;if(t)t instanceof Ref&&(n=t);else{const t=a.get("Font");t&&(n=t.getRaw(e))}if(n){if(this.parsingType3Font&&this.type3FontRefs.has(n))return errorFont();if(this.fontCache.has(n))return this.fontCache.get(n);t=this.xref.fetchIfRef(n)}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=r||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:s,resolve:o}=Promise.withResolvers();let c;try{c=this.preEvaluateFont(t);c.cssFontInfo=i}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:l,hash:h}=c,u=n instanceof Ref;let d;if(h&&l instanceof Dict){const e=l.fontAliases||=Object.create(null);if(e[h]){const t=e[h].aliasRef;if(u&&t&&this.fontCache.has(t)){this.fontCache.putAlias(n,t);return this.fontCache.get(n)}}else e[h]={fontID:this.idFactory.createFontId()};u&&(e[h].aliasRef=n);d=e[h].fontID}else d=this.idFactory.createFontId();assert(d?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(u)this.fontCache.put(n,s);else{t.cacheKey=`cacheKey_${d}`;this.fontCache.put(t.cacheKey,s)}t.loadedName=`${this.idFactory.getDocId()}_${d}`;this.translateFont(c).then((e=>{o(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);o(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return s}buildPath(e,t,a,r=!1){const i=e.length-1;a||(a=[]);if(i<0||e.fnArray[i]!==aa){if(r){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(Be,null)}let i;switch(t){case Xe:const e=a[0]+a[2],t=a[1]+a[3];i=[Math.min(a[0],e),Math.min(a[1],t),Math.max(a[0],e),Math.max(a[1],t)];break;case Ee:case Pe:i=[a[0],a[1],a[0],a[1]];break;default:i=[1/0,1/0,-1/0,-1/0]}e.addOp(aa,[[t],a,i]);r&&e.addOp(Re,null)}else{const r=e.argsArray[i];r[0].push(t);r[1].push(...a);const n=r[2];switch(t){case Xe:const e=a[0]+a[2],t=a[1]+a[3];n[0]=Math.min(n[0],a[0],e);n[1]=Math.min(n[1],a[1],t);n[2]=Math.max(n[2],a[0],e);n[3]=Math.max(n[3],a[1],t);break;case Ee:case Pe:n[0]=Math.min(n[0],a[0]);n[1]=Math.min(n[1],a[1]);n[2]=Math.max(n[2],a[0]);n[3]=Math.max(n[3],a[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:a}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:a}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:a,localShadingPatternCache:r}){let i,n=r.get(e);if(n)return n;try{i=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,a).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);r.set(e,null);return null}throw t}n=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(n=`${this.idFactory.getDocId()}_type3_${n}`);r.set(e,n);this.parsingType3Font?this.handler.send("commonobj",[n,"Pattern",i]):this.handler.send("obj",[n,this.pageIndex,"Pattern",i]);return n}handleColorN(e,t,a,r,i,n,s,o,c,l){const h=a.pop();if(h instanceof Name){const u=i.getRaw(h.name),d=u instanceof Ref&&c.getByRef(u);if(d)try{const i=r.base?r.base.getRgb(a,0):null,n=getTilingPatternIR(d.operatorListIR,d.dict,i);e.addOp(t,n);return}catch{}const f=this.xref.fetchIfRef(u);if(f){const i=f instanceof BaseStream?f.dict:f,h=i.get("PatternType");if(h===yn){const o=r.base?r.base.getRgb(a,0):null;return this.handleTilingType(t,o,n,f,i,e,s,c)}if(h===wn){const a=i.get("Shading"),r=this.parseShading({shading:a,resources:n,localColorSpaceCache:o,localShadingPatternCache:l});if(r){const a=i.getArray("Matrix");e.addOp(t,["Shading",r,a])}return}throw new FormatError(`Unknown PatternType: ${h}`)}}throw new FormatError(`Unknown PatternName: ${h}`)}_parseVisibilityExpression(e,t,a){if(++t>10){warn("Visibility expression is too deeply nested");return}const r=e.length,i=this.xref.fetchIfRef(e[0]);if(!(r<2)&&i instanceof Name){switch(i.name){case"And":case"Or":case"Not":a.push(i.name);break;default:warn(`Invalid operator ${i.name} in visibility expression`);return}for(let i=1;i0)return{type:"OCMD",expression:t}}const t=a.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const a of t)e.push(a.toString());else e.push(t.objId);return{type:r,ids:e,policy:a.get("P")instanceof Name?a.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:r,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:a,operatorList:r,initialState:i=null,fallbackFontDict:n=null}){a||=Dict.empty;i||=new EvalState;if(!r)throw new Error('getOperatorList: missing "operatorList" parameter');const s=this,o=this.xref;let c=!1;const l=new LocalImageCache,h=new LocalColorSpaceCache,u=new LocalGStateCache,d=new LocalTilingPatternCache,f=new Map,g=a.get("XObject")||Dict.empty,p=a.get("Pattern")||Dict.empty,m=new StateManager(i),b=new EvaluatorPreprocessor(e,o,m),y=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=b.savedStatesDepth;e0&&r.addOp(De,[t]);e=null;continue}}next(new Promise((function(e,i){if(!F)throw new FormatError("GState must be referred to by name.");const n=a.get("ExtGState");if(!(n instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const o=n.get(v);if(!(o instanceof Dict))throw new FormatError("GState should be a dictionary.");s.setGState({resources:a,gState:o,operatorList:r,cacheKey:v,task:t,stateManager:m,localGStateCache:u,localColorSpaceCache:h}).then(e,i)})).catch((function(e){if(!(e instanceof AbortException)){if(!s.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case Ee:case Pe:case Le:case je:case _e:case Ue:case Xe:s.buildPath(r,i,e,c);continue;case Et:case Pt:case Ut:case Xt:continue;case jt:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);r.addOp(jt,["OC",null]);continue}if("OC"===e[0].name){next(s.parseMarkedContentProps(e[1],a).then((e=>{r.addOp(jt,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!s.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);r.addOp(jt,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(S=0,k=e.length;S{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:i,stateManager:n=null,includeMarkedContent:s=!1,sink:o,seenStyles:c=new Set,viewBox:l,markedContentData:h=null,disableNormalization:u=!1,keepWhiteSpace:d=!1}){i||=Dict.empty;n||=new StateManager(new TextState);s&&(h||={level:0});const f={items:[],styles:Object.create(null)},g={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},p=[" "," "];let m=0;function saveLastChar(e){const t=(m+1)%2,a=" "!==p[m]&&" "===p[t];p[m]=e;m=t;return!d&&a}function shouldAddWhitepsace(){return!d&&" "!==p[m]&&" "===p[(m+1)%2]}function resetLastChars(){p[0]=p[1]=" ";m=0}const b=this,y=this.xref,w=[];let x=null;const S=new LocalImageCache,k=new LocalGStateCache,C=new EvaluatorPreprocessor(e,y,n);let v;function pushWhitespace({width:e=0,height:t=0,transform:a=g.prevTransform,fontName:r=g.fontName}){f.items.push({str:" ",dir:"ltr",width:e,height:t,transform:a,fontName:r,hasEOL:!1})}function getCurrentTextTransform(){const e=v.font,t=[v.fontSize*v.textHScale,0,0,v.fontSize,0,v.textRise];if(e.isType3Font&&(v.fontSize<=1||e.isCharBBox)&&!isArrayEqual(v.fontMatrix,r)){const a=e.bbox[3]-e.bbox[1];a>0&&(t[3]*=a*v.fontMatrix[3])}return Util.transform(v.ctm,Util.transform(v.textMatrix,t))}function ensureTextContentItem(){if(g.initialized)return g;const{font:e,loadedName:t}=v;if(!c.has(t)){c.add(t);f.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(b.options.fontExtraProperties&&e.systemFontInfo){const a=f.styles[t];a.fontSubstitution=e.systemFontInfo.css;a.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}g.fontName=t;const a=g.transform=getCurrentTextTransform();if(e.vertical){g.width=g.totalWidth=Math.hypot(a[0],a[1]);g.height=g.totalHeight=0;g.vertical=!0}else{g.width=g.totalWidth=0;g.height=g.totalHeight=Math.hypot(a[2],a[3]);g.vertical=!1}const r=Math.hypot(v.textLineMatrix[0],v.textLineMatrix[1]),i=Math.hypot(v.ctm[0],v.ctm[1]);g.textAdvanceScale=i*r;const{fontSize:n}=v;g.trackingSpaceMin=.102*n;g.notASpace=.03*n;g.negativeSpaceMax=-.2*n;g.spaceInFlowMin=.102*n;g.spaceInFlowMax=.6*n;g.hasEOL=!1;g.initialized=!0;return g}function updateAdvanceScale(){if(!g.initialized)return;const e=Math.hypot(v.textLineMatrix[0],v.textLineMatrix[1]),t=Math.hypot(v.ctm[0],v.ctm[1])*e;if(t!==g.textAdvanceScale){if(g.vertical){g.totalHeight+=g.height*g.textAdvanceScale;g.height=0}else{g.totalWidth+=g.width*g.textAdvanceScale;g.width=0}g.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");u||(t=function normalizeUnicode(e){if(!la){la=/([\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;ha=new Map([["ſt","ſt"]])}return e.replaceAll(la,((e,t,a)=>t?t.normalize("NFKC"):ha.get(a)))}(t));const a=bidi(t,-1,e.vertical);return{str:a.str,dir:a.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,a){const n=await b.loadFont(e,a,i);if(n.font.isType3Font)try{await n.loadType3Data(b,i,t)}catch{}v.loadedName=n.loadedName;v.font=n.font;v.fontMatrix=n.font.fontMatrix||r}function applyInverseRotation(e,t,a){const r=Math.hypot(a[0],a[1]);return[(a[0]*e+a[1]*t)/r,(a[2]*e+a[3]*t)/r]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let a=t[4],r=t[5];if(v.font?.vertical){if(al[2]||r+el[3])return!1}else if(a+el[2]||rl[3])return!1;if(!v.font||!g.prevTransform)return!0;let i=g.prevTransform[4],n=g.prevTransform[5];if(i===a&&n===r)return!0;let s=-1;t[0]&&0===t[1]&&0===t[2]?s=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(s=t[1]>0?90:270);switch(s){case 0:break;case 90:[a,r]=[r,a];[i,n]=[n,i];break;case 180:[a,r,i,n]=[-a,-r,-i,-n];break;case 270:[a,r]=[-r,-a];[i,n]=[-n,-i];break;default:[a,r]=applyInverseRotation(a,r,t);[i,n]=applyInverseRotation(i,n,g.prevTransform)}if(v.font.vertical){const e=(n-r)/g.textAdvanceScale,t=a-i,s=Math.sign(g.height);if(e.5*g.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>g.width){appendEOL();return!0}e<=s*g.notASpace&&resetLastChars();if(e<=s*g.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else g.height+=e;else if(!addFakeSpaces(e,g.prevTransform,s))if(0===g.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else g.height+=e;Math.abs(t)>.25*g.width&&flushTextContentItem();return!0}const o=(a-i)/g.textAdvanceScale,c=r-n,h=Math.sign(g.width);if(o.5*g.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(c)>g.height){appendEOL();return!0}o<=h*g.notASpace&&resetLastChars();if(o<=h*g.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else g.width+=o;else if(!addFakeSpaces(o,g.prevTransform,h))if(0===g.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else g.width+=o;Math.abs(c)>.25*g.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const a=v.font;if(!e){const e=v.charSpacing+t;e&&(a.vertical?v.translateTextMatrix(0,-e):v.translateTextMatrix(e*v.textHScale,0));d&&compareWithLastPosition(0);return}const r=a.charsToGlyphs(e),i=v.fontMatrix[0]*v.fontSize;for(let e=0,n=r.length;e0){const e=w.join("");w.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case dt:if(!n.state.font){b.ensureStateFont(n.state);continue}buildTextContentItem({chars:m[0],extraSpacing:0});break;case gt:if(!n.state.font){b.ensureStateFont(n.state);continue}v.carriageReturn();buildTextContentItem({chars:m[0],extraSpacing:0});break;case pt:if(!n.state.font){b.ensureStateFont(n.state);continue}v.wordSpacing=m[0];v.charSpacing=m[1];v.carriageReturn();buildTextContentItem({chars:m[2],extraSpacing:0});break;case Nt:flushTextContentItem();x||(x=i.get("XObject")||Dict.empty);var M=m[0]instanceof Name,D=m[0].name;if(M&&S.getByName(D))break;next(new Promise((function(e,a){if(!M)throw new FormatError("XObject must be referred to by name.");let r=x.getRaw(D);if(r instanceof Ref){if(S.getByRef(r)){e();return}if(b.globalImageCache.getData(r,b.pageIndex)){e();return}r=y.fetch(r)}if(!(r instanceof BaseStream))throw new FormatError("XObject should be a stream");const f=r.dict.get("Subtype");if(!(f instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==f.name){S.set(D,r.dict.objId,!0);e();return}const g=n.state.clone(),p=new StateManager(g),m=r.dict.getArray("Matrix");Array.isArray(m)&&6===m.length&&p.transform(m);enqueueChunk();const w={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;o.enqueue(e,t)},get desiredSize(){return o.desiredSize},get ready(){return o.ready}};b.getTextContent({stream:r,task:t,resources:r.dict.get("Resources")||i,stateManager:p,includeMarkedContent:s,sink:w,seenStyles:c,viewBox:l,markedContentData:h,disableNormalization:u,keepWhiteSpace:d}).then((function(){w.enqueueInvoked||S.set(D,r.dict.objId,!0);e()}),a)})).catch((function(e){if(!(e instanceof AbortException)){if(!b.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case De:M=m[0]instanceof Name;D=m[0].name;if(M&&k.getByName(D))break;next(new Promise((function(e,t){if(!M)throw new FormatError("GState must be referred to by name.");const a=i.get("ExtGState");if(!(a instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const r=a.get(D);if(!(r instanceof Dict))throw new FormatError("GState should be a dictionary.");const n=r.get("Font");if(n){flushTextContentItem();v.fontName=null;v.fontSize=n[1];handleSetFont(null,n[0]).then(e,t)}else{k.set(D,r.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!b.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Lt:flushTextContentItem();if(s){h.level++;f.items.push({type:"beginMarkedContent",tag:m[0]instanceof Name?m[0].name:null})}break;case jt:flushTextContentItem();if(s){h.level++;let e=null;m[1]instanceof Dict&&(e=m[1].get("MCID"));f.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${b.idFactory.getPageObjId()}_mc${e}`:null,tag:m[0]instanceof Name?m[0].name:null})}break;case _t:flushTextContentItem();if(s){if(0===h.level)break;h.level--;f.items.push({type:"endMarkedContent"})}break;case Re:!e||e.font===v.font&&e.fontSize===v.fontSize&&e.fontName===v.fontName||flushTextContentItem()}if(f.items.length>=o.desiredSize){p=!0;break}}if(p)next(xn);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const a=this.xref;let r;const i=this.readToUnicode(t.toUnicode);if(t.composite){const a=e.get("CIDSystemInfo");a instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(a.get("Registry")),ordering:stringToPDFString(a.get("Ordering")),supplement:a.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(r=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const n=[];let s,o=null;if(e.has("Encoding")){s=e.get("Encoding");if(s instanceof Dict){o=s.get("BaseEncoding");o=o instanceof Name?o.name:null;if(s.has("Differences")){const e=s.get("Differences");let t=0;for(const r of e){const e=a.fetchIfRef(r);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);n[t++]=e.name}}}}else if(s instanceof Name)o=s.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const c=!t.file||t.isInternalFont,l=Lr()[t.name];o&&c&&l&&(o=null);if(o)t.defaultEncoding=getEncoding(o);else{const e=!!(t.flags&Tr),a=!!(t.flags&Mr);s=lr;"TrueType"!==t.type||a||(s=hr);if(e||l){s=cr;c&&(/Symbol/i.test(t.name)?s=ur:/Dingbats/i.test(t.name)?s=dr:/Wingdings/i.test(t.name)&&(s=hr))}t.defaultEncoding=s}t.differences=n;t.baseEncodingName=o;t.hasEncoding=!!o||n.length>0;t.dict=e;t.toUnicode=await i;const h=await this.buildToUnicode(t);t.toUnicode=h;r&&(t.cidToGidMap=this.readCidToGidMap(r,h));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const a=[],r=e.defaultEncoding.slice(),i=e.baseEncodingName,n=e.differences;for(const e in n){const t=n[e];".notdef"!==t&&(r[e]=t)}const s=xr();for(const n in r){let o=r[n];if(""===o)continue;let c=s[o];if(void 0!==c){a[n]=String.fromCharCode(c);continue}let l=0;switch(o[0]){case"G":3===o.length&&(l=parseInt(o.substring(1),16));break;case"g":5===o.length&&(l=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const a=o.substring(1);if(t){l=parseInt(a,16);break}l=+a;if(Number.isNaN(l)&&Number.isInteger(parseInt(a,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":c=getUnicodeForGlyph(o,s);-1!==c&&(l=c);break;default:switch(o){case"f_h":case"f_t":case"T_h":a[n]=o.replaceAll("_","");continue}}if(l>0&&l<=1114111&&Number.isInteger(l)){if(i&&l===+n){const e=getEncoding(i);if(e&&(o=e[n])){a[n]=String.fromCharCode(s[o]);continue}}a[n]=String.fromCodePoint(l)}}return a}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:a}=e.cidSystemInfo,r=Name.get(`${t}-${a}-UCS2`),i=await CMapFactory.create({encoding:r,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),n=[],s=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const a=i.lookup(t);if(a){s.length=0;for(let e=0,t=a.length;e>1;(0!==i||t.has(n))&&(a[n]=i)}return a}extractWidths(e,t,a){const r=this.xref;let i=[],n=0;const s=[];let o,c,l,h,u,d,f,g;if(a.composite){n=e.has("DW")?e.get("DW"):1e3;g=e.get("W");if(g)for(c=0,l=g.length;c{const t=c.get(e),i=new OperatorList;return r.getOperatorList({stream:t,task:a,resources:l,operatorList:i}).then((()=>{i.fnArray[0]===bt&&this._removeType3ColorOperators(i,g);h[e]=i.getIR();for(const e of i.dependencies)s.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const a=new OperatorList;h[e]=a.getIR()}))}));this.type3Loaded=o.then((()=>{n.charProcOperatorList=h;if(this._bbox){n.isCharBBox=!0;n.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const a=Util.normalizeRect(e.argsArray[0].slice(2)),r=a[2]-a[0],i=a[3]-a[1],n=Math.hypot(r,i);if(0===r||0===i){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(n/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],a[0]);this._bbox[1]=Math.min(this._bbox[1],a[1]);this._bbox[2]=Math.max(this._bbox[2],a[2]);this._bbox[3]=Math.max(this._bbox[3],a[3])}let s=0,o=e.length;for(;s=Ee&&n<=Je;if(i.variableArgs)o>s&&info(`Command ${r}: expected [0, ${s}] args, but received ${o} args.`);else{if(o!==s){const e=this.nonProcessedArgs;for(;o>s;){e.push(t.shift());o--}for(;oEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(n,t);e.fn=n;e.args=t;return!0}if(a===da)return!1;if(null!==a){null===t&&(t=[]);t.push(a);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case Be:this.stateManager.save();break;case Re:this.stateManager.restore();break;case Ne:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:a,args:r}=e;switch(0|a){case nt:const[e,a]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof a&&a>0&&(t.fontSize=a);break;case It:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case vt:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Tt:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,a){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=a;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},a=!1;const r=[];try{for(;;){e.args.length=0;if(a||!this.read(e))break;const{fn:i,args:n}=e;switch(0|i){case Be:r.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case Re:t=r.pop()||t;break;case ht:t.scaleFactor*=Math.hypot(n[0],n[1]);break;case nt:const[e,i]=n;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i*t.scaleFactor);break;case wt:t.fillColorSpace=ColorSpace.parse({cs:n[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case kt:t.fillColorSpace.getRgbItem(n,0,t.fontColor,0);break;case It:ColorSpace.singletons.rgb.getRgbItem(n,0,t.fontColor,0);break;case vt:ColorSpace.singletons.gray.getRgbItem(n,0,t.fontColor,0);break;case Tt:ColorSpace.singletons.cmyk.getRgbItem(n,0,t.fontColor,0);break;case dt:case ft:case gt:case pt:a=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const a=new OffscreenCanvas(1,1);this.ctxMeasure=a.getContext("2d");FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],a=[...this.widths.entries()].sort();let r=null,i=null;for(const[e,n]of a)if(r)if(e===r+i.length)i.push(n);else{t.push(r,i);r=e;i=[n]}else{r=e;i=[n]}r&&t.push(r,i);e.set("W",t);const n=new Dict(this.xref);n.set("Ordering","Identity");n.set("Registry","Adobe");n.set("Supplement",0);e.set("CIDSystemInfo",n);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const a of e.split(/\r\n?|\n/))for(const e of a.split("")){const a=e.charCodeAt(0);if(this.widths.has(a))continue;const r=t.measureText(e),i=Math.ceil(r.width);this.widths.set(a,i);this.firstChar=Math.min(a,this.firstChar);this.lastChar=Math.max(a,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,a){const[r,s,o,c]=e;let l=o-r,h=c-s;t%180!=0&&([l,h]=[h,l]);const u=i*a;return{coords:[0,h+n*a-u],bbox:[0,0,l,h],matrix:0!==t?getRotationMatrix(t,h,u):void 0}}createAppearance(e,t,a,r,s,o){const c=this._createContext(),l=[];let h=-1/0;for(const t of e.split(/\r\n?|\n/)){l.push(t);const e=c.measureText(t).width;h=Math.max(h,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let a=this.widths.get(e);if(void 0===a){const r=c.measureText(t);a=Math.ceil(r.width);this.widths.set(e,a);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}h*=r/1e3;const[u,d,f,g]=t;let p=f-u,m=g-d;a%180!=0&&([p,m]=[m,p]);let b=1;h>p&&(b=p/h);let y=1;const w=i*r,x=n*r,S=w*l.length;S>m&&(y=m/S);const k=r*Math.min(b,y),C=["q",`0 0 ${numberToString(p)} ${numberToString(m)} re W n`,"BT",`1 0 0 1 0 ${numberToString(m+x)} Tm 0 Tc ${getPdfColor(s,!0)}`,`/${this.fontName.name} ${numberToString(k)} Tf`],{resources:v}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){C.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.set("Type",Name.get("ExtGState"));e.set("R0",t);v.set("ExtGState",e)}const F=numberToString(w);for(const e of l)C.push(`0 -${F} Td <${stringToUTF16HexString(e)}> Tj`);C.push("ET","Q");const O=C.join("\n"),T=new Dict(this.xref);T.set("Subtype",Name.get("Form"));T.set("Type",Name.get("XObject"));T.set("BBox",[0,0,p,m]);T.set("Length",O.length);T.set("Resources",v);if(a){const e=getRotationMatrix(a,p,m);T.set("Matrix",e)}const M=new StringStream(O);M.dict=T;return M}}class NameOrNumberTree{constructor(e,t,a){this.constructor===NameOrNumberTree&&unreachable("Cannot initialize NameOrNumberTree.");this.root=e;this.xref=t;this._type=a}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,a=new RefSet;a.put(this.root);const r=[this.root];for(;r.length>0;){const i=t.fetchIfRef(r.shift());if(!(i instanceof Dict))continue;if(i.has("Kids")){const e=i.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(a.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);r.push(t);a.put(t)}continue}const n=i.get(this._type);if(Array.isArray(n))for(let a=0,r=n.length;a10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const i=a.get("Kids");if(!Array.isArray(i))return null;let n=0,s=i.length-1;for(;n<=s;){const r=n+s>>1,o=t.fetchIfRef(i[r]),c=o.get("Limits");if(et.fetchIfRef(c[1]))){a=o;break}n=r+1}}if(n>s)return null}const i=a.get(this._type);if(Array.isArray(i)){let a=0,r=i.length-2;for(;a<=r;){const n=a+r>>1,s=n+(1&n),o=t.fetchIfRef(i[s]);if(eo))return t.fetchIfRef(i[s+1]);a=s+2}}}return null}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){ui=Object.create(null)}();!function clearPrimitiveCaches(){fa=Object.create(null);ga=Object.create(null);pa=Object.create(null)}();!function clearUnicodeCaches(){vr.clear()}()}function pickPlatformItem(e){return e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null}class FileSpec{#A=!1;constructor(e,t,a=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));this.description=e.has("Desc")?stringToPDFString(e.get("Desc")):"";e.has("RF")&&warn("Related file specifications are not supported");a||(e.has("EF")?this.#A=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){if(!this._filename&&this.root){const e=pickPlatformItem(this.root)||"unnamed";this._filename=stringToPDFString(e).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/")}return this._filename}get content(){if(!this.#A)return null;!this.contentRef&&this.root&&(this.contentRef=pickPlatformItem(this.root.get("EF")));let e=null;if(this.contentRef){const t=this.xref.fetchIfRef(this.contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have a content");return e}get serializable(){return{filename:this.filename,content:this.content}}}const Sn=0,kn=-2,An=-3,Cn=-4,vn=-5,Fn=-6,In=-9;function isWhitespace(e,t){const a=e[t];return" "===a||"\n"===a||"\r"===a||"\t"===a}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const a=[];let r=t;function skipWs(){for(;r"!==e[r]&&"/"!==e[r];)++r;const i=e.substring(t,r);skipWs();for(;r"!==e[r]&&"/"!==e[r]&&"?"!==e[r];){skipWs();let t="",i="";for(;r"!==e[a]&&"?"!==e[a]&&"/"!==e[a];)++a;const r=e.substring(t,a);!function skipWs(){for(;a"!==e[a+1]);)++a;return{name:r,value:e.substring(i,a),parsed:a-t}}parseXml(e){let t=0;for(;t",a);if(t<0){this.onError(In);return}this.onEndElement(e.substring(a,t));a=t+1;break;case"?":++a;const r=this._parseProcessingInstruction(e,a);if("?>"!==e.substring(a+r.parsed,a+r.parsed+2)){this.onError(An);return}this.onPi(r.name,r.value);a+=r.parsed+2;break;case"!":if("--"===e.substring(a+1,a+3)){t=e.indexOf("--\x3e",a+3);if(t<0){this.onError(vn);return}this.onComment(e.substring(a+3,t));a=t+3}else if("[CDATA["===e.substring(a+1,a+8)){t=e.indexOf("]]>",a+8);if(t<0){this.onError(kn);return}this.onCdata(e.substring(a+8,t));a=t+3}else{if("DOCTYPE"!==e.substring(a+1,a+8)){this.onError(Fn);return}{const r=e.indexOf("[",a+8);let i=!1;t=e.indexOf(">",a+8);if(t<0){this.onError(Cn);return}if(r>0&&t>r){t=e.indexOf("]>",a+8);if(t<0){this.onError(Cn);return}i=!0}const n=e.substring(a+8,t+(i?1:0));this.onDoctype(n);a=t+(i?2:1)}}break;default:const i=this._parseContent(e,a);if(null===i){this.onError(Fn);return}let n=!1;if("/>"===e.substring(a+i.parsed,a+i.parsed+2))n=!0;else if(">"!==e.substring(a+i.parsed,a+i.parsed+1)){this.onError(In);return}this.onBeginElement(i.name,i.attributes,n);a+=i.parsed+(n?2:1)}}else{for(;a0}searchNode(e,t){if(t>=e.length)return this;const a=e[t];if(a.name.startsWith("#")&&t0){r.push([i,0]);i=i.childNodes[0]}else{if(0===r.length)return null;for(;0!==r.length;){const[e,t]=r.pop(),a=t+1;if(a");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=Sn;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=Sn;this.parseXml(e);if(this._errorCode!==Sn)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,a=e.length;t\\376\\377([^<]+)/g,(function(e,t){const a=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,a,r){return String.fromCharCode(64*t+8*a+1*r)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),r=[">"];for(let e=0,t=a.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?r.push(String.fromCharCode(t)):r.push("&#x"+(65536+t).toString(16).substring(1)+";")}return r.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,a=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,a.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}class DecryptStream extends DecodeStream{constructor(e,t,a){super(t);this.str=e;this.dict=e.dict;this.decrypt=a;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e||0===e.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const a=this.bufferLength,r=a+e.length;this.ensureBuffer(r).set(e,a);this.bufferLength=r}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),a=e.length;for(let e=0;e<256;++e)t[e]=e;for(let r=0,i=0;r<256;++r){const n=t[r];i=i+n+e[r%a]&255;t[r]=t[i];t[i]=n}this.s=t}encryptBlock(e){let t=this.a,a=this.b;const r=this.s,i=e.length,n=new Uint8Array(i);for(let s=0;s>5&255;h[u++]=i>>13&255;h[u++]=i>>21&255;h[u++]=i>>>29&255;h[u++]=0;h[u++]=0;h[u++]=0;const g=new Int32Array(16);for(u=0;u>>32-o)|0;i=n}n=n+i|0;s=s+l|0;o=o+f|0;c=c+p|0}return new Uint8Array([255&n,n>>8&255,n>>16&255,n>>>24&255,255&s,s>>8&255,s>>16&255,s>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255,255&c,c>>8&255,c>>16&255,c>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,a;if(32&e){a=this.low;t=this.high}else{t=this.low;a=this.high}e&=31;this.low=t>>>e|a<<32-e;this.high=a>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let a=(this.high>>>0)+(e.high>>>0);t>4294967295&&(a+=1);this.low=0|t;this.high=0|a}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Tn=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,a){return e&t^~e&a}function maj(e,t,a){return e&t^e&a^t&a}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,a,r){let i=1779033703,n=3144134277,s=1013904242,o=2773480762,c=1359893119,l=2600822924,h=528734635,u=1541459225;const d=64*Math.ceil((r+9)/64),f=new Uint8Array(d);let g,p;for(g=0;g>>29&255;f[g++]=r>>21&255;f[g++]=r>>13&255;f[g++]=r>>5&255;f[g++]=r<<3&255;const b=new Uint32Array(64);for(g=0;g>>10)+b[p-7]+littleSigma(b[p-15])+b[p-16]|0;let t,a,r=i,d=n,m=s,w=o,x=c,S=l,k=h,C=u;for(p=0;p<64;++p){t=C+sigmaPrime(x)+ch(x,S,k)+e[p]+b[p];a=sigma(r)+maj(r,d,m);C=k;k=S;S=x;x=w+t|0;w=m;m=d;d=r;r=t+a|0}i=i+r|0;n=n+d|0;s=s+m|0;o=o+w|0;c=c+x|0;l=l+S|0;h=h+k|0;u=u+C|0}var y;return new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,l>>24&255,l>>16&255,l>>8&255,255&l,h>>24&255,h>>16&255,h>>8&255,255&h,u>>24&255,u>>16&255,u>>8&255,255&u])}}(),Mn=function calculateSHA512Closure(){function ch(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.not();i.and(r);e.xor(i)}function maj(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.and(r);e.xor(i);i.assign(a);i.and(r);e.xor(i)}function sigma(e,t,a){e.assign(t);e.rotateRight(28);a.assign(t);a.rotateRight(34);e.xor(a);a.assign(t);a.rotateRight(39);e.xor(a)}function sigmaPrime(e,t,a){e.assign(t);e.rotateRight(14);a.assign(t);a.rotateRight(18);e.xor(a);a.assign(t);a.rotateRight(41);e.xor(a)}function littleSigma(e,t,a){e.assign(t);e.rotateRight(1);a.assign(t);a.rotateRight(8);e.xor(a);a.assign(t);a.shiftRight(7);e.xor(a)}function littleSigmaPrime(e,t,a){e.assign(t);e.rotateRight(19);a.assign(t);a.rotateRight(61);e.xor(a);a.assign(t);a.shiftRight(6);e.xor(a)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,a,r,i=!1){let n,s,o,c,l,h,u,d;if(i){n=new Word64(3418070365,3238371032);s=new Word64(1654270250,914150663);o=new Word64(2438529370,812702999);c=new Word64(355462360,4144912697);l=new Word64(1731405415,4290775857);h=new Word64(2394180231,1750603025);u=new Word64(3675008525,1694076839);d=new Word64(1203062813,3204075428)}else{n=new Word64(1779033703,4089235720);s=new Word64(3144134277,2227873595);o=new Word64(1013904242,4271175723);c=new Word64(2773480762,1595750129);l=new Word64(1359893119,2917565137);h=new Word64(2600822924,725511199);u=new Word64(528734635,4215389547);d=new Word64(1541459225,327033209)}const f=128*Math.ceil((r+17)/128),g=new Uint8Array(f);let p,m;for(p=0;p>>29&255;g[p++]=r>>21&255;g[p++]=r>>13&255;g[p++]=r>>5&255;g[p++]=r<<3&255;const y=new Array(80);for(p=0;p<80;p++)y[p]=new Word64(0,0);let w=new Word64(0,0),x=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0),C=new Word64(0,0),v=new Word64(0,0),F=new Word64(0,0),O=new Word64(0,0);const T=new Word64(0,0),M=new Word64(0,0),D=new Word64(0,0),R=new Word64(0,0);let N,E;for(p=0;p=1;--e){a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e)n[e]=this._inv_s[n[e]];for(let a=0,r=16*e;a<16;++a,++r)n[a]^=t[r];for(let e=0;e<16;e+=4){const t=this._mix[n[e]],r=this._mix[n[e+1]],i=this._mix[n[e+2]],s=this._mix[n[e+3]];a=t^r>>>8^r<<24^i>>>16^i<<16^s>>>24^s<<8;n[e]=a>>>24&255;n[e+1]=a>>16&255;n[e+2]=a>>8&255;n[e+3]=255&a}}a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e){n[e]=this._inv_s[n[e]];n[e]^=t[e]}return n}_encrypt(e,t){const a=this._s;let r,i,n;const s=new Uint8Array(16);s.set(e);for(let e=0;e<16;++e)s[e]^=t[e];for(let e=1;e=r;--a)if(e[a]!==t){t=0;break}o-=t;n[n.length-1]=e.subarray(0,16-t)}}const c=new Uint8Array(o);for(let e=0,t=0,a=n.length;e=256&&(o=255&(27^o))}for(let t=0;t<4;++t){a[e]=r^=a[e-32];e++;a[e]=i^=a[e-32];e++;a[e]=n^=a[e-32];e++;a[e]=s^=a[e-32];e++}}return a}}class PDF17{checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(Tn(i,0,i.length),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(Tn(r,0,r.length),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=Tn(i,0,i.length);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=Tn(r,0,r.length);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,a){let r=Tn(t,0,t.length).subarray(0,32),i=[0],n=0;for(;n<64||i.at(-1)>n-32;){const t=e.length+r.length+a.length,l=new Uint8Array(t);let h=0;l.set(e,h);h+=e.length;l.set(r,h);h+=r.length;l.set(a,h);const u=new Uint8Array(64*t);for(let e=0,a=0;e<64;e++,a+=t)u.set(l,a);i=new AES128Cipher(r.subarray(0,16)).encrypt(u,r.subarray(16,32));const d=i.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===d?r=Tn(i,0,i.length):1===d?r=(s=i,o=0,c=i.length,Mn(s,o,c,!0)):2===d&&(r=Mn(i,0,i.length));n++}var s,o,c;return r.subarray(0,32)}checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(this._hash(e,i,a),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(this._hash(e,r,[]),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=this._hash(e,i,a);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=this._hash(e,r,[]);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const a=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return a.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let a=stringToBytes(e);a=t.decryptBlock(a,!0);return bytesToString(a)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const a=16-e.length%16;e+=String.fromCharCode(a).repeat(a);const r=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(r);else for(let e=0;e<16;e++)r[e]=Math.floor(256*Math.random());let i=stringToBytes(e);i=t.encrypt(i,r);const n=new Uint8Array(16+i.length);n.set(r);n.set(i,16);return bytesToString(n)}let a=stringToBytes(e);a=t.encrypt(a);return bytesToString(a)}}class CipherTransformFactory{static#C=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#v(e,t,a,r,i,n,s,o,c,l,h,u){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const d=6===e?new PDF20:new PDF17;return d.checkUserPassword(t,o,s)?d.getUserKey(t,c,h):t.length&&d.checkOwnerPassword(t,r,n,a)?d.getOwnerKey(t,i,n,l):null}#F(e,t,a,r,i,n,s,o){const c=40+a.length+e.length,l=new Uint8Array(c);let h,u,d=0;if(t){u=Math.min(32,t.length);for(;d>8&255;l[d++]=i>>16&255;l[d++]=i>>>24&255;for(h=0,u=e.length;h=4&&!o){l[d++]=255;l[d++]=255;l[d++]=255;l[d++]=255}let f=On(l,0,d);const g=s>>3;if(n>=3)for(h=0;h<50;++h)f=On(f,0,g);const p=f.subarray(0,g);let m,b;if(n>=3){for(d=0;d<32;++d)l[d]=CipherTransformFactory.#C[d];for(h=0,u=e.length;h>3;if(a>=3)for(o=0;o<50;++o)c=On(c,0,c.length);let h,u;if(a>=3){u=t;const e=new Uint8Array(l);for(o=19;o>=0;o--){for(let t=0;t>8&255;i[s++]=e>>16&255;i[s++]=255&t;i[s++]=t>>8&255;if(r){i[s++]=115;i[s++]=65;i[s++]=108;i[s++]=84}return On(i,0,s).subarray(0,Math.min(a.length+5,16))}#T(e,t,a,r,i){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const n=this,s=e.get(t.name),o=s?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(n.#O(a,r,i,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(n.#O(a,r,i,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(i)};throw new FormatError("Unknown crypto method")}constructor(e,t,a){const r=e.get("Filter");if(!isName(r,"Standard"))throw new FormatError("unknown encryption method");this.filterName=r.name;this.dict=e;const i=e.get("V");if(!Number.isInteger(i)||1!==i&&2!==i&&4!==i&&5!==i)throw new FormatError("unsupported encryption algorithm");this.algorithm=i;let n=e.get("Length");if(!n)if(i<=3)n=40;else{const t=e.get("CF"),a=e.get("StmF");if(t instanceof Dict&&a instanceof Name){t.suppressEncryption=!0;const e=t.get(a.name);n=e?.get("Length")||128;n<40&&(n<<=3)}}if(!Number.isInteger(n)||n<40||n%8!=0)throw new FormatError("invalid key length");const s=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),c=s.subarray(0,32),l=o.subarray(0,32),h=e.get("P"),u=e.get("R"),d=(4===i||5===i)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=d;const f=stringToBytes(t);let g,p;if(a){if(6===u)try{a=utf8StringToString(a)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}g=stringToBytes(a)}if(5!==i)p=this.#F(f,g,c,l,h,u,n,d);else{const t=s.subarray(32,40),a=s.subarray(40,48),r=o.subarray(0,48),i=o.subarray(32,40),n=o.subarray(40,48),h=stringToBytes(e.get("OE")),d=stringToBytes(e.get("UE")),f=stringToBytes(e.get("Perms"));p=this.#v(u,g,c,t,a,r,l,i,n,h,d,f)}if(!p&&!a)throw new PasswordException("No password given",ra);if(!p&&a){const e=this.#I(g,c,u,n);p=this.#F(f,e,c,l,h,u,n,d)}if(!p)throw new PasswordException("Incorrect Password",ia);this.encryptionKey=p;if(i>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#T(this.cf,this.strf,e,t,this.encryptionKey),this.#T(this.cf,this.stmf,e,t,this.encryptionKey));const a=this.#O(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(a)};return new CipherTransform(cipherConstructor,cipherConstructor)}}async function writeObject(e,t,a,{encrypt:r=null}){const i=r?.createCipherTransform(e.num,e.gen);a.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,a,i):t instanceof BaseStream?await writeStream(t,a,i):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,a,i);a.push("\nendobj\n")}async function writeDict(e,t,a){t.push("<<");for(const r of e.getKeys()){t.push(` /${escapePDFName(r)} `);await writeValue(e.getRaw(r),t,a)}t.push(">>")}async function writeStream(e,t,a){let r=e.getBytes();const{dict:i}=e,[n,s]=await Promise.all([i.getAsync("Filter"),i.getAsync("DecodeParms")]),o=isName(Array.isArray(n)?await i.xref.fetchIfRefAsync(n[0]):n,"FlateDecode");if("undefined"!=typeof CompressionStream&&(r.length>=256||o))try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();t.write(r);t.close();const a=await new Response(e.readable).arrayBuffer();r=new Uint8Array(a);let c,l;if(n){if(!o){c=Array.isArray(n)?[Name.get("FlateDecode"),...n]:[Name.get("FlateDecode"),n];s&&(l=Array.isArray(s)?[null,...s]:[null,s])}}else c=Name.get("FlateDecode");c&&i.set("Filter",c);l&&i.set("DecodeParms",l)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let c=bytesToString(r);a&&(c=a.encryptString(c));i.set("Length",c.length);await writeDict(i,t,a);t.push(" stream\n",c,"\nendstream")}async function writeArray(e,t,a){t.push("[");let r=!0;for(const i of e){r?r=!1:t.push(" ");await writeValue(i,t,a)}t.push("]")}async function writeValue(e,t,a){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,a);else if("string"==typeof e){a&&(e=a.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,a):e instanceof BaseStream?await writeStream(e,t,a):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,a,r){for(let i=t+a-1;i>a-1;i--){r[i]=255&e;e>>=8}return a+t}function writeString(e,t,a){for(let r=0,i=e.length;r1&&(n=a.documentElement.searchNode([i.at(-1)],0));n?n.childNodes=Array.isArray(r)?r.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",r)]:warn(`Node not found for path: ${t}`)}const r=[];a.documentElement.dump(r);return r.join("")}(r.fetchIfRef(t).getString(),a)}const i=r.encrypt;if(i){e=i.createCipherTransform(t.num,t.gen).encryptString(e)}const n=`${t.num} ${t.gen} obj\n<< /Type /EmbeddedFile /Length ${e.length}>>\nstream\n`+e+"\nendstream\nendobj\n";a.push({ref:t,data:n})}function getIndexes(e){const t=[];for(const{ref:a}of e)a.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(a.num,1);return t}function computeIDs(e,t,a){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const r=function computeMD5(e,t){const a=Math.floor(Date.now()/1e3),r=t.filename||"",i=[a.toString(),r,e.toString()];let n=i.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){i.push(e);n+=e.length}const s=new Uint8Array(n);let o=0;for(const e of i){writeString(e,o,s);o+=e.length}return bytesToString(On(s))}(e,t);a.set("ID",[t.fileIds[0],r])}}async function incrementalUpdate({originalData:e,xrefInfo:t,newRefs:a,xref:r=null,hasXfa:i=!1,xfaDatasetsRef:n=null,hasXfaDatasetsEntry:s=!1,needAppearances:o,acroFormRef:c=null,acroForm:l=null,xfaData:h=null,useXrefStream:u=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:a,hasXfa:r,hasXfaDatasetsEntry:i,xfaDatasetsRef:n,needAppearances:s,newRefs:o}){!r||i||n||warn("XFA - Cannot save it");if(!s&&(!r||!n||i))return;const c=t.clone();if(r&&!i){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,n);c.set("XFA",e)}s&&c.set("NeedAppearances",!0);const l=[];await writeObject(a,c,l,e);o.push({ref:a,data:l.join("")})}({xref:r,acroForm:l,acroFormRef:c,hasXfa:i,hasXfaDatasetsEntry:s,xfaDatasetsRef:n,needAppearances:o,newRefs:a});i&&updateXFA({xfaData:h,xfaDatasetsRef:n,newRefs:a,xref:r});let d,f;const g=e.at(-1);if(10===g||13===g){d=[];f=e.length}else{d=["\n"];f=e.length+1}const p=function getTrailerDict(e,t,a){const r=new Dict(null);r.set("Prev",e.startXRef);const i=e.newRef;if(a){t.push({ref:i,data:""});r.set("Size",i.num+1);r.set("Type",Name.get("XRef"))}else r.set("Size",i.num);null!==e.rootRef&&r.set("Root",e.rootRef);null!==e.infoRef&&r.set("Info",e.infoRef);null!==e.encryptRef&&r.set("Encrypt",e.encryptRef);return r}(t,a,u);a=a.sort(((e,t)=>e.ref.num-t.ref.num));for(const{data:e}of a)d.push(e);await(u?async function getXRefStreamTable(e,t,a,r,i){const n=[];let s=0,o=0;for(const{ref:e,data:r}of a){s=Math.max(s,t);const a=Math.min(e.gen,65535);o=Math.max(o,a);n.push([1,t,a]);t+=r.length}r.set("Index",getIndexes(a));const c=[1,getSizeInBytes(s),getSizeInBytes(o)];r.set("W",c);computeIDs(t,e,r);const l=c.reduce(((e,t)=>e+t),0),h=new Uint8Array(l*n.length),u=new Stream(h);u.dict=r;let d=0;for(const[e,t,a]of n){d=writeInt(e,c[0],d,h);d=writeInt(t,c[1],d,h);d=writeInt(a,c[2],d,h)}await writeObject(e.newRef,u,i,{});i.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,f,a,p,d):async function getXRefTable(e,t,a,r,i){i.push("xref\n");const n=getIndexes(a);let s=0;for(const{ref:e,data:r}of a){if(e.num===n[s]){i.push(`${n[s]} ${n[s+1]}\n`);s+=2}i.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=r.length}computeIDs(t,e,r);i.push("trailer\n");await writeDict(r,i);i.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,f,a,p,d));const m=d.reduce(((e,t)=>e+t.length),e.length),b=new Uint8Array(m);b.set(e);let y=e.length;for(const e of d){writeString(e,y,b);y+=e.length}return b}const Dn=1,Bn=2,Rn=3,Nn=4,En=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#M(e,t,a){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let r=this.structParentIds.get(e);if(!r){r=[];this.structParentIds.put(e,r)}r.push([t,a])}addAnnotationIdToPage(e,t){this.#M(e,t,Nn)}readRoleMap(){const e=this.dict.get("RoleMap");e instanceof Dict&&e.forEach(((e,t)=>{t instanceof Name&&this.roleMap.set(e,t.name)}))}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:a}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let r=0,i=!0;for(const[e,n]of a){const{ref:a}=await t.getPage(e);if(!(a instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);i=!0;break}for(const e of n)if(e.accessibilityData?.type){e.parentTreeId=r++;i=!1}}if(i){for(const e of a.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:a,pdfManager:r,newRefs:i}){const n=r.catalog.cloneDict(),s=t.getNewTemporaryRef();n.set("StructTreeRoot",s);const o=[];await writeObject(a,n,o,t);i.push({ref:a,data:o.join("")});const c=new Dict(t);c.set("Type",Name.get("StructTreeRoot"));const l=t.getNewTemporaryRef();c.set("ParentTree",l);const h=[];c.set("K",h);const u=new Dict(t),d=[];u.set("Nums",d);const f=await this.#D({newAnnotationsByPage:e,structTreeRootRef:s,kids:h,nums:d,xref:t,pdfManager:r,newRefs:i,buffer:o});c.set("ParentTreeNextKey",f);o.length=0;await writeObject(l,u,o,t);i.push({ref:l,data:o.join("")});o.length=0;await writeObject(s,c,o,t);i.push({ref:s,data:o.join("")})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:a}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let r=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(r)||r<0){warn("Cannot update the struct tree: invalid next key.");return!1}const i=this.dict.get("ParentTree");if(!(i instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const n=i.get("Nums");if(!Array.isArray(n)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const s=new NumberTree(i,t);for(const t of a.keys()){const{pageDict:a}=await e.getPage(t);if(!a.has("StructParents"))continue;const r=a.get("StructParents");if(!Number.isInteger(r)||!Array.isArray(s.get(r))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let o=!0;for(const[t,i]of a){const{pageDict:a}=await e.getPage(t);StructTreeRoot.#B({elements:i,xref:this.dict.xref,pageDict:a,numberTree:s});for(const e of i)if(e.accessibilityData?.type){e.parentTreeId=r++;o=!1}}if(o){for(const e of a.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,newRefs:a}){const r=this.dict.xref,i=this.dict.clone(),n=this.ref;let s,o=i.getRaw("ParentTree");if(o instanceof Ref)s=r.fetch(o);else{s=o;o=r.getNewTemporaryRef();i.set("ParentTree",o)}s=s.clone();let c=s.getRaw("Nums"),l=null;if(c instanceof Ref){l=c;c=r.fetch(l)}c=c.slice();l||s.set("Nums",c);let h=i.getRaw("K"),u=null;if(h instanceof Ref){u=h;h=r.fetch(u)}else{u=r.getNewTemporaryRef();i.set("K",u)}h=Array.isArray(h)?h.slice():[h];const d=[],f=await StructTreeRoot.#D({newAnnotationsByPage:e,structTreeRootRef:n,kids:h,nums:c,xref:r,pdfManager:t,newRefs:a,buffer:d});i.set("ParentTreeNextKey",f);d.length=0;await writeObject(u,h,d,r);a.push({ref:u,data:d.join("")});if(l){d.length=0;await writeObject(l,c,d,r);a.push({ref:l,data:d.join("")})}d.length=0;await writeObject(o,s,d,r);a.push({ref:o,data:d.join("")});d.length=0;await writeObject(n,i,d,r);a.push({ref:n,data:d.join("")})}static async#D({newAnnotationsByPage:e,structTreeRootRef:t,kids:a,nums:r,xref:i,pdfManager:n,newRefs:s,buffer:o}){const c=Name.get("OBJR");let l=-1/0;for(const[h,u]of e){const{ref:e}=await n.getPage(h),d=e instanceof Ref;for(const{accessibilityData:n,ref:h,parentTreeId:f,structTreeParent:g}of u){if(!n?.type)continue;const{type:u,title:p,lang:m,alt:b,expanded:y,actualText:w}=n;l=Math.max(l,f);const x=i.getNewTemporaryRef(),S=new Dict(i);S.set("S",Name.get(u));p&&S.set("T",p);m&&S.set("Lang",m);b&&S.set("Alt",b);y&&S.set("E",y);w&&S.set("ActualText",w);g?await this.#R({structTreeParent:g,tagDict:S,newTagRef:x,fallbackRef:t,xref:i,newRefs:s,buffer:o}):S.set("P",t);const k=new Dict(i);S.set("K",k);k.set("Type",c);d&&k.set("Pg",e);k.set("Obj",h);o.length=0;await writeObject(x,S,o,i);s.push({ref:x,data:o.join("")});r.push(f,x);a.push(x)}}return l+1}static#B({elements:e,xref:t,pageDict:a,numberTree:r}){const i=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);i.set(e,t)}const n=a.get("StructParents");if(!Number.isInteger(n))return;const s=r.get(n),updateElement=(e,a,r)=>{const n=i.get(e);if(n){const e=a.getRaw("P"),i=t.fetchIfRef(e);e instanceof Ref&&i instanceof Dict&&(n.structTreeParent={ref:r,dict:a});return!0}return!1};for(const e of s){if(!(e instanceof Ref))continue;const a=t.fetch(e),r=a.get("K");if(Number.isInteger(r))updateElement(r,a,e);else if(Array.isArray(r))for(let i of r){i=t.fetchIfRef(i);if(Number.isInteger(i)&&updateElement(i,a,e))break}}}static async#R({structTreeParent:{ref:e,dict:t},tagDict:a,newTagRef:r,fallbackRef:i,xref:n,newRefs:s,buffer:o}){const c=t.getRaw("P");let l=n.fetchIfRef(c);a.set("P",c);let h,u=!1,d=l.getRaw("K");if(d instanceof Ref)h=n.fetch(d);else{h=d;d=n.getNewTemporaryRef();l=l.clone();l.set("K",d);u=!0}if(Array.isArray(h)){const t=h.indexOf(e);if(!(t>=0)){warn("Cannot update the struct tree: parent kid not found.");a.set("P",i);return}h=h.slice();h.splice(t+1,0,r)}else if(h instanceof Dict){h=[d,r];d=n.getNewTemporaryRef();l.set("K",d);u=!0}o.length=0;await writeObject(d,h,o,n);s.push({ref:d,data:o.join("")});if(u){o.length=0;await writeObject(c,l,o,n);s.push({ref:c,data:o.join("")})}}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:a}=this.tree;return a.roleMap.has(t)?a.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const a=this.dict.get("K");if(Array.isArray(a))for(const t of a){const a=this.parseKid(e,t);a&&this.kids.push(a)}else{const t=this.parseKid(e,a);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Dn,mcid:t,pageObjId:e});let a=null;t instanceof Ref?a=this.dict.xref.fetch(t):t instanceof Dict&&(a=t);if(!a)return null;const r=a.getRaw("Pg");r instanceof Ref&&(e=r.toString());const i=a.get("Type")instanceof Name?a.get("Type").name:null;if("MCR"===i){if(this.tree.pageDict.objId!==e)return null;const t=a.getRaw("Stm");return new StructElement({type:Bn,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:a.get("MCID")})}if("OBJR"===i){if(this.tree.pageDict.objId!==e)return null;const t=a.getRaw("Obj");return new StructElement({type:Rn,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:En,dict:a})}}class StructElement{constructor({type:e,dict:t=null,mcid:a=null,pageObjId:r=null,refObjId:i=null}){this.type=e;this.dict=t;this.mcid=a;this.pageObjId=r;this.refObjId=i;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}parse(e){if(!this.root||!this.rootDict)return;const t=this.rootDict.get("ParentTree");if(!t)return;const a=this.pageDict.get("StructParents"),r=e instanceof Ref&&this.root.structParentIds?.get(e);if(!Number.isInteger(a)&&!r)return;const i=new Map,n=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(a)){const e=n.get(a);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),i)}if(r)for(const[e,t]of r){const a=n.get(e);if(a){const e=this.addNode(this.rootDict.xref.fetchIfRef(a),i);1===e?.kids?.length&&e.kids[0].type===Rn&&(e.kids[0].type=t)}}}addNode(e,t,a=0){if(a>40){warn("StructTree MAX_DEPTH reached.");return null}if(t.has(e))return t.get(e);const r=new StructElementNode(this,e);t.set(e,r);const i=e.get("P");if(!i||isName(i.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,r)||t.delete(e);return r}const n=this.addNode(i,t,a+1);if(!n)return r;let s=!1;for(const t of n.kids)if(t.type===En&&t.dict===e){t.parentNode=r;s=!0}s||t.delete(e);return r}addTopLevelNode(e,t){const a=this.rootDict.get("K");if(!a)return!1;if(a instanceof Dict){if(a.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(a))return!0;let r=!1;for(let i=0;i40){warn("StructTree too deep to be fully serialized.");return}const r=Object.create(null);r.role=e.role;r.children=[];t.children.push(r);const i=e.dict.get("Alt");"string"==typeof i&&(r.alt=stringToPDFString(i));const n=e.dict.get("Lang");"string"==typeof n&&(r.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===En?t.parentNode:null;e?nodeToSerializable(e,r,a+1):t.type===Dn||t.type===Bn?r.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Rn?r.children.push({type:"object",id:t.refObjId}):t.type===Nn&&r.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function fetchDestination(e){e instanceof Dict&&(e=e.get("D"));return Array.isArray(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(Array.isArray(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ba.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang","string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const a=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(a instanceof BaseStream&&a.dict instanceof Dict){const e=a.dict.get("Type"),r=a.dict.get("Subtype");if(isName(e,"Metadata")&&isName(r,"XML")){const e=stringToUTF8String(a.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const a in t){const r=e.get(a);"boolean"==typeof r&&(t[a]=r)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const a=new StructTreeRoot(t,e);a.init();return a}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},a=[{obj:e,parent:t}],r=new RefSet;r.put(e);const i=this.xref,n=new Uint8ClampedArray(3);for(;a.length>0;){const t=a.shift(),s=i.fetchIfRef(t.obj);if(null===s)continue;s.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:s,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const c=s.get("Title"),l=s.get("F")||0,h=s.getArray("C"),u=s.get("Count");let d=n;!Array.isArray(h)||3!==h.length||0===h[0]&&0===h[1]&&0===h[2]||(d=ColorSpace.singletons.rgb.getRgb(h,0));const f={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof c?stringToPDFString(c):"",color:d,count:Number.isInteger(u)?u:void 0,bold:!!(2&l),italic:!!(1&l),items:[]};t.parent.items.push(f);e=s.getRaw("First");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:f});r.put(e)}e=s.getRaw("Next");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:t.parent});r.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const a=[];for(const e in w){const r=w[e];t&r&&a.push(r)}return a}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const a=t.get("D");if(!a)return shadow(this,"optionalContentConfig",null);const r=t.get("OCGs");if(!Array.isArray(r))return shadow(this,"optionalContentConfig",null);const i=[],n=new RefSet;for(const e of r)if(e instanceof Ref&&!n.has(e)){n.put(e);i.push(this.#N(e))}e=this.#E(a,n);e.groups=i}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#N(e){const t=this.xref.fetch(e),a={id:e.toString(),name:null,intent:null,usage:{print:null,view:null}},r=t.get("Name");"string"==typeof r&&(a.name=stringToPDFString(r));let i=t.getArray("Intent");Array.isArray(i)||(i=[i]);i.every((e=>e instanceof Name))&&(a.intent=i.map((e=>e.name)));const n=t.get("Usage");if(!(n instanceof Dict))return a;const s=a.usage,o=n.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.print={printState:e.name}}}const c=n.get("View");if(c instanceof Dict){const e=c.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.view={viewState:e.name}}}return a}#E(e,t){function parseOnOff(e){const a=[];if(Array.isArray(e))for(const r of e)r instanceof Ref&&t.has(r)&&a.push(r.toString());return a}function parseOrder(e,a=0){if(!Array.isArray(e))return null;const i=[];for(const n of e){if(n instanceof Ref&&t.has(n)){r.put(n);i.push(n.toString());continue}const e=parseNestedOrder(n,a);e&&i.push(e)}if(a>0)return i;const n=[];for(const e of t)r.has(e)||n.push(e.toString());n.length&&i.push({name:null,order:n});return i}function parseNestedOrder(e,t){if(++t>i){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const r=a.fetchIfRef(e);if(!Array.isArray(r))return null;const n=a.fetchIfRef(r[0]);if("string"!=typeof n)return null;const s=parseOrder(r.slice(1),t);return s&&s.length?{name:stringToPDFString(n),order:s}:null}const a=this.xref,r=new RefSet,i=10;return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:null}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[a,r]of e.getAll()){const e=fetchDestination(r);e&&(t[stringToPDFString(a)]=e)}else e instanceof Dict&&e.forEach((function(e,a){const r=fetchDestination(a);r&&(t[e]=r)}));return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const a=fetchDestination(t.get(e));if(a)return a;const r=this.destinations[e];if(r){warn(`Found "${e}" at an incorrect position in the NameTree.`);return r}}else if(t instanceof Dict){const a=fetchDestination(t.get(e));if(a)return a}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let a=null,r="";const i=new NumberTree(e,this.xref).getAll();let n="",s=1;for(let e=0,o=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");s=e}else s=1}switch(a){case"D":n=s;break;case"R":case"r":n=toRomanNumerals(s,"r"===a);break;case"A":case"a":const e=26,t="a"===a?97:65,r=s-1;n=String.fromCharCode(t+r%e).repeat(Math.floor(r/e)+1);break;default:if(a)throw new FormatError(`Invalid style "${a}" in PageLabel dictionary.`);n=""}t[e]=r+n;s++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const a of e.getKeys()){const r=e.get(a);let i;switch(a){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof r&&(i=r);break;case"NonFullScreenPageMode":if(r instanceof Name)switch(r.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":i=r.name;break;default:i="UseNone"}break;case"Direction":if(r instanceof Name)switch(r.name){case"L2R":case"R2L":i=r.name;break;default:i="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(r instanceof Name)switch(r.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":i=r.name;break;default:i="CropBox"}break;case"PrintScaling":if(r instanceof Name)switch(r.name){case"None":case"AppDefault":i=r.name;break;default:i="AppDefault"}break;case"Duplex":if(r instanceof Name)switch(r.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":i=r.name;break;default:i="None"}break;case"PrintPageRange":if(Array.isArray(r)&&r.length%2==0){r.every(((e,t,a)=>Number.isInteger(e)&&e>0&&(0===t||e>=a[t-1])&&e<=this.numPages))&&(i=r)}break;case"NumCopies":Number.isInteger(r)&&r>0&&(i=r);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${a}.`);continue}if(void 0!==i){t||(t=Object.create(null));t[a]=i}else warn(`Bad value, for key "${a}", in ViewerPreferences: ${r}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const a=new Dict(this.xref);a.set("A",e);const r={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:a,resultObj:r});Array.isArray(r.dest)?t.dest=r.dest:r.action&&(t.action=r.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const a=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,r]of a.getAll()){const a=new FileSpec(r,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=a.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const a=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,r]of a.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),r)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,a){if(!(a instanceof Dict))return;if(!isName(a.get("S"),"JavaScript"))return;let r=a.get("JS");if(r instanceof BaseStream)r=r.getString();else if("string"!=typeof r)return;r=stringToPDFString(r).replaceAll("\0","");r&&(t||=new Map).set(e,r)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,a]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),a)}const a=this._catDict.get("OpenAction");a&&appendIfJavaScriptDict("OpenAction",a);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,we);if(e){t||=Object.create(null);for(const[a,r]of e)a in t?t[a].push(r):t[a]=[r]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const a=await Promise.all(this.fontCache);for(const r of a)if(r.loadedName===e){r.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],a=new RefSet,r=this._catDict.getRaw("Pages");r instanceof Ref&&a.put(r);const i=this.xref,n=this.pageKidsCountCache,s=this.pageIndexCache;let o=0;for(;t.length;){const r=t.pop();if(r instanceof Ref){const c=n.get(r);if(c>=0&&o+c<=e){o+=c;continue}if(a.has(r))throw new FormatError("Pages tree contains circular reference.");a.put(r);const l=await i.fetchAsync(r);if(l instanceof Dict){let t=l.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!l.has("Kids")){n.has(r)||n.put(r,1);s.has(r)||s.put(r,o);if(o===e)return[l,r];o++;continue}}t.push(l);continue}if(!(r instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=r;let l=r.getRaw("Count");l instanceof Ref&&(l=await i.fetchAsync(l));if(Number.isInteger(l)&&l>=0){c&&!n.has(c)&&n.put(c,l);if(o+l<=e){o+=l;continue}}let h=r.getRaw("Kids");h instanceof Ref&&(h=await i.fetchAsync(h));if(!Array.isArray(h)){let t=r.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!r.has("Kids")){if(o===e)return[r,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--)t.push(h[e])}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,a=[{currentNode:this.toplevelPagesDict,posInKids:0}],r=new RefSet,i=this._catDict.getRaw("Pages");i instanceof Ref&&r.put(i);const n=new Map,s=this.xref,o=this.pageIndexCache;let c=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,c);n.set(c++,[e,t])}function addPageError(a){if(a instanceof XRefEntryException&&!e)throw a;if(e&&t&&0===c){warn(`getAllPageDicts - Skipping invalid first page: "${a}".`);a=Dict.empty}n.set(c++,[a,null])}for(;a.length>0;){const e=a.at(-1),{currentNode:t,posInKids:i}=e;let n=t.getRaw("Kids");if(n instanceof Ref)try{n=await s.fetchAsync(n)}catch(e){addPageError(e);break}if(!Array.isArray(n)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(i>=n.length){a.pop();continue}const o=n[i];let c;if(o instanceof Ref){if(r.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}r.put(o);try{c=await s.fetchAsync(o)}catch(e){addPageError(e);break}}else c=o;if(!(c instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let l=c.getRaw("Type");if(l instanceof Ref)try{l=await s.fetchAsync(l)}catch(e){addPageError(e);break}isName(l,"Page")||!c.has("Kids")?addPageDict(c,o instanceof Ref?o:null):a.push({currentNode:c,posInKids:0});e.posInKids++}return n}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const a=this.xref;let r=0;const next=t=>function pagesBeforeRef(t){let r,i=0;return a.fetchAsync(t).then((function(a){if(isRefsEqual(t,e)&&!isDict(a,"Page")&&!(a instanceof Dict&&!a.has("Type")&&a.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!a)return null;if(!(a instanceof Dict))throw new FormatError("Node must be a dictionary.");r=a.getRaw("Parent");return a.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const n=[];let s=!1;for(const r of e){if(!(r instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(r,t)){s=!0;break}n.push(a.fetchAsync(r).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?i+=e.get("Count"):i++})))}if(!s)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(n).then((function(){return[i,r]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,r);return r}const[a,i]=t;r+=a;return next(i)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:a=null,docAttachments:r=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let i,n,s=e.get("A");if(!(s instanceof Dict))if(e.has("Dest"))s=e.get("Dest");else{s=e.get("AA");s instanceof Dict&&(s.has("D")?s=s.get("D"):s.has("U")&&(s=s.get("U")))}if(s instanceof Dict){const e=s.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const a=e.name;switch(a){case"ResetForm":const e=s.get("Flags"),o=0==(1&("number"==typeof e?e:0)),c=[],l=[];for(const e of s.get("Fields")||[])e instanceof Ref?l.push(e.toString()):"string"==typeof e&&c.push(stringToPDFString(e));t.resetForm={fields:c,refs:l,include:o};break;case"URI":i=s.get("URI");i instanceof Name&&(i="/"+i.name);break;case"GoTo":n=s.get("D");break;case"Launch":case"GoToR":const h=s.get("F");if(h instanceof Dict){const e=new FileSpec(h,null,!0),{filename:t}=e.serializable;i=t}else"string"==typeof h&&(i=h);const u=fetchRemoteDest(s);u&&"string"==typeof i&&(i=i.split("#",1)[0]+"#"+u);const d=s.get("NewWindow");"boolean"==typeof d&&(t.newWindow=d);break;case"GoToE":const f=s.get("T");let g;if(r&&f instanceof Dict){const e=f.get("R"),t=f.get("N");isName(e,"C")&&"string"==typeof t&&(g=r[stringToPDFString(t)])}if(g){t.attachment=g;const e=fetchRemoteDest(s);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const p=s.get("N");p instanceof Name&&(t.action=p.name);break;case"SetOCGState":const m=s.get("State"),b=s.get("PreserveRB");if(!Array.isArray(m)||0===m.length)break;const y=[];for(const e of m)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":y.push(e.name)}else e instanceof Ref&&y.push(e.toString());if(y.length!==m.length)break;t.setOCGState={state:y,preserveRB:"boolean"!=typeof b||b};break;case"JavaScript":const w=s.get("JS");let x;w instanceof BaseStream?x=w.getString():"string"==typeof w&&(x=w);const S=x&&recoverJsURL(stringToPDFString(x));if(S){i=S.url;t.newWindow=S.newWindow;break}default:if("JavaScript"===a||"SubmitForm"===a)break;warn(`parseDestDictionary - unsupported action: "${a}".`)}}else e.has("Dest")&&(n=e.get("Dest"));if("string"==typeof i){const e=createValidAbsoluteUrl(i,a,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=i}if(n){n instanceof Name&&(n=n.name);"string"==typeof n?t.dest=stringToPDFString(n):Array.isArray(n)&&(t.dest=n)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const r of e)((a=r)instanceof Ref||a instanceof Dict||a instanceof BaseStream||Array.isArray(a))&&t.push(r);var a}class ObjectLoader{constructor(e,t,a){this.dict=e;this.keys=t;this.xref=a;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const a=[];for(const r of e){const e=t.getRaw(r);void 0!==e&&a.push(e)}return this._walk(a)}async _walk(e){const t=[],a=[];for(;e.length;){let r=e.pop();if(r instanceof Ref){if(this.refSet.has(r))continue;try{this.refSet.put(r);r=this.xref.fetch(r)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(r);a.push({begin:e.begin,end:e.end})}}if(r instanceof BaseStream){const e=r.getBaseStreams();if(e){let i=!1;for(const t of e)if(!t.isDataLoaded){i=!0;a.push({begin:t.start,end:t.end})}i&&t.push(r)}}addChildren(r,e)}if(a.length){await this.xref.stream.manager.requestRanges(a);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const Pn=Symbol(),Ln=Symbol(),jn=Symbol(),_n=Symbol(),Un=Symbol(),Xn=Symbol(),qn=Symbol(),Hn=Symbol(),zn=Symbol(),Wn=Symbol("content"),$n=Symbol("data"),Gn=Symbol(),Vn=Symbol("extra"),Kn=Symbol(),Jn=Symbol(),Yn=Symbol(),Zn=Symbol(),Qn=Symbol(),es=Symbol(),ts=Symbol(),as=Symbol(),rs=Symbol(),is=Symbol(),ns=Symbol(),ss=Symbol(),os=Symbol(),cs=Symbol(),ls=Symbol(),hs=Symbol(),us=Symbol(),ds=Symbol(),fs=Symbol(),gs=Symbol(),ps=Symbol(),ms=Symbol(),bs=Symbol(),ys=Symbol(),ws=Symbol(),xs=Symbol(),Ss=Symbol(),ks=Symbol(),As=Symbol(),Cs=Symbol(),vs=Symbol(),Fs=Symbol(),Is=Symbol("namespaceId"),Os=Symbol("nodeName"),Ts=Symbol(),Ms=Symbol(),Ds=Symbol(),Bs=Symbol(),Rs=Symbol(),Ns=Symbol(),Es=Symbol(),Ls=Symbol(),js=Symbol("root"),_s=Symbol(),Us=Symbol(),Xs=Symbol(),qs=Symbol(),Hs=Symbol(),zs=Symbol(),Ws=Symbol(),$s=Symbol(),Gs=Symbol(),Vs=Symbol(),Ks=Symbol(),Js=Symbol("uid"),Ys=Symbol(),Zs={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},Qs={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},eo=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseInt(e,10);return!isNaN(r)&&a(r)?r:t}function getFloat({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseFloat(e);return!isNaN(r)&&a(r)?r:t}function getKeyword({data:e,defaultValue:t,validate:a}){return e&&a(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const a=e.trim().match(eo);if(!a)return getMeasurement(t);const[,r,i]=a,n=parseFloat(r);if(isNaN(n))return getMeasurement(t);if(0===n)return 0;const s=Qs[i];return s?s(n):n}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[a,r]=t;return{num:a,den:r}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,a,r){this.success=e;this.html=t;this.bbox=a;this.breakNode=r}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const a=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,a)}addPdfFont(e){const t=e.cssFontInfo,a=t.fontFamily;let r=this.fonts.get(a);if(!r){r=Object.create(null);this.fonts.set(a,r);this.defaultFont||(this.defaultFont=r)}let i="";const n=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?i=n>=700?"bolditalic":"italic":n>=700&&(i="bold");if(!i){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(i="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(i+="italic")}i||(i="regular");r[i]=e}getDefault(){return this.defaultFont}find(e,t=!0){let a=this.fonts.get(e)||this.cache.get(e);if(a)return a;const r=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let i=e.replaceAll(r,"");a=this.fonts.get(i);if(a){this.cache.set(e,a);return a}i=i.toLowerCase();const n=[];for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t);if(0===n.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(0===n.length){i=i.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t)}if(0===n.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(n.length>=1){1!==n.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,n[0]);return n[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,a,r){this.lineHeight=a;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(r);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const i=r.find(e.typeface);if(i){this.pdfFont=selectFont(e,i);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(r))}else[this.pdfFont,this.xfaFont]=this.defaultFont(r)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,a,r){this.fontFinder=r;this.stack=[new FontInfo(e,t,a,r)]}pushData(e,t,a){const r=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=r.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=r.paraMargin[e]);const i=new FontInfo(e,t,a||r.lineHeight,this.fontFinder);i.pdfFont||(i.pdfFont=r.pdfFont);this.stack.push(i)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,a,r){this.glyphs=[];this.fontSelector=new FontSelector(e,t,a,r);this.extraHeight=0}pushData(e,t,a){this.fontSelector.pushData(e,t,a)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),a=t.xfaFont.size;if(t.pdfFont){const r=t.xfaFont.letterSpacing,i=t.pdfFont,n=i.lineHeight||1.2,s=t.lineHeight||Math.max(1.2,n)*a,o=n-(void 0===i.lineGap?.2:i.lineGap),c=Math.max(1,o)*a,l=a/1e3,h=i.defaultWidth||i.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=i.encodeString(t).join(""),a=i.charsToGlyphs(e);for(const e of a){const t=e.width||h;this.glyphs.push([t*l+r,s,c,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([a,1.2*a,a,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,a=0,r=0,i=0,n=0,s=0,o=!1,c=!0;for(let l=0,h=this.glyphs.length;le){r=Math.max(r,n);n=0;i+=s;s=m;t=-1;a=0;o=!0;c=!1}else{s=Math.max(m,s);a=n;n+=h;t=l}else if(n+h>e){i+=s;s=m;if(-1!==t){l=t;r=Math.max(r,a);n=0;t=-1;a=0}else{r=Math.max(r,n);n=h}o=!0;c=!1}else{n+=h;s=Math.max(m,s)}}r=Math.max(r,n);i+=s+this.extraHeight;return{width:1.02*r,height:i,isBroken:o}}}const to=/^[^.[]+/,ao=/^[^\]]+/,ro={dot:0,dotDot:1,dotHash:2,dotBracket:3,dotParen:4},io=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[ss]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),no=new WeakMap;function parseExpression(e,t,a=!0){let r=e.match(to);if(!r)return null;let[i]=r;const n=[{name:i,cacheName:"."+i,index:0,js:null,formCalc:null,operator:ro.dot}];let s=i.length;for(;s0&&h.push(e)}if(0!==h.length||o||0!==c)e=isFinite(l)?h.filter((e=>le[l])):h.flat();else{const a=t[hs]();if(!(t=a))return null;c=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,a){const r=parseExpression(a);if(!r)return null;if(r.some((e=>e.operator===ro.dotDot)))return null;const i=io.get(r[0].name);let n=0;if(i){e=i(e,t);n=1}else e=t||e;for(let t=r.length;ne[Ws]())).join("")}get[co](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,co,e._attributes)}[xs](e){let t=this;for(;t;){if(t===e)return!0;t=t[hs]()}return!1}[hs](){return this[xo]}[ls](){return this[hs]()}[ss](e=null){return e?this[e]:this[lo]}[Gn](){const e=Object.create(null);this[Wn]&&(e.$content=this[Wn]);for(const t of Object.getOwnPropertyNames(this)){const a=this[t];null!==a&&(a instanceof XFAObject?e[t]=a[Gn]():a instanceof XFAObjectArray?a.isEmpty()||(e[t]=a.dump()):e[t]=a)}return e}[Ks](){return null}[Gs](){return HTMLResult.EMPTY}*[os](){for(const e of this[ss]())yield e}*[go](e,t){for(const a of this[os]())if(!e||t===e.has(a[Os])){const e=this[Qn](),t=a[Gs](e);t.success||(this[Vn].failingNode=a);yield t}}[Jn](){return null}[Ln](e,t){this[Vn].children.push(e)}[Qn](){}[_n]({filter:e=null,include:t=!0}){if(this[Vn].generator){const e=this[Qn](),t=this[Vn].failingNode[Gs](e);if(!t.success)return t;t.html&&this[Ln](t.html,t.bbox);delete this[Vn].failingNode}else this[Vn].generator=this[go](e,t);for(;;){const e=this[Vn].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ln](t.html,t.bbox)}this[Vn].generator=null;return HTMLResult.EMPTY}[qs](e){this[ko]=new Set(Object.keys(e))}[mo](e){const t=this[co],a=this[ko];return[...e].filter((e=>t.has(e)&&!a.has(e)))}[_s](e,t=new Set){for(const a of this[lo])a[So](e,t)}[So](e,t){const a=this[po](e,t);a?this[so](a,e,t):this[_s](e,t)}[po](e,t){const{use:a,usehref:r}=this;if(!a&&!r)return null;let i=null,n=null,s=null,o=a;if(r){o=r;r.startsWith("#som(")&&r.endsWith(")")?n=r.slice(5,-1):r.startsWith(".#som(")&&r.endsWith(")")?n=r.slice(6,-1):r.startsWith("#")?s=r.slice(1):r.startsWith(".#")&&(s=r.slice(2))}else a.startsWith("#")?s=a.slice(1):n=a;this.use=this.usehref="";if(s)i=e.get(s);else{i=searchNode(e.get(js),this,n,!0,!1);i&&(i=i[0])}if(!i){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(i[Os]!==this[Os]){warn(`XFA - Incompatible prototype: ${i[Os]} !== ${this[Os]}.`);return null}if(t.has(i)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(i);const c=i[po](e,t);c&&i[so](c,e,t);i[_s](e,t);t.delete(i);return i}[so](e,t,a){if(a.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Wn]&&e[Wn]&&(this[Wn]=e[Wn]);new Set(a).add(e);for(const t of this[mo](e[ko])){this[t]=e[t];this[ko]&&this[ko].add(t)}for(const r of Object.getOwnPropertyNames(this)){if(this[co].has(r))continue;const i=this[r],n=e[r];if(i instanceof XFAObjectArray){for(const e of i[lo])e[So](t,a);for(let r=i[lo].length,s=n[lo].length;rXFAObject[ho](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Hn](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Js]=`${e[Os]}${Co++}`;e[lo]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[co].has(t)){e[t]=XFAObject[ho](this[t]);continue}const a=this[t];e[t]=a instanceof XFAObjectArray?new XFAObjectArray(a[yo]):null}for(const t of this[lo]){const a=t[Os],r=t[Hn]();e[lo].push(r);r[xo]=e;null===e[a]?e[a]=r:e[a][lo].push(r)}return e}[ss](e=null){return e?this[lo].filter((t=>t[Os]===e)):this[lo]}[es](e){return this[e]}[ts](e,t,a=!0){return Array.from(this[as](e,t,a))}*[as](e,t,a=!0){if("parent"!==e){for(const a of this[lo]){a[Os]===e&&(yield a);a.name===e&&(yield a);(t||a[Cs]())&&(yield*a[as](e,t,!1))}a&&this[co].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[xo]}}class XFAObjectArray{constructor(e=1/0){this[yo]=e;this[lo]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[lo].length<=this[yo]){this[lo].push(e);return!0}warn(`XFA - node "${e[Os]}" accepts no more than ${this[yo]} children`);return!1}isEmpty(){return 0===this[lo].length}dump(){return 1===this[lo].length?this[lo][0][Gn]():this[lo].map((e=>e[Gn]()))}[Hn](){const e=new XFAObjectArray(this[yo]);e[lo]=this[lo].map((e=>e[Hn]()));return e}get children(){return this[lo]}clear(){this[lo].length=0}}class XFAAttribute{constructor(e,t,a){this[xo]=e;this[Os]=t;this[Wn]=a;this[zn]=!1;this[Js]="attribute"+Co++}[hs](){return this[xo]}[ws](){return!0}[rs](){return this[Wn].trim()}[Hs](e){e=e.value||"";this[Wn]=e.toString()}[Ws](){return this[Wn]}[xs](e){return this[xo]===e||this[xo][xs](e)}}class XmlObject extends XFAObject{constructor(e,t,a={}){super(e,t);this[Wn]="";this[uo]=null;if("#text"!==t){const e=new Map;this[oo]=e;for(const[t,r]of Object.entries(a))e.set(t,new XFAAttribute(this,t,r));if(a.hasOwnProperty(Ts)){const e=a[Ts].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[uo]=!1:"dataValue"===e&&(this[uo]=!0))}}this[zn]=!1}[Vs](e){const t=this[Os];if("#text"===t){e.push(encodeToXmlString(this[Wn]));return}const a=utf8StringToString(t),r=this[Is]===vo?"xfa:":"";e.push(`<${r}${a}`);for(const[t,a]of this[oo].entries()){const r=utf8StringToString(t);e.push(` ${r}="${encodeToXmlString(a[Wn])}"`)}null!==this[uo]&&(this[uo]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Wn]||0!==this[lo].length){e.push(">");if(this[Wn])"string"==typeof this[Wn]?e.push(encodeToXmlString(this[Wn])):this[Wn][Vs](e);else for(const t of this[lo])t[Vs](e);e.push(``)}else e.push("/>")}[Ms](e){if(this[Wn]){const e=new XmlObject(this[Is],"#text");this[jn](e);e[Wn]=this[Wn];this[Wn]=""}this[jn](e);return!0}[Bs](e){this[Wn]+=e}[Kn](){if(this[Wn]&&this[lo].length>0){const e=new XmlObject(this[Is],"#text");this[jn](e);e[Wn]=this[Wn];delete this[Wn]}}[Gs](){return"#text"===this[Os]?HTMLResult.success({name:"#text",value:this[Wn]}):HTMLResult.EMPTY}[ss](e=null){return e?this[lo].filter((t=>t[Os]===e)):this[lo]}[Zn](){return this[oo]}[es](e){const t=this[oo].get(e);return void 0!==t?t:this[ss](e)}*[as](e,t){const a=this[oo].get(e);a&&(yield a);for(const a of this[lo]){a[Os]===e&&(yield a);t&&(yield*a[as](e,t))}}*[Yn](e,t){const a=this[oo].get(e);!a||t&&a[zn]||(yield a);for(const a of this[lo])yield*a[Yn](e,t)}*[ns](e,t,a){for(const r of this[lo]){r[Os]!==e||a&&r[zn]||(yield r);t&&(yield*r[ns](e,t,a))}}[ws](){return null===this[uo]?0===this[lo].length||this[lo][0][Is]===Zs.xhtml.id:this[uo]}[rs](){return null===this[uo]?0===this[lo].length?this[Wn].trim():this[lo][0][Is]===Zs.xhtml.id?this[lo][0][Ws]().trim():null:this[Wn].trim()}[Hs](e){e=e.value||"";this[Wn]=e.toString()}[Gn](e=!1){const t=Object.create(null);e&&(t.$ns=this[Is]);this[Wn]&&(t.$content=this[Wn]);t.$name=this[Os];t.children=[];for(const a of this[lo])t.children.push(a[Gn](e));t.attributes=Object.create(null);for(const[e,a]of this[oo])t.attributes[e]=a[Wn];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Wn]=""}[Bs](e){this[Wn]+=e}[Kn](){}}class OptionObject extends ContentObject{constructor(e,t,a){super(e,t);this[wo]=a}[Kn](){this[Wn]=getKeyword({data:this[Wn],defaultValue:this[wo][0],validate:e=>this[wo].includes(e)})}[Un](e){super[Un](e);delete this[wo]}}class StringObject extends ContentObject{[Kn](){this[Wn]=this[Wn].trim()}}class IntegerObject extends ContentObject{constructor(e,t,a,r){super(e,t);this[fo]=a;this[Ao]=r}[Kn](){this[Wn]=getInteger({data:this[Wn],defaultValue:this[fo],validate:this[Ao]})}[Un](e){super[Un](e);delete this[fo];delete this[Ao]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Fo={anchorType(e,t){const a=e[ls]();if(a&&(!a.layout||"position"===a.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const a=e[ls]();let r=e.w;const i=e.h;if(a.layout?.includes("row")){const t=a[Vn],i=e.colSpan;let n;if(-1===i){n=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{n=t.columnWidths.slice(t.currentColumn,t.currentColumn+i).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(n)||(r=e.w=n)}t.width=""!==r?measureToString(r):"auto";t.height=""!==i?measureToString(i):"auto"},position(e,t){const a=e[ls]();if(!a?.layout||"position"===a.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Os])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Ks]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[ls]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,a,r,i,n){const s=new TextMeasure(t,a,r,i);"string"==typeof e?s.addString(e):e[Rs](s);return s.compute(n)}function layoutNode(e,t){let a=null,r=null,i=!1;if((!e.w||!e.h)&&e.value){let n=0,s=0;if(e.margin){n=e.margin.leftInset+e.margin.rightInset;s=e.margin.topInset+e.margin.bottomInset}let o=null,c=null;if(e.para){c=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;c.top=""===e.para.spaceAbove?0:e.para.spaceAbove;c.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;c.left=""===e.para.marginLeft?0:e.para.marginLeft;c.right=""===e.para.marginRight?0:e.para.marginRight}let l=e.font;if(!l){const t=e[us]();let a=e[hs]();for(;a&&a!==t;){if(a.font){l=a.font;break}a=a[hs]()}}const h=(e.w||t.width)-n,u=e[ds].fontFinder;if(e.value.exData&&e.value.exData[Wn]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Wn],l,c,o,u,h);r=t.width;a=t.height;i=t.isBroken}else{const t=e.value[Ws]();if(t){const e=layoutText(t,l,c,o,u,h);r=e.width;a=e.height;i=e.isBroken}}null===r||e.w||(r+=n);null===a||e.h||(a+=s)}return{w:r,h:a,isBroken:i}}function computeBbox(e,t,a){let r;if(""!==e.w&&""!==e.h)r=[e.x,e.y,e.w,e.h];else{if(!a)return null;let i=e.w;if(""===i){if(0===e.maxW){const t=e[ls]();i="position"===t.layout&&""!==t.w?0:e.minW}else i=Math.min(e.maxW,a.width);t.attributes.style.width=measureToString(i)}let n=e.h;if(""===n){if(0===e.maxH){const t=e[ls]();n="position"===t.layout&&""!==t.h?0:e.minH}else n=Math.min(e.maxH,a.height);t.attributes.style.height=measureToString(n)}r=[e.x,e.y,i,n]}return r}function fixDimensions(e){const t=e[ls]();if(t.layout?.includes("row")){const a=t[Vn],r=e.colSpan;let i;i=-1===r?a.columnWidths.slice(a.currentColumn).reduce(((e,t)=>e+t),0):a.columnWidths.slice(a.currentColumn,a.currentColumn+r).reduce(((e,t)=>e+t),0);isNaN(i)||(e.w=i)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const a=Object.create(null);for(const r of t){const t=e[r];if(null!==t)if(Fo.hasOwnProperty(r))Fo[r](e,a);else if(t instanceof XFAObject){const e=t[Ks]();e?Object.assign(a,e):warn(`(DEBUG) - XFA - style for ${r} not implemented yet`)}}return a}function createWrapper(e,t){const{attributes:a}=t,{style:r}=a,i={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};a.class.push("xfaWrapped");if(e.border){const{widths:a,insets:n}=e.border[Vn];let s,o,c=n[0],l=n[3];const h=n[0]+n[2],u=n[1]+n[3];switch(e.border.hand){case"even":c-=a[0]/2;l-=a[3]/2;s=`calc(100% + ${(a[1]+a[3])/2-u}px)`;o=`calc(100% + ${(a[0]+a[2])/2-h}px)`;break;case"left":c-=a[0];l-=a[3];s=`calc(100% + ${a[1]+a[3]-u}px)`;o=`calc(100% + ${a[0]+a[2]-h}px)`;break;case"right":s=u?`calc(100% - ${u}px)`:"100%";o=h?`calc(100% - ${h}px)`:"100%"}const d=["xfaBorder"];isPrintOnly(e.border)&&d.push("xfaPrintOnly");const f={name:"div",attributes:{class:d,style:{top:`${c}px`,left:`${l}px`,width:s,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==r[e]){f.attributes.style[e]=r[e];delete r[e]}i.children.push(f,t)}else i.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==r[e]){i.attributes.style[e]=r[e];delete r[e]}i.attributes.style.position="absolute"===r.position?"absolute":"relative";delete r.position;if(r.alignSelf){i.attributes.style.alignSelf=r.alignSelf;delete r.alignSelf}return i}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const a="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),r=getMeasurement(e[a],"0px");e[a]=r-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[us]()[Vn].paraStack;return t.length?t.at(-1):null}function setPara(e,t,a){if(a.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const r=getCurrentPara(e);if(r){const e=a.attributes.style;e.display="flex";e.flexDirection="column";switch(r.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=r[Ks]();for(const[a,r]of Object.entries(t))a in e||(e[a]=r)}}}function setFontFamily(e,t,a,r){if(!a){delete r.fontFamily;return}const i=stripQuotes(e.typeface);r.fontFamily=`"${i}"`;const n=a.find(i);if(n){const{fontFamily:a}=n.regular.cssFontInfo;a!==i&&(r.fontFamily=`"${a}"`);const s=getCurrentPara(t);if(s&&""!==s.lineHeight)return;if(r.lineHeight)return;const o=selectFont(e,n);o&&(r.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Vn])return null;const t={name:"div",attributes:e[Vn].attributes,children:e[Vn].children};if(e[Vn].failingNode){const a=e[Vn].failingNode[Jn]();a&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[a])):t.children.push(a))}return 0===t.children.length?null:t}function addHTML(e,t,a){const r=e[Vn],i=r.availableSpace,[n,s,o,c]=a;switch(e.layout){case"position":r.width=Math.max(r.width,n+o);r.height=Math.max(r.height,s+c);r.children.push(t);break;case"lr-tb":case"rl-tb":if(!r.line||1===r.attempt){r.line=createLine(e,[]);r.children.push(r.line);r.numberInLine=0}r.numberInLine+=1;r.line.children.push(t);if(0===r.attempt){r.currentWidth+=o;r.height=Math.max(r.height,r.prevHeight+c)}else{r.currentWidth=o;r.prevHeight=r.height;r.height+=c;r.attempt=0}r.width=Math.max(r.width,r.currentWidth);break;case"rl-row":case"row":{r.children.push(t);r.width+=o;r.height=Math.max(r.height,c);const e=measureToString(r.height);for(const t of r.children)t.attributes.style.height=e;break}case"table":case"tb":r.width=Math.min(i.width,Math.max(r.width,o));r.height+=c;r.children.push(t)}}function getAvailableSpace(e){const t=e[Vn].availableSpace,a=e.margin?e.margin.topInset+e.margin.bottomInset:0,r=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Vn].attempt?{width:t.width-r-e[Vn].currentWidth,height:t.height-a-e[Vn].prevHeight}:{width:t.width-r,height:t.height-a-e[Vn].height};case"rl-row":case"row":return{width:e[Vn].columnWidths.slice(e[Vn].currentColumn).reduce(((e,t)=>e+t)),height:t.height-r};case"table":case"tb":return{width:t.width-r,height:t.height-a-e[Vn].height};default:return t}}function checkDimensions(e,t){if(null===e[us]()[Vn].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const a=e[ls](),r=a[Vn]?.attempt||0,[,i,n,s]=function getTransformedBBox(e){let t,a,r=""===e.w?NaN:e.w,i=""===e.h?NaN:e.h,[n,s]=[0,0];switch(e.anchorType||""){case"bottomCenter":[n,s]=[r/2,i];break;case"bottomLeft":[n,s]=[0,i];break;case"bottomRight":[n,s]=[r,i];break;case"middleCenter":[n,s]=[r/2,i/2];break;case"middleLeft":[n,s]=[0,i/2];break;case"middleRight":[n,s]=[r,i/2];break;case"topCenter":[n,s]=[r/2,0];break;case"topRight":[n,s]=[r,0]}switch(e.rotate||0){case 0:[t,a]=[-n,-s];break;case 90:[t,a]=[-s,n];[r,i]=[i,-r];break;case 180:[t,a]=[n,s];[r,i]=[-r,-i];break;case 270:[t,a]=[s,-n];[r,i]=[-i,r]}return[e.x+t+Math.min(0,r),e.y+a+Math.min(0,i),Math.abs(r),Math.abs(i)]}(e);switch(a.layout){case"lr-tb":case"rl-tb":return 0===r?e[us]()[Vn].noLayoutFailure?""!==e.w?Math.round(n-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(s-t.height)>2)&&(""!==e.w?Math.round(n-t.width)<=2||0===a[Vn].numberInLine&&t.height>2:t.width>2):!!e[us]()[Vn].noLayoutFailure||!(""!==e.h&&Math.round(s-t.height)>2)&&((""===e.w||Math.round(n-t.width)<=2||!a[As]())&&t.height>2);case"table":case"tb":return!!e[us]()[Vn].noLayoutFailure||(""===e.h||e[ks]()?(""===e.w||Math.round(n-t.width)<=2||!a[As]())&&t.height>2:Math.round(s-t.height)<=2);case"position":if(e[us]()[Vn].noLayoutFailure)return!0;if(""===e.h||Math.round(s+i-t.height)<=2)return!0;return s+i>e[us]()[Vn].currentContentArea.h;case"rl-row":case"row":return!!e[us]()[Vn].noLayoutFailure||(""===e.h||Math.round(s-t.height)<=2);default:return!0}}const Io=Zs.template.id,Oo="http://www.w3.org/2000/svg",Mo=/^H(\d+)$/,Do=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),Bo=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[is]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[jn](t);e.value=t}e.value[Hs](t)}function*getContainedChildren(e){for(const t of e[ss]())t instanceof SubformSet?yield*t[os]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[zs]=e[hs]()[zs];return}if(e[zs])return;let t=null;for(const a of e.traversal[ss]())if("next"===a.operation){t=a;break}if(!t||!t.ref){e[zs]=e[hs]()[zs];return}const a=e[us]();e[zs]=++a[zs];const r=a[Us](t.ref,e);if(!r)return;e=r[0]}}function applyAssist(e,t){const a=e.assist;if(a){const e=a[Gs]();e&&(t.title=e);const r=a.role.match(Mo);if(r){const e="heading",a=r[1];t.role=e;t["aria-level"]=a}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const a=e[hs]();"row"===a.layout&&(t.role="TH"===a.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Wn]?t.speak[Wn]:t.toolTip?t.toolTip[Wn]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[us]();if(null===t[Vn].firstUnsplittable){t[Vn].firstUnsplittable=e;t[Vn].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[us]();t[Vn].firstUnsplittable===e&&(t[Vn].noLayoutFailure=!1)}function handleBreak(e){if(e[Vn])return!1;e[Vn]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[us]();let a=null;if(e.target){a=t[Us](e.target,e[hs]());if(!a)return!1;a=a[0]}const{currentPageArea:r,currentContentArea:i}=t[Vn];if("pageArea"===e.targetType){a instanceof PageArea||(a=null);if(e.startNew){e[Vn].target=a||r;return!0}if(a&&a!==r){e[Vn].target=a;return!0}return!1}a instanceof ContentArea||(a=null);const n=a&&a[hs]();let s,o=n;if(e.startNew)if(a){const e=n.contentArea.children,t=e.indexOf(i),r=e.indexOf(a);-1!==t&&te;r[Vn].noLayoutFailure=!0;const s=t[Gs](a);e[Ln](s.html,s.bbox);r[Vn].noLayoutFailure=i;t[ls]=n}class AppearanceFilter extends StringObject{constructor(e){super(Io,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Io,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Gs](){const e=this.edge||new Edge({}),t=e[Ks](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ks]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;let r;const i={xmlns:Oo,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)r={name:"ellipse",attributes:{xmlns:Oo,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:a}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,n=this.sweepAngle>180?1:0,[s,o,c,l]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];r={name:"path",attributes:{xmlns:Oo,d:`M ${s} ${o} A 50 50 0 ${n} 0 ${c} ${l}`,vectorEffect:"non-scaling-stroke",style:a}};Object.assign(i,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const n={name:"svg",children:[r],attributes:i};if(hasMargin(this[hs]()[hs]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[n]});n.attributes.style.position="absolute";return HTMLResult.success(n)}}class Area extends XFAObject{constructor(e){super(Io,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[os](){yield*getContainedChildren(this)}[Cs](){return!0}[ys](){return!0}[Ln](e,t){const[a,r,i,n]=t;this[Vn].width=Math.max(this[Vn].width,a+i);this[Vn].height=Math.max(this[Vn].height,r+n);this[Vn].children.push(e)}[Qn](){return this[Vn].availableSpace}[Gs](e){const t=toStyle(this,"position"),a={style:t,id:this[Js],class:["xfaArea"]};isPrintOnly(this)&&a.class.push("xfaPrintOnly");this.name&&(a.xfaName=this.name);const r=[];this[Vn]={children:r,width:0,height:0,availableSpace:e};const i=this[_n]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!i.success){if(i.isBreak())return i;delete this[Vn];return HTMLResult.FAILURE}t.width=measureToString(this[Vn].width);t.height=measureToString(this[Vn].height);const n={name:"div",attributes:a,children:r},s=[this.x,this.y,this[Vn].width,this[Vn].height];delete this[Vn];return HTMLResult.success(n,s)}}class Assist extends XFAObject{constructor(e){super(Io,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Gs](){return this.toolTip?.[Wn]||null}}class Barcode extends XFAObject{constructor(e){super(Io,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Io,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Io,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Io,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Io,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Gs](e){return valueToHtml(1===this[Wn]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Io,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[is](){if(!this[Vn]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let a=e.length;a<4;a++)e.push(t)}const t=e.map((e=>e.thickness)),a=[0,0,0,0];if(this.margin){a[0]=this.margin.topInset;a[1]=this.margin.rightInset;a[2]=this.margin.bottomInset;a[3]=this.margin.leftInset}this[Vn]={widths:t,insets:a,edges:e}}return this[Vn]}[Ks](){const{edges:e}=this[is](),t=e.map((e=>{const t=e[Ks]();t.color||="#000000";return t})),a=Object.create(null);this.margin&&Object.assign(a,this.margin[Ks]());"visible"===this.fill?.presence&&Object.assign(a,this.fill[Ks]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Ks]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let a=e.length;a<4;a++)e.push(t)}a.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":a.borderStyle="";break;case"inactive":a.borderStyle="none";break;default:a.borderStyle=t.map((e=>e.style)).join(" ")}a.borderWidth=t.map((e=>e.width)).join(" ");a.borderColor=t.map((e=>e.color)).join(" ");return a}}class Break extends XFAObject{constructor(e){super(Io,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Io,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Io,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Gs](e){this[Vn]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Io,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Gs](e){const t=this[hs]()[hs](),a={name:"button",attributes:{id:this[Js],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Wn]);if(!t)continue;const r=fixURL(t.url);r&&a.children.push({name:"a",attributes:{id:"link"+this[Js],href:r,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(a)}}class Calculate extends XFAObject{constructor(e){super(Io,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Io,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[Hs](e){_setValue(this,e)}[is](e){if(!this[Vn]){let{width:t,height:a}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":a=this.reserve<=0?a:this.reserve}this[Vn]=layoutNode(this,{width:t,height:a})}return this[Vn]}[Gs](e){if(!this.value)return HTMLResult.EMPTY;this[Es]();const t=this.value[Gs](e).html;if(!t){this[Ns]();return HTMLResult.EMPTY}const a=this.reserve;if(this.reserve<=0){const{w:t,h:a}=this[is](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=a}}const r=[];"string"==typeof t?r.push({name:"#text",value:t}):r.push(t);const i=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(i.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(i.height=measureToString(this.reserve))}setPara(this,null,t);this[Ns]();this.reserve=a;return HTMLResult.success({name:"div",attributes:{style:i,class:["xfaCaption"]},children:r})}}class Certificate extends StringObject{constructor(e){super(Io,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Io,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Io,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle("margin"),a=measureToString(this.size);t.width=t.height=a;let r,i,n;const s=this[hs]()[hs](),o=s.items.children.length&&s.items.children[0][Gs]().html||[],c={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},l=(s.value?.[Ws]()||"off")===c.on||void 0,h=s[ls](),u=s[Js];let d;if(h instanceof ExclGroup){n=h[Js];r="radio";i="xfaRadio";d=h[$n]?.[Js]||h[Js]}else{r="checkbox";i="xfaCheckbox";d=s[$n]?.[Js]||s[Js]}const f={name:"input",attributes:{class:[i],style:t,fieldId:u,dataId:d,type:r,checked:l,xfaOn:c.on,xfaOff:c.off,"aria-label":ariaLabel(s),"aria-required":!1}};n&&(f.attributes.name=n);if(isRequired(s)){f.attributes["aria-required"]=!0;f.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[f]})}}class ChoiceList extends XFAObject{constructor(e){super(Io,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","margin"),a=this[hs]()[hs](),r={fontSize:`calc(${a.font?.size||10}px * var(--scale-factor))`},i=[];if(a.items.children.length>0){const e=a.items;let t=0,n=0;if(2===e.children.length){t=e.children[0].save;n=1-t}const s=e.children[t][Gs]().html,o=e.children[n][Gs]().html;let c=!1;const l=a.value?.[Ws]()||"";for(let e=0,t=s.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(n.length<3)return{r:a,g:r,b:i};[a,r,i]=n;return{r:a,g:r,b:i}}(e.value):"";this.extras=null}[fs](){return!1}[Ks](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Io,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Io,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Io,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Gs](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},a=["xfaContentarea"];isPrintOnly(this)&&a.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:a,id:this[Js]}})}}class Corner extends XFAObject{constructor(e){super(Io,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Io,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Io,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Io,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin"),a=this[hs]()[hs](),r={name:"input",attributes:{type:"text",fieldId:a[Js],dataId:a[$n]?.[Js]||a[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Decimal extends ContentObject{constructor(e){super(Io,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseFloat(this[Wn].trim());this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Io,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Io,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Io,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Io,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Io,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[Hs](e){_setValue(this,e)}[Gs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Es]();const t=this.w,a=this.h,{w:r,h:i,isBroken:n}=layoutNode(this,e);if(r&&""===this.w){if(n&&this[ls]()[As]()){this[Ns]();return HTMLResult.FAILURE}this.w=r}i&&""===this.h&&(this.h=i);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=a;this[Ns]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const s=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,s);if(s.margin){s.padding=s.margin;delete s.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const c={style:s,id:this[Js],class:o};this.name&&(c.xfaName=this.name);const l={name:"div",attributes:c,children:[]};applyAssist(this,c);const h=computeBbox(this,l,e),u=this.value?this.value[Gs](e).html:null;if(null===u){this.w=t;this.h=a;this[Ns]();return HTMLResult.success(createWrapper(this,l),h)}l.children.push(u);setPara(this,s,u);this.w=t;this.h=a;this[Ns]();return HTMLResult.success(createWrapper(this,l),h)}}class Edge extends XFAObject{constructor(e){super(Io,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Ks]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Io,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Io,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Io,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Io,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Io,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Io,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Io,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Io,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Io,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[bs](){return"text/html"===this.contentType}[Ms](e){if("text/html"===this.contentType&&e[Is]===Zs.xhtml.id){this[Wn]=e;return!0}if("text/xml"===this.contentType){this[Wn]=e;return!0}return!1}[Gs](e){return"text/html"===this.contentType&&this[Wn]?this[Wn][Gs](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Io,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Io,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[ys](){return!0}[fs](){return!0}[Hs](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[jn](e);t.value=e}t.value[Hs](e)}}[As](){return this.layout.endsWith("-tb")&&0===this[Vn].attempt&&this[Vn].numberInLine>0||this[hs]()[As]()}[ks](){const e=this[ls]();if(!e[ks]())return!1;if(void 0!==this[Vn]._isSplittable)return this[Vn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Vn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Vn].numberInLine)return!1;this[Vn]._isSplittable=!0;return!0}[Jn](){return flushHTML(this)}[Ln](e,t){addHTML(this,e,t)}[Qn](){return getAvailableSpace(this)}[Gs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Js],class:[]};setAccess(this,a.class);this[Vn]||(this[Vn]=Object.create(null));Object.assign(this[Vn],{children:t,attributes:a,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[ks]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const i=new Set(["field"]);if(this.layout.includes("row")){const e=this[ls]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Vn].columnWidths=e;this[Vn].currentColumn=0}}const n=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),s=["xfaExclgroup"],o=layoutClass(this);o&&s.push(o);isPrintOnly(this)&&s.push("xfaPrintOnly");a.style=n;a.class=s;this.name&&(a.xfaName=this.name);this[Es]();const c="lr-tb"===this.layout||"rl-tb"===this.layout,l=c?2:1;for(;this[Vn].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[ys](){return!0}[Hs](e){_setValue(this,e)}[Gs](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[ds]=this[ds];this[jn](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[jn](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Vn];this[Es]();const t=this.caption?this.caption[Gs](e).html:null,a=this.w,r=this.h;let i=0,n=0;if(this.margin){i=this.margin.leftInset+this.margin.rightInset;n=this.margin.topInset+this.margin.bottomInset}let s=null;if(""===this.w||""===this.h){let t=null,a=null,r=0,o=0;if(this.ui.checkButton)r=o=this.ui.checkButton.size;else{const{w:t,h:a}=layoutNode(this,e);if(null!==t){r=t;o=a}else o=function fonts_getMetrics(e,t=!1){let a=null;if(e){const t=stripQuotes(e.typeface),r=e[ds].fontFinder.find(t);a=selectFont(e,r)}if(!a)return{lineHeight:12,lineGap:2,lineNoGap:10};const r=e.size||10,i=a.lineHeight?Math.max(t?0:1.2,a.lineHeight):1.2,n=void 0===a.lineGap?.2:a.lineGap;return{lineHeight:i*r,lineGap:n*r,lineNoGap:Math.max(1,i-n)*r}}(this.font,!0).lineNoGap}s=getBorderDims(this.ui[is]());r+=s.w;o+=s.h;if(this.caption){const{w:i,h:n,isBroken:s}=this.caption[is](e);if(s&&this[ls]()[As]()){this[Ns]();return HTMLResult.FAILURE}t=i;a=n;switch(this.caption.placement){case"left":case"right":case"inline":t+=r;break;case"top":case"bottom":a+=o}}else{t=r;a=o}if(t&&""===this.w){t+=i;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Io,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseFloat(this[Wn].trim());this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Io,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Un](e){super[Un](e);this[ds].usedTypefaces.add(this.typeface)}[Ks](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[ds].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Io,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Io,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Io,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Io,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Gs](){if(this.contentType&&!Do.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[ds].images&&this[ds].images.get(this.href);if(!e&&(this.href||!this[Wn]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=stringToBytes(atob(this[Wn])));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,a]of Bo)if(e.length>t.length&&t.every(((t,a)=>t===e[a]))){this.contentType=a;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let a;switch(this.aspect){case"fit":case"actual":break;case"height":a={height:"100%",objectFit:"fill"};break;case"none":a={width:"100%",height:"100%",objectFit:"fill"};break;case"width":a={width:"100%",objectFit:"fill"}}const r=this[hs]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:a,src:URL.createObjectURL(t),alt:r?ariaLabel(r[hs]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Io,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Io,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseInt(this[Wn].trim(),10);this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Io,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Io,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Gs](){const e=[];for(const t of this[ss]())e.push(t[Ws]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Io,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Io,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Io,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Gs](){const e=this[hs]()[hs](),t=this.edge||new Edge({}),a=t[Ks](),r=Object.create(null),i="visible"===t.presence?t.thickness:0;r.strokeWidth=measureToString(i);r.stroke=a.color;let n,s,o,c,l="100%",h="100%";if(e.w<=i){[n,s,o,c]=["50%",0,"50%","100%"];l=r.strokeWidth}else if(e.h<=i){[n,s,o,c]=[0,"50%","100%","50%"];h=r.strokeWidth}else"\\"===this.slope?[n,s,o,c]=[0,0,"100%","100%"]:[n,s,o,c]=[0,"100%","100%",0];const u={name:"svg",children:[{name:"line",attributes:{xmlns:Oo,x1:n,y1:s,x2:o,y2:c,style:r}}],attributes:{xmlns:Oo,width:l,height:h,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[u]});u.attributes.style.position="absolute";return HTMLResult.success(u)}}class Linear extends XFAObject{constructor(e){super(Io,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Ks]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Io,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){this[Wn]=getStringOption(this[Wn],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Io,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Io,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Io,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Io,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const a=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(a.length<4||a[2]<0||a[3]<0)return{x:t,y:t,width:t,height:t};const[r,i,n,s]=a;return{x:r,y:i,width:n,height:s}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Io,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Io,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin"),a=this[hs]()[hs](),r={name:"input",attributes:{type:"text",fieldId:a[Js],dataId:a[$n]?.[Js]||a[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Occur extends XFAObject{constructor(e){super(Io,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Un](){const e=this[hs](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[vs](){if(!this[Vn]){this[Vn]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Vn].numberOfUsee.oddOrEven===t&&e.pagePosition===a));if(r)return r;r=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===a));if(r)return r;r=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return r||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Io,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Ks](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Ks]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Io,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Io,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";const t=this.color?this.color[Ks]():"#000000",a="repeating-linear-gradient",r=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${a}(to top,${r}) ${a}(to right,${r})`;case"crossDiagonal":return`${a}(45deg,${r}) ${a}(-45deg,${r})`;case"diagonalLeft":return`${a}(45deg,${r})`;case"diagonalRight":return`${a}(-45deg,${r})`;case"horizontal":return`${a}(to top,${r})`;case"vertical":return`${a}(to right,${r})`}return""}}class Picture extends StringObject{constructor(e){super(Io,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Io,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Io,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";const t=this.color?this.color[Ks]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Io,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Io,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Io,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Gs](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Ks](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ks]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;const r=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Ks](),i={name:"svg",children:[{name:"rect",attributes:{xmlns:Oo,width:"100%",height:"100%",x:0,y:0,rx:r.radius,ry:r.radius,style:a}}],attributes:{xmlns:Oo,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[hs]()[hs]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[i]});i.attributes.style.position="absolute";return HTMLResult.success(i)}}class RefElement extends StringObject{constructor(e){super(Io,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Io,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Io,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Io,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Io,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Io,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Io,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](e){return e?e[Ks]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Io,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Io,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Io,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[ls](){const e=this[hs]();return e instanceof SubformSet?e[ls]():e}[ys](){return!0}[As](){return this.layout.endsWith("-tb")&&0===this[Vn].attempt&&this[Vn].numberInLine>0||this[hs]()[As]()}*[os](){yield*getContainedChildren(this)}[Jn](){return flushHTML(this)}[Ln](e,t){addHTML(this,e,t)}[Qn](){return getAvailableSpace(this)}[ks](){const e=this[ls]();if(!e[ks]())return!1;if(void 0!==this[Vn]._isSplittable)return this[Vn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Vn]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Vn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Vn].numberInLine)return!1;this[Vn]._isSplittable=!0;return!0}[Gs](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[ds]=this[ds];this[jn](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[ds]=this[ds];this[jn](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[ds]=this[ds];this[jn](e);this.overflow.push(e)}this[Ls](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Vn]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Js],class:[]};setAccess(this,a.class);this[Vn]||(this[Vn]=Object.create(null));Object.assign(this[Vn],{children:t,line:null,attributes:a,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[us](),i=r[Vn].noLayoutFailure,n=this[ks]();n||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[ls]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Vn].columnWidths=e;this[Vn].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),c=["xfaSubform"],l=layoutClass(this);l&&c.push(l);a.style=o;a.class=c;this.name&&(a.xfaName=this.name);if(this.overflow){const t=this.overflow[is]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Es]();const h="lr-tb"===this.layout||"rl-tb"===this.layout,u=h?2:1;for(;this[Vn].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Vn].afterBreakAfter=y;return HTMLResult.breakNode(e)}}delete this[Vn];return y}}class SubformSet extends XFAObject{constructor(e){super(Io,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[os](){yield*getContainedChildren(this)}[ls](){let e=this[hs]();for(;!(e instanceof Subform);)e=e[hs]();return e}[ys](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Io,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){this[Wn]=new Map(this[Wn].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Io,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Io,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Io,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Kn](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[zs]=5e3}[ks](){return!0}[Us](e,t){return e.startsWith("#")?[this[gs].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[$s](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Vn]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[Xn]();const t=e.pageSet.pageArea.children,a={name:"div",children:[]};let r=null,i=null,n=null;if(e.breakBefore.children.length>=1){i=e.breakBefore.children[0];n=i.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){i=e.subform.children[0].breakBefore.children[0];n=i.target}else if(e.break?.beforeTarget){i=e.break;n=i.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){i=e.subform.children[0].break;n=i.beforeTarget}if(i){const e=this[Us](n,i[hs]());if(e instanceof PageArea){r=e;i[Vn]={}}}r||(r=t[0]);r[Vn]={numberOfUse:1};const s=r[hs]();s[Vn]={numberOfUse:1,pageIndex:s.pageArea.children.indexOf(r),pageSetIndex:0};let o,c=null,l=null,h=!0,u=0,d=0;for(;;){if(h)u=0;else{a.children.pop();if(3==++u){warn("XFA - Something goes wrong: please file a bug.");return a}}o=null;this[Vn].currentPageArea=r;const t=r[Gs]().html;a.children.push(t);if(c){this[Vn].noLayoutFailure=!0;t.children.push(c[Gs](r[Vn].space).html);c=null}if(l){this[Vn].noLayoutFailure=!0;t.children.push(l[Gs](r[Vn].space).html);l=null}const i=r.contentArea.children,n=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));h=!1;this[Vn].firstUnsplittable=null;this[Vn].noLayoutFailure=!1;const flush=t=>{const a=e[Jn]();if(a){h||=a.children?.length>0;n[t].children.push(a)}};for(let t=d,r=i.length;t0;n[t].children.push(u.html)}else!h&&a.children.length>1&&a.children.pop();return a}if(u.isBreak()){const e=u.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){c=this[Us](e.leader,e[hs]());c=c?c[0]:null}if(e.trailer){l=this[Us](e.trailer,e[hs]());l=l?l[0]:null}if("pageArea"===e.targetType){o=e[Vn].target;t=1/0}else if(e[Vn].target){o=e[Vn].target;d=e[Vn].index+1;t=1/0}else t=e[Vn].index}else if(this[Vn].overflowNode){const e=this[Vn].overflowNode;this[Vn].overflowNode=null;const a=e[is](),r=a.target;a.addLeader=null!==a.leader;a.addTrailer=null!==a.trailer;flush(t);const n=t;t=1/0;if(r instanceof PageArea)o=r;else if(r instanceof ContentArea){const e=i.indexOf(r);if(-1!==e)e>n?t=e-1:d=e;else{o=r[hs]();d=o.contentArea.children.indexOf(r)}}}else flush(t)}this[Vn].pageNumber+=1;o&&(o[vs]()?o[Vn].numberOfUse+=1:o=null);r=o||r[cs]();yield null}}}class Text extends ContentObject{constructor(e){super(Io,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[Pn](){return!0}[Ms](e){if(e[Is]===Zs.xhtml.id){this[Wn]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Os]}.`);return!1}[Bs](e){this[Wn]instanceof XFAObject||super[Bs](e)}[Kn](){"string"==typeof this[Wn]&&(this[Wn]=this[Wn].replaceAll("\r\n","\n"))}[is](){return"string"==typeof this[Wn]?this[Wn].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Wn][Ws]()}[Gs](e){if("string"==typeof this[Wn]){const e=valueToHtml(this[Wn]).html;if(this[Wn].includes("\u2029")){e.name="div";e.children=[];this[Wn].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Wn])){e.name="div";e.children=[];this[Wn].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Wn][Gs](e)}}class TextEdit extends XFAObject{constructor(e){super(Io,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin");let a;const r=this[hs]()[hs]();""===this.multiLine&&(this.multiLine=r instanceof Draw?1:0);a=1===this.multiLine?{name:"textarea",attributes:{dataId:r[$n]?.[Js]||r[Js],fieldId:r[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:r[$n]?.[Js]||r[Js],fieldId:r[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}};if(isRequired(r)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Time extends StringObject{constructor(e){super(Io,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Io,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Io,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Io,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Io,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Cs](){return!1}}class Ui extends XFAObject{constructor(e){super(Io,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[is](){if(void 0===this[Vn]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Vn]=t;return t}}this[Vn]=null}return this[Vn]}[Gs](e){const t=this[is]();return t?t[Gs](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Io,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Io,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[Hs](e){const t=this[hs]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[jn](this.image)}this.image[Wn]=e[Wn];return}const a=e[Os];if(null===this[a]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Ls](t)}}this[e[Os]]=e;this[jn](e)}else this[a][Wn]=e[Wn]}[Ws](){if(this.exData)return"string"==typeof this.exData[Wn]?this.exData[Wn].trim():this.exData[Wn][Ws]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Wn]||"").toString().trim()}return null}[Gs](e){for(const t of Object.getOwnPropertyNames(this)){const a=this[t];if(a instanceof XFAObject)return a[Gs](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Io,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Cs](){return!0}}class TemplateNamespace{static[Ys](e,t){if(TemplateNamespace.hasOwnProperty(e)){const a=TemplateNamespace[e](t);a[qs](t);return a}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ro=Zs.datasets.id;function createText(e){const t=new Text({});t[Wn]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(Zs.datasets.id,"data");this.emptyMerge=0===this.data[ss]().length;this.root.form=this.form=e.template[Hn]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,a){e[$n]=t;if(e[fs]())if(t[ws]()){const a=t[rs]();e[Hs](createText(a))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const a=t[ss]().map((e=>e[Wn].trim())).join("\n");e[Hs](createText(a))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[ws]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,a,r){if(!e)return null;let i,n;for(let r=0;r<3;r++){i=a[ns](e,!1,!0);for(;;){n=i.next().value;if(!n)break;if(t===n[ws]())return n}if(a[Is]===Zs.datasets.id&&"data"===a[Os])break;a=a[hs]()}if(!r)return null;i=this.data[ns](e,!0,!1);n=i.next().value;if(n)return n;i=this.data[Yn](e,!0);n=i.next().value;return n?.[ws]()?n:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:a,target:r,connection:i}of e.setProperty.children){if(i)continue;if(!a)continue;const n=searchNode(this.root,t,a,!1,!1);if(!n){warn(`XFA - Invalid reference: ${a}.`);continue}const[s]=n;if(!s[xs](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,r,!1,!1);if(!o){warn(`XFA - Invalid target: ${r}.`);continue}const[c]=o;if(!c[xs](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const l=c[hs]();if(c instanceof SetProperty||l instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(c instanceof BindItems||l instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const h=s[Ws](),u=c[Os];if(c instanceof XFAAttribute){const e=Object.create(null);e[u]=h;const t=Reflect.construct(Object.getPrototypeOf(l).constructor,[e]);l[u]=t[u]}else if(c.hasOwnProperty(Wn)){c[$n]=s;c[Wn]=h;c[Kn]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Ls](t);e.items.clear();const a=new Items({}),r=new Items({});e[jn](a);e.items.push(a);e[jn](r);e.items.push(r);for(const{ref:i,labelRef:n,valueRef:s,connection:o}of e.bindItems.children){if(o)continue;if(!i)continue;const e=searchNode(this.root,t,i,!1,!1);if(e)for(const t of e){if(!t[xs](this.datasets)){warn(`XFA - Invalid ref (${i}): must be a datasets child.`);continue}const e=searchNode(this.root,t,n,!0,!1);if(!e){warn(`XFA - Invalid label: ${n}.`);continue}const[o]=e;if(!o[xs](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const c=searchNode(this.root,t,s,!0,!1);if(!c){warn(`XFA - Invalid value: ${s}.`);continue}const[l]=c;if(!l[xs](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const h=createText(o[Ws]()),u=createText(l[Ws]());a[jn](h);a.text.push(h);r[jn](u);r.text.push(u)}else warn(`XFA - Invalid reference: ${i}.`)}}_bindOccurrences(e,t,a){let r;if(t.length>1){r=e[Hn]();r[Ls](r.occur);r.occur=null}this._bindValue(e,t[0],a);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const i=e[hs](),n=e[Os],s=i[ps](e);for(let e=1,o=t.length;et.name===e.name)).length:a[r].children.length;const n=a[ps](e)+1,s=t.initial-i;if(s){const t=e[Hn]();t[Ls](t.occur);t.occur=null;a[r].push(t);a[ms](n,t);for(let e=1;e0)this._bindOccurrences(r,[e[0]],null);else if(this.emptyMerge){const e=t[Is]===Ro?-1:t[Is],a=r[$n]=new XmlObject(e,r.name||"root");t[jn](a);this._bindElement(r,a)}continue}if(!r[ys]())continue;let e=!1,i=null,n=null,s=null;if(r.bind){switch(r.bind.match){case"none":this._setAndBind(r,t);continue;case"global":e=!0;break;case"dataRef":if(!r.bind.ref){warn(`XFA - ref is empty in node ${r[Os]}.`);this._setAndBind(r,t);continue}n=r.bind.ref}r.bind.picture&&(i=r.bind.picture[Wn])}const[o,c]=this._getOccurInfo(r);if(n){s=searchNode(this.root,t,n,!0,!1);if(null===s){s=createDataNode(this.data,t,n);if(!s)continue;this._isConsumeData()&&(s[zn]=!0);this._setAndBind(r,s);continue}this._isConsumeData()&&(s=s.filter((e=>!e[zn])));s.length>c?s=s.slice(0,c):0===s.length&&(s=null);s&&this._isConsumeData()&&s.forEach((e=>{e[zn]=!0}))}else{if(!r.name){this._setAndBind(r,t);continue}if(this._isConsumeData()){const a=[];for(;a.length0?a:null}else{s=t[ns](r.name,!1,this.emptyMerge).next().value;if(!s){if(0===o){a.push(r);continue}const e=t[Is]===Ro?-1:t[Is];s=r[$n]=new XmlObject(e,r.name);this.emptyMerge&&(s[zn]=!0);t[jn](s);this._setAndBind(r,s);continue}this.emptyMerge&&(s[zn]=!0);s=[s]}}s?this._bindOccurrences(r,s,i):o>0?this._setAndBind(r,t):a.push(r)}a.forEach((e=>e[hs]()[Ls](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[ss]()]];for(;t.length>0;){const a=t.at(-1),[r,i]=a;if(r+1===i.length){t.pop();continue}const n=i[++a[0]],s=e.get(n[Js]);if(s)n[Hs](s);else{const t=n[Zn]();for(const a of t.values()){const t=e.get(a[Js]);if(t){a[Hs](t);break}}}const o=n[ss]();o.length>0&&t.push([-1,o])}const a=[''];if(this.dataset)for(const e of this.dataset[ss]())"data"!==e[Os]&&e[Vs](a);this.data[Vs](a);a.push("");return a.join("")}}const No=Zs.config.id;class Acrobat extends XFAObject{constructor(e){super(No,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(No,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(No,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(No,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(No,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(No,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(No,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(No,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(No,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(No,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(No,"amd")}}class config_Area extends XFAObject{constructor(e){super(No,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(No,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(No,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(No,"base")}}class BatchOutput extends XFAObject{constructor(e){super(No,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(No,"behaviorOverride")}[Kn](){this[Wn]=new Map(this[Wn].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(No,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(No,"change")}}class Common extends XFAObject{constructor(e){super(No,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(No,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(No,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(No,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(No,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(No,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(No,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(No,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(No,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(No,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(No,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(No,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(No,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(No,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(No,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(No,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(No,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(No,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(No,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(No,"embed")}}class config_Encrypt extends Option01{constructor(e){super(No,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(No,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(No,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(No,"enforce")}}class Equate extends XFAObject{constructor(e){super(No,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(No,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,a=this._unicodeRange;for(let r of a.split(",").map((e=>e.trim())).filter((e=>!!e))){r=r.split("-",2).map((e=>{const a=e.match(t);return a?parseInt(a[1],16):0}));1===r.length&&r.push(r[0]);e.push(r)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(No,"exclude")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(No,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(No,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(No,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(No,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(No,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(No,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(No,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(No,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(No,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(No,"interactive")}}class Jog extends OptionObject{constructor(e){super(No,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(No,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(No,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(No,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(No,"linearized")}}class Locale extends StringObject{constructor(e){super(No,"locale")}}class LocaleSet extends StringObject{constructor(e){super(No,"localeSet")}}class Log extends XFAObject{constructor(e){super(No,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(No,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(No,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(No,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(No,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(No,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(No,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(No,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(No,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(No,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(No,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(No,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(No,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(No,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(No,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(No,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(No,"packets")}[Kn](){"*"!==this[Wn]&&(this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(No,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(No,"pageRange")}[Kn](){const e=this[Wn].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let a=0,r=e.length;a!1))}}class Pcl extends XFAObject{constructor(e){super(No,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(No,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(No,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(No,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(No,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(No,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(No,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(No,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(No,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(No,"print")}}class PrintHighQuality extends Option01{constructor(e){super(No,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(No,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(No,"printerName")}}class Producer extends StringObject{constructor(e){super(No,"producer")}}class Ps extends XFAObject{constructor(e){super(No,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(No,"range")}[Kn](){this[Wn]=this[Wn].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(No,"record")}[Kn](){this[Wn]=this[Wn].trim();const e=parseInt(this[Wn],10);!isNaN(e)&&e>=0&&(this[Wn]=e)}}class Relevant extends ContentObject{constructor(e){super(No,"relevant")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(No,"rename")}[Kn](){this[Wn]=this[Wn].trim();(this[Wn].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Wn]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(No,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(No,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(No,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(No,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(No,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(No,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(No,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(No,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(No,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(No,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(No,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(No,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(No,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(No,"tagged")}}class config_Template extends XFAObject{constructor(e){super(No,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(No,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(No,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(No,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(No,"trace",!0);this.area=new XFAObjectArray}}class config_Transform extends XFAObject{constructor(e){super(No,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(No,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(No,"uri")}}class config_Validate extends OptionObject{constructor(e){super(No,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(No,"validateApprovalSignatures")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(No,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(No,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(No,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(No,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(No,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(No,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(No,"window")}[Kn](){const e=this[Wn].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Wn]=[0,0];else{1===e.length&&e.push(e[0]);this[Wn]=e}}}class Xdc extends XFAObject{constructor(e){super(No,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(No,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(No,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(No,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[Ys](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new config_Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Eo=Zs.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Eo,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Eo,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Eo,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Eo,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Eo,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Eo,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Eo,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Eo,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Eo,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Eo,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Eo,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Eo,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[Ys](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Po=Zs.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Po,"data",e)}[Ss](){return!0}}class Datasets extends XFAObject{constructor(e){super(Po,"datasets",!0);this.data=null;this.Signature=null}[Ms](e){const t=e[Os];("data"===t&&e[Is]===Po||"Signature"===t&&e[Is]===Zs.signature.id)&&(this[t]=e);this[jn](e)}}class DatasetsNamespace{static[Ys](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Lo=Zs.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Lo,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Lo,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Lo,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Lo,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Lo,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Lo,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Lo,"day")}}class DayNames extends XFAObject{constructor(e){super(Lo,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Lo,"era")}}class EraNames extends XFAObject{constructor(e){super(Lo,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Lo,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Lo,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Lo,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Lo,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Lo,"month")}}class MonthNames extends XFAObject{constructor(e){super(Lo,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Lo,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Lo,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Lo,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Lo,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Lo,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Lo,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Lo,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Lo,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[Ys](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const jo=Zs.signature.id;class signature_Signature extends XFAObject{constructor(e){super(jo,"signature",!0)}}class SignatureNamespace{static[Ys](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const _o=Zs.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(_o,"stylesheet",!0)}}class StylesheetNamespace{static[Ys](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const Uo=Zs.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(Uo,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Ds](e){const t=Zs[e[Os]];return t&&e[Is]===t.id}}class XdpNamespace{static[Ys](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const Xo=Zs.xhtml.id,qo=Symbol(),Ho=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),zo=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=getMeasurement(e)))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Wo=/\s+/g,$o=/[\r\n]+/g,Go=/\r\n?/g;function mapStyle(e,t,a){const r=Object.create(null);if(!e)return r;const i=Object.create(null);for(const[t,a]of e.split(";").map((e=>e.split(":",2)))){const e=zo.get(t);if(""===e)continue;let n=a;e&&(n="string"==typeof e?e:e(a,i));t.endsWith("scale")?r.transform=r.transform?`${r[t]} ${n}`:n:r[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=n}r.fontFamily&&setFontFamily({typeface:r.fontFamily,weight:r.fontWeight||"normal",posture:r.fontStyle||"normal",size:i.fontSize||0},t,t[ds].fontFinder,r);if(a&&r.verticalAlign&&"0px"!==r.verticalAlign&&r.fontSize){const e=.583,t=.333,a=getMeasurement(r.fontSize);r.fontSize=measureToString(a*e);r.verticalAlign=measureToString(Math.sign(getMeasurement(r.verticalAlign))*a*t)}a&&r.fontSize&&(r.fontSize=`calc(${r.fontSize} * var(--scale-factor))`);fixTextIndent(r);return r}const Vo=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(Xo,t);this[qo]=!1;this.style=e.style||""}[Un](e){super[Un](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,a])=>{"font-family"===t&&e[ds].usedTypefaces.add(a);return Ho.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[Pn](){return!Vo.has(this[Os])}[Bs](e,t=!1){if(t)this[qo]=!0;else{e=e.replaceAll($o,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Wo," "))}e&&(this[Wn]+=e)}[Rs](e,t=!0){const a=Object.create(null),r={top:NaN,bottom:NaN,left:NaN,right:NaN};let i=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":a.typeface=stripQuotes(t);break;case"font-size":a.size=getMeasurement(t);break;case"font-weight":a.weight=t;break;case"font-style":a.posture=t;break;case"letter-spacing":a.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:r.top=r.bottom=r.left=r.right=e[0];break;case 2:r.top=r.bottom=e[0];r.left=r.right=e[1];break;case 3:r.top=e[0];r.bottom=e[2];r.left=r.right=e[1];break;case 4:r.top=e[0];r.left=e[1];r.bottom=e[2];r.right=e[3]}break;case"margin-top":r.top=getMeasurement(t);break;case"margin-bottom":r.bottom=getMeasurement(t);break;case"margin-left":r.left=getMeasurement(t);break;case"margin-right":r.right=getMeasurement(t);break;case"line-height":i=getMeasurement(t)}e.pushData(a,r,i);if(this[Wn])e.addString(this[Wn]);else for(const t of this[ss]())"#text"!==t[Os]?t[Rs](e):e.addString(t[Wn]);t&&e.popFont()}[Gs](e){const t=[];this[Vn]={children:t};this[_n]({});if(0===t.length&&!this[Wn])return HTMLResult.EMPTY;let a;a=this[qo]?this[Wn]?this[Wn].replaceAll(Go,"\n"):void 0:this[Wn]||void 0;return HTMLResult.success({name:this[Os],attributes:{href:this.href,style:mapStyle(this.style,this,this[qo])},children:t,value:a})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Rs](e){e.pushFont({weight:"bold"});super[Rs](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Gs](e){const t=super[Gs](e),{html:a}=t;if(!a)return HTMLResult.EMPTY;a.name="div";a.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Ws](){return"\n"}[Rs](e){e.addString("\n")}[Gs](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Gs](e){const t=[];this[Vn]={children:t};this[_n]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Wn]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Rs](e){e.pushFont({posture:"italic"});super[Rs](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Rs](e){super[Rs](e,!1);e.addString("\n");e.addPara();e.popFont()}[Ws](){return this[hs]()[ss]().at(-1)===this?super[Ws]():super[Ws]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[Ys](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const Ko={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[Ys](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[gs]=e}[Ms](e){this.element=e;return!0}[Kn](){super[Kn]();if(this.element.template instanceof Template){this[gs].set(js,this.element);this.element.template[_s](this[gs]);this.element.template[gs]=this[gs]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Ms](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(Zs).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:a,namespace:r,prefixes:i}){const n=null!==r;if(n){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(r)}i&&this._addNamespacePrefix(i);if(a.hasOwnProperty(Ts)){const e=Ko.datasets,t=a[Ts];let r=null;for(const[a,i]of Object.entries(t)){if(this._getNamespaceToUse(a)===e){r={xfa:i};break}}r?a[Ts]=r:delete a[Ts]}const s=this._getNamespaceToUse(e),o=s?.[Ys](t,a)||new Empty;o[Ss]()&&this._nsAgnosticLevel++;(n||i||o[Ss]())&&(o[qn]={hasNamespace:n,prefixes:i,nsAgnostic:o[Ss]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[a,{check:r}]of Object.entries(Zs))if(r(e)){t=Ko[a];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:a}of e){const e=this._searchNamespace(a);let r=this._namespacePrefixes.get(t);if(!r){r=[];this._namespacePrefixes.set(t,r)}r.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:a,nsAgnostic:r}=e;t&&(this._currentNamespace=this._namespaceStack.pop());a&&a.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));r&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=Sn;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===Sn){this._current[Kn]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[Pn]()?this._current[Bs](e,this._richText):this._whiteRegex.test(e)||this._current[Bs](e.trim())}onCdata(e){this._current[Bs](e)}_mkAttributes(e,t){let a=null,r=null;const i=Object.create({});for(const{name:n,value:s}of e)if("xmlns"===n)a?warn(`XFA - multiple namespace definition in <${t}>`):a=s;else if(n.startsWith("xmlns:")){const e=n.substring(6);r||(r=[]);r.push({prefix:e,value:s})}else{const e=n.indexOf(":");if(-1===e)i[n]=s;else{let t=i[Ts];t||(t=i[Ts]=Object.create(null));const[a,r]=[n.slice(0,e),n.slice(e+1)];(t[a]||=Object.create(null))[r]=s}}return[a,r,i]}_getNameAndPrefix(e,t){const a=e.indexOf(":");return-1===a?[e,null]:[e.substring(a+1),t?"":e.substring(0,a)]}onBeginElement(e,t,a){const[r,i,n]=this._mkAttributes(t,e),[s,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),c=this._builder.build({nsPrefix:o,name:s,attributes:n,namespace:r,prefixes:i});c[ds]=this._globalData;if(a){c[Kn]();this._current[Ms](c)&&c[Xs](this._ids);c[Un](this._builder)}else{this._stack.push(this._current);this._current=c}}onEndElement(e){const t=this._current;if(t[bs]()&&"string"==typeof t[Wn]){const e=new XFAParser;e._globalData=this._globalData;const a=e.parse(t[Wn]);t[Wn]=null;t[Ms](a)}t[Kn]();this._current=this._stack.pop();this._current[Ms](t)&&t[Xs](this._ids);t[Un](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[ds].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[$s]();return new Promise(((t,a)=>{const nextIteration=()=>{try{const a=e.next();a.done?t(a.value):setTimeout(nextIteration,0)}catch(e){a(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:a}=e.attributes.style;return[0,0,parseInt(t),parseInt(a)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[ds].images=e}setFonts(e){this.form[ds].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[ds].usedTypefaces){e=stripQuotes(e);this.form[ds].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[ds].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Os])){const e=XhtmlNamespace.body({});e[jn](t);t=e}const a=t[Gs]();if(!a.success)return null;const{html:r}=a,{attributes:i}=r;if(i){i.class&&(i.class=i.class.filter((e=>!e.startsWith("xfa"))));i.dir="auto"}return{html:r,str:t[Ws]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,a,r,i,n])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:a,structTreeRoot:r,baseUrl:i,attachments:n})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,a,r,i,n){const s=i?await this._getPageIndex(e,t,a.pdfManager):null;return a.pdfManager.ensure(this,"_create",[e,t,a,r,i,s,n])}static _create(e,t,a,r,i=!1,n=null,s=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:l}=a,h=t instanceof Ref?t.toString():`annot_${r.createObjId()}`;let u=o.get("Subtype");u=u instanceof Name?u.name:null;const d={xref:e,ref:t,dict:o,subtype:u,id:h,annotationGlobals:a,collectFields:i,needAppearances:!i&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:l.evaluatorOptions,pageRef:s};switch(u){case"Link":return new LinkAnnotation(d);case"Text":return new TextAnnotation(d);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(d);case"Btn":return new ButtonWidgetAnnotation(d);case"Ch":return new ChoiceWidgetAnnotation(d);case"Sig":return new SignatureWidgetAnnotation(d)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(d);case"Popup":return new PopupAnnotation(d);case"FreeText":return new FreeTextAnnotation(d);case"Line":return new LineAnnotation(d);case"Square":return new SquareAnnotation(d);case"Circle":return new CircleAnnotation(d);case"PolyLine":return new PolylineAnnotation(d);case"Polygon":return new PolygonAnnotation(d);case"Caret":return new CaretAnnotation(d);case"Ink":return new InkAnnotation(d);case"Highlight":return new HighlightAnnotation(d);case"Underline":return new UnderlineAnnotation(d);case"Squiggly":return new SquigglyAnnotation(d);case"StrikeOut":return new StrikeOutAnnotation(d);case"Stamp":return new StampAnnotation(d);case"FileAttachment":return new FileAttachmentAnnotation(d);default:i||warn(u?`Unimplemented annotation type "${u}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(d)}}static async _getPageIndex(e,t,a){try{const r=await e.fetchIfRefAsync(t);if(!(r instanceof Dict))return-1;const i=r.getRaw("P");if(i instanceof Ref)try{return await a.ensureCatalog("getPageIndex",[i])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(r.has("Kids"))return-1;const n=await a.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const a=e.getArray("QuadPoints");if(!Array.isArray(a)||0===a.length||a.length%8>0)return null;const r=[];for(let e=0,i=a.length/8;et[2]||st[3]))return null;r.push([{x:i,y:o},{x:n,y:o},{x:i,y:s},{x:n,y:s}])}return r}function getTransformMatrix(e,t,a){const[r,i,n,s]=Util.getAxialAlignedBoundingBox(t,a);if(r===n||i===s)return[1,0,0,1,e[0],e[1]];const o=(e[2]-e[0])/(n-r),c=(e[3]-e[1])/(s-i);return[o,0,0,c,e[0]-r*o,e[1]-i*c]}class Annotation{constructor(e){const{dict:t,xref:a,annotationGlobals:r}=e;this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const i=t.get("MK");this.setBorderAndBackgroundColors(i);this.setRotation(i,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const n=!!(this.flags&ee),s=!!(this.flags&te);if(r.structTreeRoot){let a=t.get("StructParent");a=Number.isInteger(a)&&a>=0?a:-1;r.structTreeRoot.addAnnotationIdToPage(e.pageRef,a)}this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&Z),noHTML:n&&s};if(e.collectFields){const r=t.get("Kids");if(Array.isArray(r)){const e=[];for(const t of r)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(a,t,ye);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_isViewable(e){return!this._hasFlag(e,K)&&!this._hasFlag(e,Q)}_isPrintable(e){return this._hasFlag(e,Y)&&!this._hasFlag(e,J)&&!this._hasFlag(e,K)}mustBeViewed(e,t){const a=e?.get(this.data.id)?.noView;return void 0!==a?!a:this.viewable&&!this._hasFlag(this.flags,J)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:a}=e,r=getInheritableProperty({dict:t,key:"DA"})||a.acroForm.get("DA");this._defaultAppearance="string"==typeof r?r:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&K&&"Annotation"!==this.constructor.name&&(this.flags^=K)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=Array.isArray(e)&&4===e.length?Util.normalizeRect(e):[0,0,0,0]}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const a=e[t];if(a instanceof Name)switch(a.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=a.name;continue}warn(`Ignoring invalid lineEnding: ${a}`)}}setRotation(e,t){this.rotation=0;let a=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(a)&&0!==a){a%=360;a<0&&(a+=360);a%90==0&&(this.rotation=a)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(a instanceof BaseStream){this.appearance=a;return}if(!(a instanceof Dict))return;const r=e.get("AS");if(!(r instanceof Name&&a.has(r.name)))return;const i=a.get(r.name);i instanceof BaseStream&&(this.appearance=i)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,r,i){const{hasOwnCanvas:n,id:s,rect:o}=this.data;let l=this.appearance;const h=!!(n&&a&c);if(h&&(o[0]===o[2]||o[1]===o[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!l){if(!h)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};l=new StringStream("");l.dict=new Dict}const u=l.dict,d=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],l),f=u.getArray("BBox")||[0,0,1,1],g=u.getArray("Matrix")||[1,0,0,1,0,0],p=getTransformMatrix(o,f,g),m=new OperatorList;let b;this.oc&&(b=await e.parseMarkedContentProps(this.oc,null));void 0!==b&&m.addOp(jt,["OC",b]);m.addOp($t,[s,o,p,g,h]);await e.getOperatorList({stream:l,task:t,resources:d,operatorList:m,fallbackFontDict:this._fallbackFontDict});m.addOp(Gt,[]);void 0!==b&&m.addOp(_t,[]);this.reset();return{opList:m,separateForm:!1,separateCanvas:h}}async save(e,t,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,a){if(!this.appearance)return;const r=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),i=[],n=[];let s=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){s||=t.transform.slice(-2);n.push(t.str);if(t.hasEOL){i.push(n.join("").trimEnd());n.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:r,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:a});this.reset();n.length&&i.push(n.join("").trimEnd());if(i.length>1||i[0]){const e=this.appearance.dict;this.data.textPosition=this._transformPoint(s,e.getArray("BBox"),e.getArray("Matrix"));this.data.textContent=i}}_transformPoint(e,t,a){const{rect:r}=this.data;t||=[0,0,1,1];a||=[1,0,0,1,0,0];const i=getTransformMatrix(r,t,a);i[4]-=r[0];i[5]-=r[1];e=Util.applyTransform(e,i);return Util.applyTransform(e,a)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let a=e;const r=new RefSet;e.objId&&r.put(e.objId);for(;a.has("Parent");){a=a.get("Parent");if(!(a instanceof Dict)||a.objId&&r.has(a.objId))break;a.objId&&r.put(a.objId);a.has("T")&&t.unshift(stringToPDFString(a.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.style=fe;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){const a=(t[2]-t[0])/2,r=(t[3]-t[1])/2;if(a>0&&r>0&&(e>a||e>r)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=fe;break;case"D":this.style=ge;break;case"B":this.style=pe;break;case"I":this.style=me;break;case"U":this.style=be}}setDashArray(e,t=!1){if(Array.isArray(e)){let a=!0,r=!0;for(const t of e){if(!(+t>=0)){a=!1;break}t>0&&(r=!1)}if(0===e.length||a&&!r){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const a=t.get("RT");this.data.replyType=a instanceof Name?a.name:V}let a=null;if(this.data.replyType===G){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;a=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;a=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=a instanceof Ref?a.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:a,fillColor:r,blendMode:i,strokeAlpha:n,fillAlpha:s,pointsCallback:o}){let c=Number.MAX_VALUE,l=Number.MAX_VALUE,h=Number.MIN_VALUE,u=Number.MIN_VALUE;const d=["q"];t&&d.push(t);a&&d.push(`${a[0]} ${a[1]} ${a[2]} RG`);r&&d.push(`${r[0]} ${r[1]} ${r[2]} rg`);let f=this.data.quadPoints;f||(f=[[{x:this.rectangle[0],y:this.rectangle[3]},{x:this.rectangle[2],y:this.rectangle[3]},{x:this.rectangle[0],y:this.rectangle[1]},{x:this.rectangle[2],y:this.rectangle[1]}]]);for(const e of f){const[t,a,r,i]=o(d,e);c=Math.min(c,t);h=Math.max(h,a);l=Math.min(l,r);u=Math.max(u,i)}d.push("Q");const g=new Dict(e),p=new Dict(e);p.set("Subtype",Name.get("Form"));const m=new StringStream(d.join(" "));m.dict=p;g.set("Fm0",m);const b=new Dict(e);i&&b.set("BM",Name.get(i));"number"==typeof n&&b.set("CA",n);"number"==typeof s&&b.set("ca",s);const y=new Dict(e);y.set("GS0",b);const w=new Dict(e);w.set("ExtGState",y);w.set("XObject",g);const x=new Dict(e);x.set("Resources",w);const S=this.data.rect=[c,l,h,u];x.set("BBox",S);this.appearance=new StringStream("/GS0 gs /Fm0 Do");this.appearance.dict=x;this._streams.push(this.appearance,m)}static async createNewAnnotation(e,t,a,r){const i=t.ref||=e.getNewTemporaryRef(),n=await this.createNewAppearanceStream(t,e,r),s=[];let o;if(n){const r=e.getNewTemporaryRef();o=this.createNewDict(t,e,{apRef:r});await writeObject(r,n,s,e);a.push({ref:r,data:s.join("")})}else o=this.createNewDict(t,e,{});Number.isInteger(t.parentTreeId)&&o.set("StructParent",t.parentTreeId);s.length=0;await writeObject(i,o,s,e);return{ref:i,data:s.join("")}}static async createNewPrintAnnotation(e,t,a,r){const i=await this.createNewAppearanceStream(a,t,r),n=this.createNewDict(a,t,{ap:i}),s=new this.prototype.constructor({dict:n,xref:t,annotationGlobals:e,evaluatorOptions:r.evaluatorOptions});a.ref&&(s.ref=s.refToReplace=a.ref);return s}}class WidgetAnnotation extends Annotation{constructor(e){super(e);const{dict:t,xref:a,annotationGlobals:r}=e,i=this.data;this._needAppearances=e.needAppearances;i.annotationType=$;void 0===i.fieldName&&(i.fieldName=this._constructFieldName(t));void 0===i.actions&&(i.actions=collectActions(a,t,ye));let n=getInheritableProperty({dict:t,key:"V",getArray:!0});i.fieldValue=this._decodeFormValue(n);const s=getInheritableProperty({dict:t,key:"DV",getArray:!0});i.defaultFieldValue=this._decodeFormValue(s);if(void 0===n&&r.xfaDatasets){const e=this._title.str;if(e){this._hasValueFromXFA=!0;i.fieldValue=n=r.xfaDatasets.getValue(e)}}void 0===n&&null!==i.defaultFieldValue&&(i.fieldValue=i.defaultFieldValue);i.alternativeText=stringToPDFString(t.get("TU")||"");this.setDefaultAppearance(e);i.hasAppearance||=this._needAppearances&&void 0!==i.fieldValue&&null!==i.fieldValue;const o=getInheritableProperty({dict:t,key:"FT"});i.fieldType=o instanceof Name?o.name:null;const c=getInheritableProperty({dict:t,key:"DR"}),l=r.acroForm.get("DR"),h=this.appearance?.dict.get("Resources");this._fieldResources={localResources:c,acroFormResources:l,appearanceResources:h,mergedResources:Dict.merge({xref:a,dictArray:[c,h,l],mergeSubDicts:!0})};i.fieldFlags=getInheritableProperty({dict:t,key:"Ff"});(!Number.isInteger(i.fieldFlags)||i.fieldFlags<0)&&(i.fieldFlags=0);i.readOnly=this.hasFieldFlag(ae);i.required=this.hasFieldFlag(re);i.hidden=this._hasFlag(i.annotationFlags,J)||this._hasFlag(i.annotationFlags,Q)}_decodeFormValue(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,Q)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return a;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const a=this.data.rect[2]-this.data.rect[0],r=this.data.rect[3]-this.data.rect[1],i=0===t||180===t?`0 0 ${a} ${r} re`:`0 0 ${r} ${a} re`;let n="";this.backgroundColor&&(n=`${getPdfColor(this.backgroundColor,!0)} ${i} f `);if(this.borderColor){n+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${i} S `}return n}async getOperatorList(e,t,a,r,i){if(r&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,a,r,i);const n=await this._getAppearance(e,t,a,i);if(this.appearance&&null===n)return super.getOperatorList(e,t,a,r,i);const s=new OperatorList;if(!this._defaultAppearance||null===n)return{opList:s,separateForm:!1,separateCanvas:!1};const o=!!(this.data.hasOwnCanvas&&a&c),l=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],h=getTransformMatrix(this.data.rect,l,[1,0,0,1,0,0]);let u;this.oc&&(u=await e.parseMarkedContentProps(this.oc,null));void 0!==u&&s.addOp(jt,["OC",u]);s.addOp($t,[this.data.id,this.data.rect,h,this.getRotationMatrix(i),o]);const d=new StringStream(n);await e.getOperatorList({stream:d,task:t,resources:this._fieldResources.mergedResources,operatorList:s});s.addOp(Gt,[]);void 0!==u&&s.addOp(_t,[]);return{opList:s,separateForm:!1,separateCanvas:o}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}async save(e,t,r){const i=r?.get(this.data.id);let n=i?.value,s=i?.rotation;if(n===this.data.fieldValue||void 0===n){if(!this._hasValueFromXFA&&void 0===s)return null;n||=this.data.fieldValue}if(void 0===s&&!this._hasValueFromXFA&&Array.isArray(n)&&Array.isArray(this.data.fieldValue)&&n.length===this.data.fieldValue.length&&n.every(((e,t)=>e===this.data.fieldValue[t])))return null;void 0===s&&(s=this.rotation);let o=null;if(!this._needAppearances){o=await this._getAppearance(e,t,h,r);if(null===o)return null}let c=!1;if(o?.needAppearances){c=!0;o=null}const{xref:l}=e,u=l.fetchIfRef(this.ref);if(!(u instanceof Dict))return null;const d=new Dict(l);for(const e of u.getKeys())"AP"!==e&&d.set(e,u.getRaw(e));const f={path:this.data.fieldName,value:n},encoder=e=>isAscii(e)?e:stringToUTF16String(e,!0);d.set("V",Array.isArray(n)?n.map(encoder):encoder(n));this.amendSavedDict(r,d);const g=this._getMKDict(s);g&&d.set("MK",g);const p=[],m=[{ref:this.ref,data:"",xfa:f,needAppearances:c}];if(null!==o){const e=l.getNewTemporaryRef(),t=new Dict(l);d.set("AP",t);t.set("N",e);const i=this._getSaveFieldResources(l),n=new StringStream(o),s=n.dict=new Dict(l);s.set("Subtype",Name.get("Form"));s.set("Resources",i);s.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const c=this.getRotationMatrix(r);c!==a&&s.set("Matrix",c);await writeObject(e,n,p,l);m.push({ref:e,data:p.join(""),xfa:null,needAppearances:!1});p.length=0}d.set("M",`D:${getModificationDate()}`);await writeObject(this.ref,d,p,l);m[0].data=p.join("");return m}async _getAppearance(e,t,a,r){if(this.hasFieldFlag(ne))return null;const i=r?.get(this.data.id);let n,o;if(i){n=i.formattedValue||i.value;o=i.rotation}if(void 0===o&&void 0===n&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const c=this.getBorderAndBackgroundAppearances(r);if(void 0===n){n=this.data.fieldValue;if(!n)return`/Tx BMC q ${c}Q EMC`}Array.isArray(n)&&1===n.length&&(n=n[0]);assert("string"==typeof n,"Expected `value` to be a string.");n=n.trim();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>n===e));n=e?.displayValue||n}if(""===n)return`/Tx BMC q ${c}Q EMC`;void 0===o&&(o=this.rotation);let l,u=-1;if(this.data.multiLine){l=n.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));u=l.length}else l=[n.replace(/\r\n?|\n/,"").normalize("NFC")];let d=this.data.rect[3]-this.data.rect[1],f=this.data.rect[2]-this.data.rect[0];90!==o&&270!==o||([f,d]=[d,f]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let g,p,m,b=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const y=[];let w=!1;for(const e of l){const t=b.encodeString(e);t.length>1&&(w=!0);y.push(t.join(""))}if(w&&a&h)return{needAppearances:!0};if(w&&this._isOffscreenCanvasSupported){const a=this.data.comb?"monospace":"sans-serif",r=new FakeUnicodeFont(e.xref,a),i=r.createFontResources(l.join("")),s=i.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of s.getKeys())e.set(t,s.getRaw(t))}else this._fieldResources.mergedResources.set("Font",s);const o=r.fontName.name;b=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},i);for(let e=0,t=y.length;e2)return`/Tx BMC q ${c}BT `+g+` 1 0 0 1 ${numberToString(2)} ${numberToString(C)} Tm (${escapeString(y[0])}) Tj ET Q EMC`;return`/Tx BMC q ${c}BT `+g+` 1 0 0 1 0 0 Tm ${this._renderText(y[0],b,p,f,k,{shift:0},2,C)} ET Q EMC`}static async _getFontData(e,t,a,r){const i=new OperatorList,n={font:null,clone(){return this}},{fontName:s,fontSize:o}=a;await e.handleSetFont(r,[s&&Name.get(s),o],null,i,t,n,null);return n.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,a,r,n){let{fontSize:s}=this.data.defaultAppearanceData,o=(s||12)*i,c=Math.round(e/o);if(!s){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===n){const n=this._getTextWidth(a,r);s=roundWithTwoDigits(Math.min(e/i,n>t?t/n:1/0));c=1}else{const l=a.split(/\r\n?|\n/),h=[];for(const e of l){const t=r.encodeString(e).join(""),a=r.charsToGlyphs(t),i=r.getCharPositions(t);h.push({line:t,glyphs:a,positions:i})}const isTooBig=a=>{let i=0;for(const n of h){i+=this._splitLine(null,r,a,t,n).length*a;if(i>e)return!0}return!1};c=Math.max(c,n);for(;;){o=e/c;s=roundWithTwoDigits(o/i);if(!isTooBig(s))break;c++}}const{fontName:l,fontColor:h}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:a}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(a,!0)}`}({fontSize:s,fontName:l,fontColor:h})}return[this._defaultAppearance,s,e/c]}_renderText(e,t,a,r,i,n,s,o){let c;if(1===i){c=(r-this._getTextWidth(e,t)*a)/2}else if(2===i){c=r-this._getTextWidth(e,t)*a-s}else c=s;const l=numberToString(c-n.shift);n.shift=c;return`${l} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:a,acroFormResources:r}=this._fieldResources,i=this.data.defaultAppearanceData?.fontName;if(!i)return t||Dict.empty;for(const e of[t,a])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(i))return e}if(r instanceof Dict){const a=r.get("Font");if(a instanceof Dict&&a.has(i)){const r=new Dict(e);r.set(i,a.getRaw(i));const n=new Dict(e);n.set("Font",r);return Dict.merge({xref:e,dictArray:[n,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;const t=e.dict;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let a=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(a)||a<0||a>2)&&(a=null);this.data.textAlignment=a;let r=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(r)||r<0)&&(r=0);this.data.maxLen=r;this.data.multiLine=this.hasFieldFlag(ie);this.data.comb=this.hasFieldFlag(de)&&!this.hasFieldFlag(ie)&&!this.hasFieldFlag(ne)&&!this.hasFieldFlag(le)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(ue)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,a,r,i,n,s,o,c,l,h){const u=i/this.data.maxLen,d=this.getBorderAndBackgroundAppearances(h),f=[],g=t.getCharPositions(a);for(const[e,t]of g)f.push(`(${escapeString(a.substring(e,t))}) Tj`);const p=f.join(` ${numberToString(u)} 0 Td `);return`/Tx BMC q ${d}BT `+e+` 1 0 0 1 ${numberToString(s)} ${numberToString(o+c)} Tm ${p} ET Q EMC`}_getMultilineAppearance(e,t,a,r,i,n,s,o,c,l,h,u){const d=[],f=i-2*o,g={shift:0};for(let e=0,n=t.length;er){c.push(e.substring(d,a));d=a;f=p;l=-1;u=-1}else{f+=p;l=a;h=i;u=t}else if(f+p>r)if(-1!==l){c.push(e.substring(d,h));d=h;t=u+1;l=-1;f=0}else{c.push(e.substring(d,a));d=a;f=p}else f+=p}d"Off"!==e));n.length=0;n.push("Off",e)}n.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=n[1];const s=a.get(this.data.exportValue);this.checkedAppearance=s instanceof BaseStream?s:null;const o=a.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const a=t.get("V");a instanceof Name&&(this.data.fieldValue=this._decodeFormValue(a))}const a=e.dict.get("AP");if(!(a instanceof Dict))return;const r=a.get("N");if(!(r instanceof Dict))return;for(const e of r.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const i=r.get(this.data.buttonValue);this.checkedAppearance=i instanceof BaseStream?i:null;const n=r.get("Off");this.uncheckedAppearance=n instanceof BaseStream?n:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:a}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:a.baseUrl,docAttachments:a.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const r=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(r))for(let e=0,t=r.length;e=0&&t0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let a=e?.get(this.data.id)?.value;Array.isArray(a)||(a=[a]);const r=[],{options:i}=this.data;for(let e=0,t=0,n=i.length;ea){a=r;t=e}}[f,g]=this._computeFontSize(e,l-4,t,d,-1)}const p=g*i,m=(p-g)/2,b=Math.floor(c/p);let y=0;if(u.length>0){const e=Math.min(...u),t=Math.max(...u);y=Math.max(0,t-b+1);y>e&&(y=e)}const w=Math.min(y+b+1,h),x=["/Tx BMC q",`1 1 ${l} ${c} re W n`];if(u.length){x.push("0.600006 0.756866 0.854904 rg");for(const e of u)y<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:a}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,r);this.data.textPosition=this._transformPoint(e,t,a)}if(this._isOffscreenCanvasSupported){const i=e.dict.get("CA"),n=new FakeUnicodeFont(a,"sans-serif");this.appearance=n.createAppearance(this._contents.str,this.rectangle,this.rotation,r,t,i);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,fontSize:n,rect:s,rotation:o,user:c,value:l}=e,h=new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",s);const u=`/Helv ${n} Tf ${getPdfColor(i,!0)}`;h.set("DA",u);h.set("Contents",isAscii(l)?l:stringToUTF16String(l,!0));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",isAscii(c)?c:stringToUTF16String(c,!0));if(a||r){const e=new Dict(t);h.set("AP",e);a?e.set("N",a):e.set("N",r)}return h}static async createNewAppearanceStream(e,t,a){const{baseFontRef:r,evaluator:n,task:s}=a,{color:o,fontSize:c,rect:l,rotation:h,value:u}=e,d=new Dict(t),f=new Dict(t);if(r)f.set("Helv",r);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));f.set("Helv",e)}d.set("Font",f);const g=await WidgetAnnotation._getFontData(n,s,{fontName:"Helv",fontSize:c},d),[p,m,b,y]=l;let w=b-p,x=y-m;h%180!=0&&([w,x]=[x,w]);const S=u.split("\n"),k=c/1e3;let C=-1/0;const v=[];for(let e of S){const t=g.encodeString(e);if(t.length>1)return null;e=t.join("");v.push(e);let a=0;const r=g.charsToGlyphs(e);for(const e of r)a+=e.width*k;C=Math.max(C,a)}let F=1;C>w&&(F=w/C);let O=1;const T=i*c,M=1*c,D=T*S.length;D>x&&(O=x/D);const R=c*Math.min(F,O);let N,E,L;switch(h){case 0:L=[1,0,0,1];E=[l[0],l[1],w,x];N=[l[0],l[3]-M];break;case 90:L=[0,1,-1,0];E=[l[1],-l[2],w,x];N=[l[1],-l[0]-M];break;case 180:L=[-1,0,0,-1];E=[-l[2],-l[3],w,x];N=[-l[2],-l[1]-M];break;case 270:L=[0,-1,1,0];E=[-l[3],l[0],w,x];N=[-l[3],l[2]-M]}const j=["q",`${L.join(" ")} 0 0 cm`,`${E.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(R)} Tf`];j.push(`${N.join(" ")} Td (${escapeString(v[0])}) Tj`);const _=numberToString(T);for(let e=1,t=v.length;e{e.push(`${r[0]} ${r[1]} m`,`${r[2]} ${r[3]} l`,"S");return[t[0].x-c,t[1].x+c,t[3].y-c,t[1].y+c]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA"),i=getRgbColor(t.getArray("IC"),null),n=i?getPdfColorArray(i):null,s=n?r:null;if(0===this.borderStyle.width&&!n)return;this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:n,strokeAlpha:r,fillAlpha:s,pointsCallback:(e,t)=>{const a=t[2].x+this.borderStyle.width/2,r=t[2].y+this.borderStyle.width/2,i=t[3].x-t[2].x-this.borderStyle.width,s=t[1].y-t[3].y-this.borderStyle.width;e.push(`${a} ${r} ${i} ${s} re`);n?e.push("B"):e.push("S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=R;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA"),i=getRgbColor(t.getArray("IC"),null),n=i?getPdfColorArray(i):null,s=n?r:null;if(0===this.borderStyle.width&&!n)return;const o=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:n,strokeAlpha:r,fillAlpha:s,pointsCallback:(e,t)=>{const a=t[0].x+this.borderStyle.width/2,r=t[0].y-this.borderStyle.width/2,i=t[3].x-this.borderStyle.width/2,s=t[3].y+this.borderStyle.width/2,c=a+(i-a)/2,l=r+(s-r)/2,h=(i-a)/2*o,u=(s-r)/2*o;e.push(`${c} ${s} m`,`${c+h} ${s} ${i} ${l+u} ${i} ${l} c`,`${i} ${l-u} ${c+h} ${r} ${c} ${r} c`,`${c-h} ${r} ${a} ${l-u} ${a} ${l} c`,`${a} ${l+u} ${c-h} ${s} ${c} ${s} c`,"h");n?e.push("B"):e.push("S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=E;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=[];if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const r=t.getArray("Vertices");if(Array.isArray(r)){for(let e=0,t=r.length;e{const a=this.data.vertices;for(let t=0,r=a.length;t{for(const t of this.data.inkLists){for(let a=0,r=t.length;ae.points)));u.set("F",4);u.set("Rotate",l);o&&u.set("IT",Name.get("InkHighlight"));const d=new Dict(t);u.set("BS",d);d.set("W",h);u.set("C",Array.from(i,(e=>e/255)));u.set("CA",n);const f=new Dict(t);u.set("AP",f);a?f.set("N",a):f.set("N",r);return u}static async createNewAppearanceStream(e,t,a){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,a);const{color:r,rect:i,paths:n,thickness:s,opacity:o}=e,c=[`${s} w 1 J 1 j`,`${getPdfColor(r,!1)}`];1!==o&&c.push("/R0 gs");const l=[];for(const{bezier:e}of n){l.length=0;l.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);if(2===e.length)l.push(`${numberToString(e[0])} ${numberToString(e[1])} l S`);else{for(let t=2,a=e.length;t{e.push(`${t[0].x} ${t[0].y} m`,`${t[1].x} ${t[1].y} l`,`${t[3].x} ${t[3].y} l`,`${t[2].x} ${t[2].y} l`,"f");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,opacity:n,rect:s,rotation:o,user:c,quadPoints:l}=e,h=new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",s);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",l);h.set("C",Array.from(i,(e=>e/255)));h.set("CA",n);c&&h.set("T",isAscii(c)?c:stringToUTF16String(c,!0));if(a||r){const e=new Dict(t);h.set("AP",e);e.set("N",a||r)}return h}static async createNewAppearanceStream(e,t,a){const{color:r,rect:i,outlines:n,opacity:s}=e,o=[`${getPdfColor(r,!0)}`,"/R0 gs"],c=[];for(const e of n){c.length=0;c.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,a=e.length;t{e.push(`${t[2].x} ${t[2].y+1.3} m`,`${t[3].x} ${t[3].y+1.3} l`,"S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=_;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA");this._setDefaultAppearance({xref:a,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:r,pointsCallback:(e,t)=>{const a=(t[0].y-t[2].y)/6;let r=a,i=t[2].x;const n=t[2].y,s=t[3].x;e.push(`${i} ${n+r} m`);do{i+=2;r=0===r?a:0;e.push(`${i} ${n+r} l`)}while(i{e.push((t[0].x+t[2].x)/2+" "+(t[0].y+t[2].y)/2+" m",(t[1].x+t[3].x)/2+" "+(t[1].y+t[3].y)/2+" l","S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{constructor(e){super(e);this.data.annotationType=X;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1}static async createImage(e,t){const{width:a,height:r}=e,i=new OffscreenCanvas(a,r),n=i.getContext("2d",{alpha:!0});n.drawImage(e,0,0);const s=n.getImageData(0,0,a,r).data,o=new Uint32Array(s.buffer),c=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>255!=(255&e));if(c){n.fillStyle="white";n.fillRect(0,0,a,r);n.drawImage(e,0,0)}const l=i.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),h=Name.get("XObject"),u=Name.get("Image"),d=new Dict(t);d.set("Type",h);d.set("Subtype",u);d.set("BitsPerComponent",8);d.set("ColorSpace",Name.get("DeviceRGB"));d.set("Filter",Name.get("DCTDecode"));d.set("BBox",[0,0,a,r]);d.set("Width",a);d.set("Height",r);let f=null;if(c){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,a=o.length;t>>24;else for(let t=0,a=o.length;t=0&&n<=1?n:null}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const a=t.firstChild;return"value"===a?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#P=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[s,o]=n;if(!Number.isInteger(s)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${s}, ${o}`);if(!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(i))throw new FormatError(`Invalid XRef entry fields length: ${s}, ${o}`);for(let n=t.entryNum;n=e.length);){a+=String.fromCharCode(r);r=e[t]}return a}function skipUntil(e,t,a){const r=a.length,i=e.length;let n=0;for(;t=r)break;t++;n++}return n}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,r=new Uint8Array([116,114,97,105,108,101,114]),i=new Uint8Array([115,116,97,114,116,120,114,101,102]),n=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const s=this.stream;s.pos=0;const o=s.getBytes(),c=bytesToString(o),l=o.length;let h=s.start;const u=[],d=[];for(;h=l)break;f=o[h]}while(10!==f&&13!==f);continue}const g=readToken(o,h);let p;if(g.startsWith("xref")&&(4===g.length||/\s/.test(g[4]))){h+=skipUntil(o,h,r);u.push(h);h+=skipUntil(o,h,i)}else if(p=a.exec(g)){const t=0|p[1],a=0|p[2],r=h+g.length;let i,u=!1;if(this.entries[t]){if(this.entries[t].gen===a)try{new Parser({lexer:new Lexer(s.makeSubStream(r))}).getObj();u=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${g}): "${e}".`):u=!0}}else u=!0;u&&(this.entries[t]={offset:h-s.start,gen:a,uncompressed:!0});e.lastIndex=r;const f=e.exec(c);if(f){i=e.lastIndex+1-h;if("endobj"!==f[1]){warn(`indexObjects: Found "${f[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);i-=f[1].length+1}}else i=l-h;const m=o.subarray(h,h+i),b=skipUntil(m,0,n);if(b0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const a=e.num,r=this._cacheMap.get(a);if(void 0!==r){r instanceof Dict&&!r.objId&&(r.objId=e.toString());return r}let i=this.getEntry(a);if(null===i){this._cacheMap.set(a,i);return i}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return ua}this._pendingRefs.put(e);try{i=i.uncompressed?this.fetchUncompressed(e,i,t):this.fetchCompressed(e,i,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}i instanceof Dict?i.objId=e.toString():i instanceof BaseStream&&(i.dict.objId=e.toString());return i}fetchUncompressed(e,t,a=!1){const r=e.gen;let i=e.num;if(t.gen!==r){const n=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||Jo)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){let e=this.pageDict.get("UserUnit");("number"!=typeof e||e<=0)&&(e=1);return shadow(this,"userUnit",e)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const a=Util.intersect(e,t);if(a&&a[2]-a[0]>0&&a[3]-a[1]>0)return shadow(this,"view",a);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}#L(e,t,a){for(const r of e)if(r.id){const e=Ref.fromString(r.id);if(!e){warn(`A non-linked annotation cannot be modified: ${r.id}`);continue}if(r.deleted){t.put(e);continue}a?.put(e);r.ref=e;delete r.id}}async saveNewAnnotations(e,t,a,r){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const i=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSet,s=new RefSet;this.#L(a,n,s);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),l=await AnnotationFactory.saveNewAnnotations(i,t,a,r);for(const{ref:e}of l.annotations)e instanceof Ref&&!s.has(e)&&c.push(e);const h=o.get("Annots");o.set("Annots",c);const u=[];await writeObject(this.ref,o,u,this.xref);h&&o.set("Annots",h);const d=l.dependencies;d.push({ref:this.ref,data:u.join("")},...l.annotations);return d}save(e,t,a){const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const i=[];for(const n of e)n.mustBePrinted(a)&&i.push(n.save(r,t,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(i).then((function(e){return e.filter((e=>!!e))}))}))}loadResources(e){this.resourcesPromise||(this.resourcesPromise=this.pdfManager.ensure(this,"resources"));return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:a,intent:r,cacheKey:i,annotationStorage:n=null}){const s=this.getContentStream(),h=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),f=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),p=this.xfaFactory?null:getNewAnnotationsMap(n);let m=null,b=Promise.resolve(null);if(p){const e=p.get(this.pageIndex);if(e){const t=this.pdfManager.ensureDoc("annotationGlobals");let r;const i=new Set;for(const{bitmapId:t,bitmap:a}of e)!t||a||i.has(t)||i.add(t);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(i.size>0){const t=e.slice();for(const[e,a]of n)e.startsWith(g)&&a.bitmap&&i.has(a.bitmapId)&&t.push(a);r=AnnotationFactory.generateImages(t,this.xref,s)}else r=AnnotationFactory.generateImages(e,this.xref,s);m=new RefSet;this.#L(e,m,null);b=t.then((t=>t?AnnotationFactory.printNewAnnotations(t,f,a,e,r):null))}}const y=Promise.all([s,h]).then((([n])=>{const s=new OperatorList(r,t);e.send("StartRenderPage",{transparency:f.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:i});return f.getOperatorList({stream:n,task:a,resources:this.resources,operatorList:s}).then((function(){return s}))}));return Promise.all([y,this._parsedAnnotations,b]).then((function([e,t,i]){if(i){t=t.filter((e=>!(e.ref&&m.has(e.ref))));for(let e=0,a=i.length;ee.ref&&isRefsEqual(e.ref,r.refToReplace)));if(n>=0){t.splice(n,1,r);i.splice(e--,1);a--}}}t=t.concat(i)}if(0===t.length||r&d){e.flush(!0);return{length:e.totalLength}}const s=!!(r&u),h=!!(r&o),g=!!(r&c),p=!!(r&l),b=[];for(const e of t)(h||g&&e.mustBeViewed(n,s)||p&&e.mustBePrinted(n))&&b.push(e.getOperatorList(f,a,r,s,n).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${a.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(b).then((function(t){let a=!1,r=!1;for(const{opList:i,separateForm:n,separateCanvas:s}of t){e.addOpList(i);a||=n;r||=s}e.flush(!0,{form:a,canvas:r});return{length:e.totalLength}}))}))}extractTextContent({handler:e,task:t,includeMarkedContent:a,disableNormalization:r,sink:i}){const n=this.getContentStream(),s=this.loadResources(["ExtGState","Font","Properties","XObject"]);return Promise.all([n,s]).then((([n])=>new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:n,task:t,resources:this.resources,includeMarkedContent:a,disableNormalization:r,sink:i,viewBox:this.view})))}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;return(await this.pdfManager.ensure(this,"_parseStructTree",[e])).serializable}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,a){const r=await this._parsedAnnotations;if(0===r.length)return r;const i=[],n=[];let s;const h=!!(a&o),u=!!(a&c),d=!!(a&l);for(const a of r){const r=h||u&&a.viewable;(r||d&&a.printable)&&i.push(a.data);if(a.hasTextContent&&r){s||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});n.push(a.extractTextContent(s,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(n);return i}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const t=await this.pdfManager.ensureDoc("annotationGlobals");if(!t)return[];const a=[];for(const r of e)a.push(AnnotationFactory.create(this.xref,r,t,this._localIdFactory,!1,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let i,n;for(const e of await Promise.all(a))e&&(e instanceof WidgetAnnotation?(n||=[]).push(e):e instanceof PopupAnnotation?(i||=[]).push(e):r.push(e));n&&r.push(...n);i&&r.push(...i);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,xe))}}const Yo=new Uint8Array([37,80,68,70,45]),Zo=new Uint8Array([115,116,97,114,116,120,114,101,102]),Qo=new Uint8Array([101,110,100,111,98,106]);function find(e,t,a=1024,r=!1){const i=t.length,n=e.peekBytes(a),s=n.length-i;if(s<=0)return!1;if(r){const a=i-1;let r=n.length-1;for(;r>=a;){let s=0;for(;s=i){e.pos+=r-a;return!0}r--}}else{let a=0;for(;a<=s;){let r=0;for(;r=i){e.pos+=a;return!0}a++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const a={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++a.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,Qo)){e.skip(6);let a=e.peekByte();for(;isWhiteSpace(a);){e.pos++;a=e.peekByte()}t=e.pos-e.start}}else{const a=1024,r=Zo.length;let i=!1,n=e.end;for(;!i&&n>0;){n-=a-r;n<0&&(n=0);e.pos=n;i=find(e,Zo,a,!0)}if(i){e.skip(9);let a;do{a=e.getByte()}while(isWhiteSpace(a));let r="";for(;a>=32&&a<=57;){r+=String.fromCharCode(a);a=e.getByte()}t=parseInt(r,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,Yo))return;e.moveStart();e.skip(Yo.length);let t,a="";for(;(t=e.getByte())>32&&a.length<7;)a+=String.fromCharCode(t);ba.test(a)?this._version=a:warn(`Invalid PDF header version: ${a}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const a=isName(e.get("FT"),"Sig"),r=e.get("Rect"),i=Array.isArray(r)&&r.every((e=>0===e));return a&&i}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),a={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){a["xdp:xdp"]=t;return a}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,r=t.length;e{u.set(e,t)}));const d=[];for(const[e,a]of u){const i=a.get("FontDescriptor");if(!(i instanceof Dict))continue;let n=i.get("FontFamily");n=n.replaceAll(/[ ]+(\d)/g,"$1");const s={fontFamily:n,fontWeight:i.get("FontWeight"),italicAngle:-i.get("ItalicAngle")};validateCSSFont(s)&&d.push(o.handleSetFont(r,[Name.get(e),1],null,c,t,h,null,s).catch((function(e){warn(`loadXfaFonts: "${e}".`);return null})))}await Promise.all(d);const f=this.xfaFactory.setFonts(l);if(!f)return;s.ignoreErrors=!0;d.length=0;l.length=0;const g=new Set;for(const e of f)getXfaFontName(`${e}-Regular`)||g.add(e);g.size&&f.push("PdfJS-Fallback");for(const e of f)if(!g.has(e))for(const a of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const i=`${e}-${a.name}`,n=getXfaFontDict(i);d.push(o.handleSetFont(r,[Name.get(i),1],null,c,t,h,n,{fontFamily:e,fontWeight:a.fontWeight,italicAngle:a.italicAngle}).catch((function(e){warn(`loadXfaFonts: "${e}".`);return null})))}await Promise.all(d);this.xfaFactory.appendFonts(l,g)}async serializeXfaData(e){return this.xfaFactory?this.xfaFactory.serializeData(e):null}get version(){return this.catalog.version||this._version}get formInfo(){const e={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},t=this.catalog.acroForm;if(!t)return shadow(this,"formInfo",e);try{const a=t.get("Fields"),r=Array.isArray(a)&&a.length>0;e.hasFields=r;const i=t.get("XFA");e.hasXfa=Array.isArray(i)&&i.length>0||i instanceof BaseStream&&!i.isEmpty;const n=!!(1&t.get("SigFlags")),s=n&&this._hasOnlyDocumentSignatures(a);e.hasAcroForm=r&&!s;e.hasSignatures=n}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const a of t.getKeys()){const r=t.get(a);switch(a){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof r){e[a]=stringToPDFString(r);continue}break;case"Trapped":if(r instanceof Name){e[a]=r;continue}break;default:let t;switch(typeof r){case"string":t=stringToPDFString(r);break;case"number":case"boolean":t=r;break;default:r instanceof Name&&(t=r)}if(void 0===t){warn(`Bad value, for custom key "${a}", in Info: ${r}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[a]=t;continue}warn(`Bad value, for key "${a}", in Info: ${r}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){function validate(e){return"string"==typeof e&&e.length>0&&"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"!==e}function hexString(e){const t=[];for(const a of e){const e=a.toString(16);t.push(e.padStart(2,"0"))}return t.join("")}const e=this.xref.trailer.get("ID");let t,a;if(Array.isArray(e)&&validate(e[0])){t=stringToBytes(e[0]);e[1]!==e[0]&&validate(e[1])&&(a=stringToBytes(e[1]))}else t=On(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[hexString(t),a?hexString(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:a,xref:r}=this,i=Ref.get(a.objectNumberFirst,0);try{const e=await r.fetchAsync(i);if(e instanceof Dict){let a=e.getRaw("Type");a instanceof Ref&&(a=await r.fetchAsync(a));if(isName(a,"Page")||!e.has("Type")&&!e.has("Kids")){t.pageKidsCountCache.has(i)||t.pageKidsCountCache.put(i,1);t.pageIndexCache.has(i)||t.pageIndexCache.put(i,0);return[e,i]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(a){warn(`_getLinearizationPage: "${a.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:a,linearization:r,xfaFactory:i}=this;let n;n=i?Promise.resolve([Dict.empty,null]):r?.pageFirst===e?this._getLinearizationPage(e):a.getPageDict(e);n=n.then((([t,r])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:r,globalIdFactory:this._globalIdFactory,fontCache:a.fontCache,builtInCMapCache:a.builtInCMapCache,standardFontDataCache:a.standardFontDataCache,globalImageCache:a.globalImageCache,systemFontCache:a.systemFontCache,nonBlendModesSet:a.nonBlendModesSet,xfaFactory:i})));this._pagePromises.set(e,n);return n}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:a}=this;t.setActualNumPages();let r;try{await Promise.all([a.ensureDoc("xfaFactory"),a.ensureDoc("linearization"),a.ensureCatalog("numPages")]);if(this.xfaFactory)return;r=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(r))throw new FormatError("Page count is not an integer.");if(r<=1)return;await this.getPage(r-1)}catch(i){this._pagePromises.delete(r-1);await this.cleanup();if(i instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${r}.`);let n;try{n=await t.getAllPageDicts(e)}catch(a){if(a instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[r,i]]of n){let n;if(r instanceof Error){n=Promise.reject(r);n.catch((()=>{}))}else n=Promise.resolve(new Page({pdfManager:a,xref:this.xref,pageIndex:e,pageDict:r,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,n)}t.setActualNumPages(n.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#j(e,t,a,r,i){const{xref:n}=this;if(!(t instanceof Ref)||i.has(t))return;i.put(t);const s=await n.fetchAsync(t);if(!(s instanceof Dict))return;if(s.has("T")){const t=stringToPDFString(await s.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let t=s;for(;;){t=t.getRaw("Parent");if(t instanceof Ref){if(i.has(t))break;t=await n.fetchAsync(t)}if(!(t instanceof Dict))break;if(t.has("T")){const a=stringToPDFString(await t.getAsync("T"));e=""===e?a:`${e}.${a}`;break}}}a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(n,t,r,null,!0,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!s.has("Kids"))return;const o=await s.getAsync("Kids");if(Array.isArray(o))for(const t of o)await this.#j(e,t,a,r,i)}get fieldObjects(){if(!this.formInfo.hasFields)return shadow(this,"fieldObjects",Promise.resolve(null));return shadow(this,"fieldObjects",Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]).then((async([e,t])=>{if(!e)return null;const a=new RefSet,r=Object.create(null),i=new Map;for(const r of await t.getAsync("Fields"))await this.#j("",r,i,e,a);const n=[];for(const[e,t]of i)n.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(r[e]=t)})));await Promise.all(n);return r})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm;if(!e?.has("CO"))return shadow(this,"calculationOrderIds",null);const t=e.get("CO");if(!Array.isArray(t)||0===t.length)return shadow(this,"calculationOrderIds",null);const a=[];for(const e of t)e instanceof Ref&&a.push(e.toString());return 0===a.length?shadow(this,"calculationOrderIds",null):shadow(this,"calculationOrderIds",a)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this.constructor===BasePdfManager&&unreachable("Cannot initialize BasePdfManager.");this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;this.evaluatorOptions=e.evaluatorOptions}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,a){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,a){const r=e[t];return"function"==typeof r?r.apply(e,a):r}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,a){try{const r=e[t];return"function"==typeof r?r.apply(e,a):r}catch(r){if(!(r instanceof MissingDataException))throw r;await this.requestRange(r.begin,r.end);return this.ensure(e,t,a)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const ec=1,tc=2,ac=1,rc=2,ic=3,nc=4,sc=5,oc=6,cc=7,lc=8;function wrapReason(e){e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details);default:return new UnknownErrorException(e.message,e.toString())}}class MessageHandler{constructor(e,t,a){this.sourceName=e;this.targetName=t;this.comObj=a;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);this._onComObjOnMessage=e=>{const t=e.data;if(t.targetName!==this.sourceName)return;if(t.stream){this.#_(t);return}if(t.callback){const e=t.callbackId,a=this.callbackCapabilities[e];if(!a)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ec)a.resolve(t.data);else{if(t.callback!==tc)throw new Error("Unexpected callback case");a.reject(wrapReason(t.reason))}return}const r=this.actionHandler[t.action];if(!r)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const e=this.sourceName,i=t.sourceName;new Promise((function(e){e(r(t.data))})).then((function(r){a.postMessage({sourceName:e,targetName:i,callback:ec,callbackId:t.callbackId,data:r})}),(function(r){a.postMessage({sourceName:e,targetName:i,callback:tc,callbackId:t.callbackId,reason:wrapReason(r)})}))}else t.streamId?this.#U(t):r(t.data)};a.addEventListener("message",this._onComObjOnMessage)}on(e,t){const a=this.actionHandler;if(a[e])throw new Error(`There is already an actionName called "${e}"`);a[e]=t}send(e,t,a){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},a)}sendWithPromise(e,t,a){const r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},a)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,a,r){const i=this.streamId++,n=this.sourceName,s=this.targetName,o=this.comObj;return new ReadableStream({start:a=>{const c=Promise.withResolvers();this.streamControllers[i]={controller:a,startCall:c,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:n,targetName:s,action:e,streamId:i,data:t,desiredSize:a.desiredSize},r);return c.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[i].pullCall=t;o.postMessage({sourceName:n,targetName:s,stream:oc,streamId:i,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[i].cancelCall=t;this.streamControllers[i].isClosed=!0;o.postMessage({sourceName:n,targetName:s,stream:ac,streamId:i,reason:wrapReason(e)});return t.promise}},a)}#U(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this,s=this.actionHandler[e.action],o={enqueue(e,n=1,s){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=n;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}i.postMessage({sourceName:a,targetName:r,stream:nc,streamId:t,chunk:e},s)},close(){if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:ic,streamId:t});delete n.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:sc,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;new Promise((function(t){t(s(e.data,o))})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:lc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:lc,streamId:t,reason:wrapReason(e)})}))}#_(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this.streamControllers[t],s=this.streamSinks[t];switch(e.stream){case lc:e.success?n.startCall.resolve():n.startCall.reject(wrapReason(e.reason));break;case cc:e.success?n.pullCall.resolve():n.pullCall.reject(wrapReason(e.reason));break;case oc:if(!s){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,success:!0});break}s.desiredSize<=0&&e.desiredSize>0&&s.sinkCapability.resolve();s.desiredSize=e.desiredSize;new Promise((function(e){e(s.onPull?.())})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,reason:wrapReason(e)})}));break;case nc:assert(n,"enqueue should have stream controller");if(n.isClosed)break;n.controller.enqueue(e.chunk);break;case ic:assert(n,"close should have stream controller");if(n.isClosed)break;n.isClosed=!0;n.controller.close();this.#X(n,t);break;case sc:assert(n,"error should have stream controller");n.controller.error(wrapReason(e.reason));this.#X(n,t);break;case rc:e.success?n.cancelCall.resolve():n.cancelCall.reject(wrapReason(e.reason));this.#X(n,t);break;case ac:if(!s)break;new Promise((function(t){t(s.onCancel?.(wrapReason(e.reason)))})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:rc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:rc,streamId:t,reason:wrapReason(e)})}));s.sinkCapability.reject(wrapReason(e.reason));s.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#X(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const a=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(a);return a}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,a){this._msgHandler=a;this.onProgress=null;const r=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=r.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static setup(e,t){let a=!1;e.on("test",(function(t){if(!a){a=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(function(e){!function setVerbosityLevel(e){Number.isInteger(e)&&(na=e)}(e.verbosity)}));e.on("GetDocRequest",(function(e){return WorkerMessageHandler.createDocumentHandler(e,t)}))}static createDocumentHandler(e,t){let a,r=!1,i=null;const n=new Set,s=getVerbosityLevel(),{docId:o,apiVersion:c}=e,l="4.1.392";if(c!==l)throw new Error(`The API version "${c}" does not match the Worker version "${l}".`);const h=[];for(const e in[])h.push(e);if(h.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+h.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const u=o+"_worker";let d=new MessageHandler(u,o,t);function ensureNotTerminated(){if(r)throw new Error("Worker was terminated")}function startWorkerTask(e){n.add(e)}function finishWorkerTask(e){e.finish();n.delete(e)}async function loadDocument(e){await a.ensureDoc("checkHeader");await a.ensureDoc("parseStartXRef");await a.ensureDoc("parse",[e]);await a.ensureDoc("checkFirstPage",[e]);await a.ensureDoc("checkLastPage",[e]);const t=await a.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([a.loadXfaFonts(d,e).catch((e=>{})).then((()=>finishWorkerTask(e))),a.loadXfaImages()])}const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("fingerprints")]);return{numPages:r,fingerprints:i,htmlForXfa:t?await a.ensureDoc("htmlForXfa"):null}}function getPdfManager({data:e,password:t,disableAutoFetch:a,rangeChunkSize:r,length:n,docBaseUrl:s,enableXfa:c,evaluatorOptions:l}){const h={source:null,disableAutoFetch:a,docBaseUrl:s,docId:o,enableXfa:c,evaluatorOptions:l,handler:d,length:n,password:t,rangeChunkSize:r},u=Promise.withResolvers();let f;if(e){try{h.source=e;f=new LocalPdfManager(h);u.resolve(f)}catch(e){u.reject(e)}return u.promise}let g,p=[];try{g=new PDFWorkerStream(d)}catch(e){u.reject(e);return u.promise}const m=g.getFullReader();m.headersReady.then((function(){if(m.isRangeSupported){h.source=g;h.length=m.contentLength;h.disableAutoFetch||=m.isStreamingSupported;f=new NetworkPdfManager(h);for(const e of p)f.sendProgressiveData(e);p=[];u.resolve(f);i=null}})).catch((function(e){u.reject(e);i=null}));let b=0;new Promise((function(e,t){const readChunk=function({value:e,done:a}){try{ensureNotTerminated();if(a){f||function(){const e=arrayBuffersToBytes(p);n&&e.length!==n&&warn("reported HTTP length is different from actual");try{h.source=e;f=new LocalPdfManager(h);u.resolve(f)}catch(e){u.reject(e)}p=[]}();i=null;return}b+=e.byteLength;m.isStreamingSupported||d.send("DocProgress",{loaded:b,total:Math.max(b,m.contentLength||0)});f?f.sendProgressiveData(e):p.push(e);m.read().then(readChunk,t)}catch(e){t(e)}};m.read().then(readChunk,t)})).catch((function(e){u.reject(e);i=null}));i=function(e){g.cancelAllRequests(e)};return u.promise}d.on("GetPage",(function(e){return a.getPage(e.pageIndex).then((function(e){return Promise.all([a.ensure(e,"rotate"),a.ensure(e,"ref"),a.ensure(e,"userUnit"),a.ensure(e,"view")]).then((function([e,t,a,r]){return{rotate:e,ref:t,userUnit:a,view:r}}))}))}));d.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return a.ensureCatalog("getPageIndex",[t])}));d.on("GetDestinations",(function(e){return a.ensureCatalog("destinations")}));d.on("GetDestination",(function(e){return a.ensureCatalog("getDestination",[e.id])}));d.on("GetPageLabels",(function(e){return a.ensureCatalog("pageLabels")}));d.on("GetPageLayout",(function(e){return a.ensureCatalog("pageLayout")}));d.on("GetPageMode",(function(e){return a.ensureCatalog("pageMode")}));d.on("GetViewerPreferences",(function(e){return a.ensureCatalog("viewerPreferences")}));d.on("GetOpenAction",(function(e){return a.ensureCatalog("openAction")}));d.on("GetAttachments",(function(e){return a.ensureCatalog("attachments")}));d.on("GetDocJSActions",(function(e){return a.ensureCatalog("jsActions")}));d.on("GetPageJSActions",(function({pageIndex:e}){return a.getPage(e).then((function(e){return a.ensure(e,"jsActions")}))}));d.on("GetOutline",(function(e){return a.ensureCatalog("documentOutline")}));d.on("GetOptionalContentConfig",(function(e){return a.ensureCatalog("optionalContentConfig")}));d.on("GetPermissions",(function(e){return a.ensureCatalog("permissions")}));d.on("GetMetadata",(function(e){return Promise.all([a.ensureDoc("documentInfo"),a.ensureCatalog("metadata")])}));d.on("GetMarkInfo",(function(e){return a.ensureCatalog("markInfo")}));d.on("GetData",(function(e){return a.requestLoadedStream().then((function(e){return e.bytes}))}));d.on("GetAnnotations",(function({pageIndex:e,intent:t}){return a.getPage(e).then((function(a){const r=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(r);return a.getAnnotationsData(d,r,t).then((e=>{finishWorkerTask(r);return e}),(e=>{finishWorkerTask(r);throw e}))}))}));d.on("GetFieldObjects",(function(e){return a.ensureDoc("fieldObjects")}));d.on("HasJSActions",(function(e){return a.ensureDoc("hasJSActions")}));d.on("GetCalculationOrderIds",(function(e){return a.ensureDoc("calculationOrderIds")}));d.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:r,filename:i}){const n=[a.requestLoadedStream(),a.ensureCatalog("acroForm"),a.ensureCatalog("acroFormRef"),a.ensureDoc("startXRef"),a.ensureDoc("xref"),a.ensureDoc("linearization"),a.ensureCatalog("structTreeRoot")],s=[],o=e?null:getNewAnnotationsMap(r),[c,l,h,u,f,g,p]=await Promise.all(n),m=f.trailer.getRaw("Root")||null;let b;if(o){p?await p.canUpdateStructTree({pdfManager:a,xref:f,newAnnotationsByPage:o})&&(b=p):await StructTreeRoot.canCreateStructureTree({catalogRef:m,pdfManager:a,newAnnotationsByPage:o})&&(b=null);const e=AnnotationFactory.generateImages(r.values(),f,a.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===b?s:[];for(const[r,i]of o)t.push(a.getPage(r).then((t=>{const a=new WorkerTask(`Save (editor): page ${r}`);return t.saveNewAnnotations(d,a,i,e).finally((function(){finishWorkerTask(a)}))})));null===b?s.push(Promise.all(t).then((async e=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:f,catalogRef:m,pdfManager:a,newRefs:e});return e}))):b&&s.push(Promise.all(t).then((async e=>{await b.updateStructureTree({newAnnotationsByPage:o,pdfManager:a,newRefs:e});return e})))}if(e)s.push(a.serializeXfaData(r));else for(let e=0;ee.needAppearances)),k=l instanceof Dict&&l.get("XFA")||null;let C=null,v=!1;if(Array.isArray(k)){for(let e=0,t=k.length;e{"string"==typeof a&&(e[t]=stringToPDFString(a))}));F={rootRef:m,encryptRef:f.trailer.getRaw("Encrypt")||null,newRef:f.getNewTemporaryRef(),infoRef:f.trailer.getRaw("Info")||null,info:e,fileIds:f.trailer.get("ID")||null,startXRef:g?u:f.lastXRefStreamPos??u,filename:i}}return incrementalUpdate({originalData:c.bytes,xrefInfo:F,newRefs:w,xref:f,hasXfa:!!k,xfaDatasetsRef:C,hasXfaDatasetsEntry:v,needAppearances:S,acroFormRef:h,acroForm:l,xfaData:x,useXrefStream:isDict(f.topDict,"XRef")}).finally((()=>{f.resetNewTemporaryRef()}))}));d.on("GetOperatorList",(function(e,t){const r=e.pageIndex;a.getPage(r).then((function(a){const i=new WorkerTask(`GetOperatorList: page ${r}`);startWorkerTask(i);const n=s>=Se.INFOS?Date.now():0;a.getOperatorList({handler:d,sink:t,task:i,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage}).then((function(e){finishWorkerTask(i);n&&info(`page=${r+1} - getOperatorList: time=${Date.now()-n}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));d.on("GetTextContent",(function(e,t){const{pageIndex:r,includeMarkedContent:i,disableNormalization:n}=e;a.getPage(r).then((function(e){const a=new WorkerTask("GetTextContent: page "+r);startWorkerTask(a);const o=s>=Se.INFOS?Date.now():0;e.extractTextContent({handler:d,task:a,sink:t,includeMarkedContent:i,disableNormalization:n}).then((function(){finishWorkerTask(a);o&&info(`page=${r+1} - getTextContent: time=`+(Date.now()-o)+"ms");t.close()}),(function(e){finishWorkerTask(a);a.terminated||t.error(e)}))}))}));d.on("GetStructTree",(function(e){return a.getPage(e.pageIndex).then((function(e){return a.ensure(e,"getStructTree")}))}));d.on("FontFallback",(function(e){return a.fontFallback(e.id,d)}));d.on("Cleanup",(function(e){return a.cleanup(!0)}));d.on("Terminate",(function(e){r=!0;const t=[];if(a){a.terminate(new AbortException("Worker was terminated."));const e=a.cleanup();t.push(e);a=null}else clearGlobalCaches();i&&i(new AbortException("Worker was terminated."));for(const e of n){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){d.destroy();d=null}))}));d.on("Ready",(function(t){!function setupDoc(e){function onSuccess(e){ensureNotTerminated();d.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);d.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);a.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);d.send("DocException",e)}))}else e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException?d.send("DocException",e):d.send("DocException",new UnknownErrorException(e.message,e.toString()))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?a.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();getPdfManager(e).then((function(e){if(r){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}a=e;a.requestLoadedStream(!0).then((e=>{d.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}(e);e=null}));return u}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);WorkerMessageHandler.setup(t,e);t.send("ready",null)}}"undefined"==typeof window&&!t&&"undefined"!=typeof self&&function isMessagePort(e){return"function"==typeof e.postMessage&&"onmessage"in e}(self)&&WorkerMessageHandler.initializeFromPort(self);var hc=__webpack_exports__.WorkerMessageHandler;export{hc as WorkerMessageHandler}; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c29b190..c2e7406 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,16 +1,16 @@ { - "name": "chatgpt-api-ui", + "name": "smoothgpt", "version": "0.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "chatgpt-api-ui", + "name": "smoothgpt", "version": "0.0.0", "dependencies": { - "highlight.js": "^11.9.0", "idb": "^8.0.0", "openai": "^3.2.1", + "pdfjs-dist": "^4.1.392", "puppeteer": "^22.6.1", "sse.js": "^0.6.1", "svelte-markdown": "^0.2.3" @@ -440,6 +440,66 @@ "@jridgewell/sourcemap-codec": "1.4.14" } }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "optional": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -567,6 +627,12 @@ "@types/node": "*" } }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "optional": true + }, "node_modules/acorn": { "version": "7.4.1", "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz", @@ -642,6 +708,25 @@ "node": ">= 8" } }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", + "optional": true + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "optional": true, + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/arg": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", @@ -719,7 +804,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "devOptional": true }, "node_modules/bare-events": { "version": "2.2.2", @@ -794,7 +879,7 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, + "devOptional": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -908,6 +993,21 @@ } ] }, + "node_modules/canvas": { + "version": "2.11.2", + "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.11.2.tgz", + "integrity": "sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==", + "hasInstallScript": true, + "optional": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.0", + "nan": "^2.17.0", + "simple-get": "^3.0.3" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -948,6 +1048,15 @@ "fsevents": "~2.3.2" } }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "optional": true, + "engines": { + "node": ">=10" + } + }, "node_modules/chromium-bidi": { "version": "0.5.14", "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.5.14.tgz", @@ -992,6 +1101,15 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "optional": true, + "bin": { + "color-support": "bin.js" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -1007,7 +1125,13 @@ "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true + "devOptional": true + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "optional": true }, "node_modules/cosmiconfig": { "version": "9.0.0", @@ -1070,6 +1194,18 @@ } } }, + "node_modules/decompress-response": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-4.2.1.tgz", + "integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==", + "optional": true, + "dependencies": { + "mimic-response": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/deepmerge": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.0.tgz", @@ -1109,6 +1245,12 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "optional": true + }, "node_modules/detect-indent": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", @@ -1118,6 +1260,15 @@ "node": ">=8" } }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "optional": true, + "engines": { + "node": ">=8" + } + }, "node_modules/detective": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/detective/-/detective-5.2.1.tgz", @@ -1421,11 +1572,35 @@ "node": ">=14.14" } }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true + "devOptional": true }, "node_modules/fsevents": { "version": "2.3.2", @@ -1447,6 +1622,26 @@ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "optional": true, + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -1487,7 +1682,7 @@ "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, + "devOptional": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -1540,13 +1735,11 @@ "node": ">=4" } }, - "node_modules/highlight.js": { - "version": "11.9.0", - "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.9.0.tgz", - "integrity": "sha512-fJ7cW7fQGCYAkgv4CPfwFHrfd/cLS4Hau96JuJ+ZTOWhjnhoeN1ub1tFmALm/+lW5z4WCAuAV9bm05AP0mS6Gw==", - "engines": { - "node": ">=12.0.0" - } + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "optional": true }, "node_modules/http-proxy-agent": { "version": "7.0.2", @@ -1621,7 +1814,7 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, + "devOptional": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -1631,7 +1824,7 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "devOptional": true }, "node_modules/ip-address": { "version": "9.0.5", @@ -1792,6 +1985,30 @@ "node": ">=12" } }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "optional": true, + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "optional": true, + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/marked": { "version": "4.2.12", "resolved": "https://registry.npmjs.org/marked/-/marked-4.2.12.tgz", @@ -1844,6 +2061,18 @@ "node": ">= 0.6" } }, + "node_modules/mimic-response": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.1.0.tgz", + "integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==", + "optional": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/min-indent": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", @@ -1857,7 +2086,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, + "devOptional": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -1874,6 +2103,40 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "optional": true, + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "optional": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/mitt": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", @@ -1905,6 +2168,12 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, + "node_modules/nan": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.19.0.tgz", + "integrity": "sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw==", + "optional": true + }, "node_modules/nanoid": { "version": "3.3.4", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", @@ -1925,12 +2194,47 @@ "node": ">= 0.4.0" } }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "optional": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, "node_modules/node-releases": { "version": "2.0.10", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.10.tgz", "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", "dev": true }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "optional": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -1949,6 +2253,27 @@ "node": ">=0.10.0" } }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "optional": true, + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-hash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", @@ -2037,7 +2362,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, + "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -2048,6 +2373,27 @@ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, + "node_modules/path2d": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path2d/-/path2d-0.1.2.tgz", + "integrity": "sha512-LW++2uxgHNL/FANhgGTPo/yDDQcgsVbKotwIVbpTgTBgRlKUpjOpjp3s3+KjG4OWCQ/r6z+WLDljH1/fC03PWw==", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pdfjs-dist": { + "version": "4.1.392", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-4.1.392.tgz", + "integrity": "sha512-fUV14+CG81uDLjgZ2Nmy35GvJsLIekotJb2VhXAoUfMCrWHhQtPJbqryUuevAdSHyEiAdr675ULikoD087+lMg==", + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "canvas": "^2.11.2", + "path2d": "^0.1.2" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -2325,6 +2671,20 @@ "pify": "^2.3.0" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -2443,6 +2803,26 @@ "node": ">=6" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "optional": true + }, "node_modules/sander": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/sander/-/sander-0.5.1.tgz", @@ -2497,6 +2877,49 @@ "node": ">=10" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "optional": true + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "optional": true + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "optional": true + }, + "node_modules/simple-get": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz", + "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==", + "optional": true, + "dependencies": { + "decompress-response": "^4.2.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", @@ -2594,6 +3017,15 @@ "bare-events": "^2.2.0" } }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -2931,6 +3363,23 @@ "node": ">=10.13.0" } }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "optional": true, + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/tar-fs": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.5.tgz", @@ -2954,6 +3403,18 @@ "streamx": "^2.15.0" } }, + "node_modules/tar/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "optional": true, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/through": { "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", @@ -2971,6 +3432,12 @@ "node": ">=8.0" } }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "optional": true + }, "node_modules/tslib": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", @@ -3047,7 +3514,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true + "devOptional": true }, "node_modules/vite": { "version": "4.1.4", @@ -3112,6 +3579,31 @@ } } }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "optional": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "optional": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "optional": true, + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", diff --git a/package.json b/package.json index 7d44b84..98f7558 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,10 @@ { - "name": "chatgpt-api-ui", + "name": "smoothgpt", "private": true, "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "vite build", "preview": "vite preview", "check": "svelte-check --tsconfig ./tsconfig.json" @@ -25,6 +25,7 @@ "dependencies": { "idb": "^8.0.0", "openai": "^3.2.1", + "pdfjs-dist": "^4.1.392", "puppeteer": "^22.6.1", "sse.js": "^0.6.1", "svelte-markdown": "^0.2.3" diff --git a/public/workers/pdf.worker.min.mjs b/public/workers/pdf.worker.min.mjs new file mode 100644 index 0000000..a8b24a3 --- /dev/null +++ b/public/workers/pdf.worker.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2023 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var e={d:(t,a)=>{for(var r in a)e.o(a,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:a[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},__webpack_exports__=globalThis.pdfjsWorker={};e.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],i=1.35,n=.35,s=.25925925925925924,o=1,c=2,l=4,h=8,u=16,d=64,f=256,g="pdfjs_internal_editor_",p=3,m=9,b=13,y=15,w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},x=0,S=4,k=1,C=2,v=3,F=1,O=2,T=3,M=4,D=5,R=6,N=7,E=8,L=9,j=10,_=11,U=12,X=13,q=14,H=15,z=16,W=17,$=20,G="Group",V="R",K=1,J=2,Y=4,Z=16,Q=32,ee=128,te=512,ae=1,re=2,ie=4096,ne=8192,se=32768,oe=65536,ce=131072,le=1048576,he=2097152,ue=8388608,de=16777216,fe=1,ge=2,pe=3,me=4,be=5,ye={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},we={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},xe={O:"PageOpen",C:"PageClose"},Se={ERRORS:0,WARNINGS:1,INFOS:5},ke={NONE:0,BINARY:1},Ae=1,Ce=2,ve=3,Fe=4,Ie=5,Oe=6,Te=7,Me=8,De=9,Be=10,Re=11,Ne=12,Ee=13,Pe=14,Le=15,je=16,_e=17,Ue=18,Xe=19,qe=20,He=21,ze=22,We=23,$e=24,Ge=25,Ve=26,Ke=27,Je=28,Ye=29,Ze=30,Qe=31,et=32,tt=33,at=34,rt=35,it=36,nt=37,st=38,ot=39,ct=40,lt=41,ht=42,ut=43,dt=44,ft=45,gt=46,pt=47,mt=48,bt=49,yt=50,wt=51,xt=52,St=53,kt=54,At=55,Ct=56,vt=57,Ft=58,It=59,Ot=60,Tt=61,Mt=62,Dt=63,Bt=64,Rt=65,Nt=66,Et=67,Pt=68,Lt=69,jt=70,_t=71,Ut=72,Xt=73,qt=74,Ht=75,zt=76,Wt=77,$t=80,Gt=81,Vt=83,Kt=84,Jt=85,Yt=86,Zt=87,Qt=88,ea=89,ta=90,aa=91,ra=1,ia=2;let na=Se.WARNINGS;function getVerbosityLevel(){return na}function info(e){na>=Se.INFOS&&console.log(`Info: ${e}`)}function warn(e){na>=Se.WARNINGS&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,a=null){if(!e)return null;try{if(a&&"string"==typeof e){if(a.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(a.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const r=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(r))return r}catch{}return null}function shadow(e,t,a,r=!1){Object.defineProperty(e,t,{value:a,enumerable:!r,configurable:!0,writable:!1});return a}const sa=function BaseExceptionClosure(){function BaseException(e,t){this.constructor===BaseException&&unreachable("Cannot initialize BaseException.");this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends sa{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends sa{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends sa{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends sa{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends sa{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends sa{constructor(e){super(e,"FormatError")}}class AbortException extends sa{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,a=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac")}):shadow(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const oa=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,a){return`#${oa[e]}${oa[t]}${oa[a]}`}static scaleMinMax(e,t){let a;if(e[0]){if(e[0]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[3];t[3]*=e[3]}else{a=t[0];t[0]=t[1];t[1]=a;a=t[2];t[2]=t[3];t[3]=a;if(e[1]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const a=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/a,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/a]}static getAxialAlignedBoundingBox(e,t){const a=this.applyTransform(e,t),r=this.applyTransform(e.slice(2,4),t),i=this.applyTransform([e[0],e[3]],t),n=this.applyTransform([e[2],e[1]],t);return[Math.min(a[0],r[0],i[0],n[0]),Math.min(a[1],r[1],i[1],n[1]),Math.max(a[0],r[0],i[0],n[0]),Math.max(a[1],r[1],i[1],n[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],a=e[0]*t[0]+e[1]*t[2],r=e[0]*t[1]+e[1]*t[3],i=e[2]*t[0]+e[3]*t[2],n=e[2]*t[1]+e[3]*t[3],s=(a+n)/2,o=Math.sqrt((a+n)**2-4*(a*n-i*r))/2,c=s+o||1,l=s-o||1;return[Math.sqrt(c),Math.sqrt(l)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const a=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(a>r)return null;const i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),n=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>n?null:[a,i,r,n]}static#e(e,t,a,r,i,n,s,o,c,l){if(c<=0||c>=1)return;const h=1-c,u=c*c,d=u*c,f=h*(h*(h*e+3*c*t)+3*u*a)+d*r,g=h*(h*(h*i+3*c*n)+3*u*s)+d*o;l[0]=Math.min(l[0],f);l[1]=Math.min(l[1],g);l[2]=Math.max(l[2],f);l[3]=Math.max(l[3],g)}static#t(e,t,a,r,i,n,s,o,c,l,h,u){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,a,r,i,n,s,o,-h/l,u);return}const d=l**2-4*h*c;if(d<0)return;const f=Math.sqrt(d),g=2*c;this.#e(e,t,a,r,i,n,s,o,(-l+f)/g,u);this.#e(e,t,a,r,i,n,s,o,(-l-f)/g,u)}static bezierBoundingBox(e,t,a,r,i,n,s,o,c){if(c){c[0]=Math.min(c[0],e,s);c[1]=Math.min(c[1],t,o);c[2]=Math.max(c[2],e,s);c[3]=Math.max(c[3],t,o)}else c=[Math.min(e,s),Math.min(t,o),Math.max(e,s),Math.max(t,o)];this.#t(e,a,i,s,t,r,n,o,3*(3*(a-i)-e+s),6*(e-2*a+i),3*(a-e),c);this.#t(e,a,i,s,t,r,n,o,3*(3*(r-n)-t+o),6*(t-2*r+n),3*(r-t),c);return c}}const ca=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const a=new TextDecoder(t,{fatal:!0}),r=stringToBytes(e),i=a.decode(r);return i.includes("")?i.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):i}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let a=0,r=e.length;a{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:a=!1}){const r=new Dict(e),i=new Map;for(const e of t)if(e instanceof Dict)for(const[t,r]of Object.entries(e._map)){let e=i.get(t);if(void 0===e){e=[];i.set(t,e)}else if(!(a&&r instanceof Dict))continue;e.push(r)}for(const[t,a]of i){if(1===a.length||!(a[0]instanceof Dict)){r._map[t]=a[0];continue}const i=new Dict(e);for(const e of a)for(const[t,a]of Object.entries(e._map))void 0===i._map[t]&&(i._map[t]=a);i.size>0&&(r._map[t]=i)}i.clear();return r.size>0?r:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=pa[e];if(t)return t;const a=/^(\d+)R(\d*)$/.exec(e);return a&&"0"!==a[1]?pa[e]=new Ref(parseInt(a[1]),a[2]?parseInt(a[2]):0):null}static get(e,t){const a=0===t?`${e}R`:`${e}R${t}`;return pa[a]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{constructor(){this.constructor===BaseStream&&unreachable("Cannot initialize BaseStream.")}get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,a=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const ba=/^[1-9]\.\d$/;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends sa{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends sa{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends sa{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends sa{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let a=0;for(let r=0;r0,"The number should be a positive integer.");const a=[];let r;for(;e>=1e3;){e-=1e3;a.push("M")}r=e/100|0;e%=100;a.push(ya[r]);r=e/10|0;e%=10;a.push(ya[10+r]);a.push(ya[20+e]);const i=a.join("");return t?i.toLowerCase():i}function log2(e){return e<=0?0:Math.ceil(Math.log2(e))}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const a=e.match(t);return a?{name:a[1],pos:parseInt(a[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let a=0;for(let r=0,i=e.length;r126||35===i||40===i||41===i||60===i||62===i||91===i||93===i||123===i||125===i||47===i||37===i){a"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,a,r){if(!e)return;let i=null;if(e instanceof Ref){if(r.has(e))return;i=e;r.put(i);e=t.fetch(e)}if(Array.isArray(e))for(const i of e)_collectJS(i,t,a,r);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let r;t instanceof BaseStream?r=t.getString():"string"==typeof t&&(r=t);r&&=stringToPDFString(r).replaceAll("\0","");r&&a.push(r)}_collectJS(e.getRaw("Next"),t,a,r)}i&&r.remove(i)}function collectActions(e,t,a){const r=Object.create(null),i=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(i)for(let t=i.length-1;t>=0;t--){const n=i[t];if(n instanceof Dict)for(const t of n.getKeys()){const i=a[t];if(!i)continue;const s=[];_collectJS(n.getRaw(t),e,s,new RefSet);s.length>0&&(r[i]=s)}}if(t.has("A")){const a=[];_collectJS(t.get("A"),e,a,new RefSet);a.length>0&&(r.Action=a)}return objectSize(r)>0?r:null}const wa={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,a=e.length;t55295&&(a<57344||a>65533)&&t++;yield a}}function encodeToXmlString(e){const t=[];let a=0;for(let r=0,i=e.length;r55295&&(i<57344||i>65533)&&r++;a=r+1}}if(0===t.length)return e;a: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:a,fontWeight:r,italicAngle:i}=e;if(!validateFontName(a,!0))return!1;const n=r?r.toString():"";e.fontWeight=t.has(n)?n:"400";const s=parseFloat(i);e.italicAngle=isNaN(s)||s<-90||s>90?"14":i.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);if(t?.[2]){const e=t[2];let a=!1;"true"===t[3]&&"app.launchURL"===t[1]&&(a=!0);return{url:e,newWindow:a}}return null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[a,r]of e){if(!a.startsWith(g))continue;let e=t.get(r.pageIndex);if(!e){e=[];t.set(r.pageIndex,e)}e.push(r)}return t.size>0?t:null}function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}function stringToUTF16HexString(e){const t=[];for(let a=0,r=e.length;a>8&255).toString(16).padStart(2,"0"),(255&r).toString(16).padStart(2,"0"))}return t.join("")}function stringToUTF16String(e,t=!1){const a=[];t&&a.push("þÿ");for(let t=0,r=e.length;t>8&255),String.fromCharCode(255&r))}return a.join("")}function getRotationMatrix(e,t,a){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,a];case 270:return[0,-1,1,0,0,a];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,a,r){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+a||this.bytes.length;this.dict=r}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e)return t.subarray(a,r);let i=a+e;i>r&&(i=r);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,a=null){return new Stream(this.bytes.buffer,e,t,a)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,a){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=a;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,a=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=a;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const a=Math.floor(e/this.chunkSize);if(a>this.numChunks)return;const r=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let i=a;i=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e){r>this.progressiveDataLength&&this.ensureRange(a,r);return t.subarray(a,r)}let i=a+e;i>r&&(i=r);i>this.progressiveDataLength&&this.ensureRange(a,i);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,a=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),a=Math.floor((this.end-1)/e)+1,r=[];for(let e=t;e{const readChunk=({value:n,done:s})=>{try{if(s){const t=arrayBuffersToBytes(r);r=null;e(t);return}i+=n.byteLength;a.isStreamingSupported&&this.onProgress({loaded:i});r.push(n);a.read().then(readChunk,t)}catch(e){t(e)}};a.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,a=new Set;this._chunksNeededByRequest.set(t,a);for(const t of e)this.stream.hasChunk(t)||a.add(t);if(0===a.size)return Promise.resolve();const r=Promise.withResolvers();this._promisesByRequest.set(t,r);const i=[];for(const e of a){let a=this._requestsByChunk.get(e);if(!a){a=[];this._requestsByChunk.set(e,a);i.push(e)}a.push(t)}if(i.length>0){const e=this.groupChunks(i);for(const t of e){const e=t.beginChunk*this.chunkSize,a=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,a).catch(r.reject)}}return r.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const a=this.getBeginChunk(e),r=this.getEndChunk(t),i=[];for(let e=a;e=0&&r+1!==n){t.push({beginChunk:a,endChunk:r+1});a=n}i+1===e.length&&t.push({beginChunk:a,endChunk:n+1});r=n}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,a=void 0===e.begin,r=a?this.progressiveDataLength:e.begin,i=r+t.byteLength,n=Math.floor(r/this.chunkSize),s=i0||o.push(a)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(s);Number.isInteger(e)&&this._requestChunks([e])}for(const e of o){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}class ColorSpace{constructor(e,t){this.constructor===ColorSpace&&unreachable("Cannot initialize ColorSpace.");this.name=e;this.numComps=t}getRgb(e,t){const a=new Uint8ClampedArray(3);this.getRgbItem(e,t,a,0);return a}getRgbItem(e,t,a,r){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,a,r,i,n,s){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,a,r,i,n,s,o,c){const l=t*a;let h=null;const u=1<u&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=s<=8?new Uint8Array(u):new Uint16Array(u);for(let e=0;e=.99554525?1:this.#p(0,1,1.055*e**(1/2.4)-.055)}#p(e,t,a){return Math.max(e,Math.min(t,a))}#m(e){return e<0?-this.#m(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#h}#b(e,t,a){if(0===e[0]&&0===e[1]&&0===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=this.#m(0),i=(1-r)/(1-this.#m(e[0])),n=1-i,s=(1-r)/(1-this.#m(e[1])),o=1-s,c=(1-r)/(1-this.#m(e[2])),l=1-c;a[0]=t[0]*i+n;a[1]=t[1]*s+o;a[2]=t[2]*c+l}#y(e,t,a){if(1===e[0]&&1===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=a;this.#u(CalRGBCS.#r,t,r);const i=CalRGBCS.#o;this.#d(e,r,i);this.#u(CalRGBCS.#i,i,a)}#w(e,t,a){const r=a;this.#u(CalRGBCS.#r,t,r);const i=CalRGBCS.#o;this.#f(e,r,i);this.#u(CalRGBCS.#i,i,a)}#a(e,t,a,r,i){const n=this.#p(0,1,e[t]*i),s=this.#p(0,1,e[t+1]*i),o=this.#p(0,1,e[t+2]*i),c=1===n?1:n**this.GR,l=1===s?1:s**this.GG,h=1===o?1:o**this.GB,u=this.MXA*c+this.MXB*l+this.MXC*h,d=this.MYA*c+this.MYB*l+this.MYC*h,f=this.MZA*c+this.MZB*l+this.MZC*h,g=CalRGBCS.#c;g[0]=u;g[1]=d;g[2]=f;const p=CalRGBCS.#l;this.#y(this.whitePoint,g,p);const m=CalRGBCS.#c;this.#b(this.blackPoint,p,m);const b=CalRGBCS.#l;this.#w(CalRGBCS.#s,m,b);const y=CalRGBCS.#c;this.#u(CalRGBCS.#n,b,y);a[r]=255*this.#g(y[0]);a[r+1]=255*this.#g(y[1]);a[r+2]=255*this.#g(y[2])}getRgbItem(e,t,a,r){this.#a(e,t,a,r,1)}getRgbBuffer(e,t,a,r,i,n,s){const o=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#x(e){return e>=6/29?e**3:108/841*(e-4/29)}#S(e,t,a,r){return a+e*(r-a)/t}#a(e,t,a,r,i){let n=e[t],s=e[t+1],o=e[t+2];if(!1!==a){n=this.#S(n,a,0,100);s=this.#S(s,a,this.amin,this.amax);o=this.#S(o,a,this.bmin,this.bmax)}s>this.amax?s=this.amax:sthis.bmax?o=this.bmax:o>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,a){let r=0;for(let i=a;i>=0;i--){r+=e[i]+t[i];e[i]=255&r;r>>=8}}function incHex(e,t){let a=1;for(let r=t;r>=0&&a>0;r--){a+=e[r];e[r]=255&a;a>>=8}}const xa=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const a=this.readByte();if(a<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&a);t=t<<7|127&a}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let a;const r=this.tmpBuf;let i=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");a=!(128&e);r[i++]=127&e}while(!a);let n=t,s=0,o=0;for(;n>=0;){for(;o<8&&r.length>0;){s|=r[--i]<>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const a=1&e[t]?255:0;let r=0;for(let i=0;i<=t;i++){r=(1&r)<<8|e[i];e[i]=r>>1^a}}readString(){const e=this.readNumber(),t=new Array(e);for(let a=0;a=0;){const e=d>>5;if(7===e){switch(31&d){case 0:r.readString();break;case 1:n=r.readString()}continue}const a=!!(16&d),i=15&d;if(i+1>xa)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const f=1,g=r.readNumber();switch(e){case 0:r.readHex(s,i);r.readHexNumber(o,i);addHex(o,s,i);t.addCodespaceRange(i+1,hexToInt(s,i),hexToInt(o,i));for(let e=1;er&&(a=r)}else{for(;!this.eof;)this.readBlock();a=this.bufferLength}this.pos=a;return this.buffer.subarray(t,a)}reset(){this.pos=0}makeSubStream(e,t,a=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const a=e+t;for(;this.bufferLength<=a&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,a)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){let a=0;for(const t of e)a+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(a);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let a;try{a=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const r=this.bufferLength,i=r+a.length;this.ensureBuffer(i).set(a,r);this.bufferLength=i}getBaseStreams(){const e=[];for(const t of this.streams){const a=t.getBaseStreams();a&&e.push(...a)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const a=this.bufferLength;let r,i;if(122===t){r=this.ensureBuffer(a+4);for(i=0;i<4;++i)r[a+i]=0;this.bufferLength+=4}else{const n=this.input;n[0]=t;for(i=1;i<5;++i){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();n[i]=t;if(-1===t||126===t)break}r=this.ensureBuffer(a+i-1);this.bufferLength+=i-1;if(i<5){for(;i<5;++i)n[i]=117;this.eof=!0}let s=0;for(i=0;i<5;++i)s=85*s+(n[i]-33);for(i=3;i>=0;--i){r[a+i]=255&s;s>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,a=this.ensureBuffer(this.bufferLength+t);let r=this.bufferLength,i=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(i<0)i=e;else{a[r++]=i<<4|e;i=-1}}if(i>=0&&this.eof){a[r++]=i<<4;i=-1}this.firstDigit=i;this.bufferLength=r}}const ka=-1,Aa=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Ca=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],va=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Fa=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Ia=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Oa=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if(!e||"function"!=typeof e.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let a;for(;0===(a=this._lookBits(12));)this._eatBits(1);1===a&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,a=this.columns;let r,i,n,s,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let n,o,c;if(this.nextLine2D){for(s=0;t[s]=64);do{o+=c=this._getWhiteCode()}while(c>=64)}else{do{n+=c=this._getWhiteCode()}while(c>=64);do{o+=c=this._getBlackCode()}while(c>=64)}this._addPixels(t[this.codingPos]+n,i);t[this.codingPos]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]=64);else do{n+=c=this._getWhiteCode()}while(c>=64);this._addPixels(t[this.codingPos]+n,i);i^=1}}let l=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){n=this._lookBits(12);if(this.eoline)for(;n!==ka&&1!==n;){this._eatBits(1);n=this._lookBits(12)}else for(;0===n;){this._eatBits(1);n=this._lookBits(12)}if(1===n){this._eatBits(12);l=!0}else n===ka&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&l&&this.byteAlign){n=this._lookBits(12);if(1===n){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(s=0;s<4;++s){n=this._lookBits(12);1!==n&&info("bad rtc code: "+n);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){n=this._lookBits(13);if(n===ka){this.eof=!0;return-1}if(n>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&n)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]n){o<<=n;1&this.codingPos||(o|=255>>8-n);this.outputBits-=n;n=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);n-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){o<<=n;n=0}}}while(n)}this.black&&(o^=255);return o}_addPixels(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}this.codingPos=r}_addPixelsNeg(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}else if(e0&&e=i){const t=a[e-i];if(t[0]===r){this._eatBits(r);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=Aa[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,Aa);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return ka}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===ka)return 1;e=t>>5==0?Ca[t]:va[t>>3];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,va);if(e[0])return e[1];e=this._findTableCode(11,12,Ca);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===ka)return 1;t=e>>7==0?Fa[e]:e>>9==0&&e>>7!=0?Ia[(e>>1)-64]:Oa[e>>7];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Oa);if(e[0])return e[1];e=this._findTableCode(7,12,Ia,64);if(e[0])return e[1];e=this._findTableCode(10,13,Fa);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,a){super(t);this.str=e;this.dict=e.dict;a instanceof Dict||(a=Dict.empty);const r={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(r,{K:a.get("K"),EndOfLine:a.get("EndOfLine"),EncodedByteAlign:a.get("EncodedByteAlign"),Columns:a.get("Columns"),Rows:a.get("Rows"),EndOfBlock:a.get("EndOfBlock"),BlackIs1:a.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Ta=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ma=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Da=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Ba=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Ra=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const a=e.getByte(),r=e.getByte();if(-1===a||-1===r)throw new FormatError(`Invalid header in flate stream: ${a}, ${r}`);if(8!=(15&a))throw new FormatError(`Unknown compression method in flate stream: ${a}, ${r}`);if(((a<<8)+r)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${a}, ${r}`);if(32&r)throw new FormatError(`FDICT bit set in flate stream: ${a}, ${r}`);this.codeSize=0;this.codeBuf=0}getBits(e){const t=this.str;let a,r=this.codeSize,i=this.codeBuf;for(;r>e;this.codeSize=r-=e;return a}getCode(e){const t=this.str,a=e[0],r=e[1];let i,n=this.codeSize,s=this.codeBuf;for(;n>16,l=65535&o;if(c<1||n>c;this.codeSize=n-c;return l}generateHuffmanTable(e){const t=e.length;let a,r=0;for(a=0;ar&&(r=e[a]);const i=1<>=1}for(a=e;a>=1;if(0===n){let t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}let r=t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}r|=t<<8;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#k("Bad block header in flate stream");return}i|=t<<8;if(i!==(65535&~r)&&(0!==r||0!==i))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const n=this.bufferLength,s=n+r;e=this.ensureBuffer(s);this.bufferLength=s;if(0===r)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(r);e.set(t,n);t.length0;)h[o++]=f}r=this.generateHuffmanTable(h.subarray(0,e));i=this.generateHuffmanTable(h.subarray(e,l))}}e=this.buffer;let s=e?e.length:0,o=this.bufferLength;for(;;){let a=this.getCode(r);if(a<256){if(o+1>=s){e=this.ensureBuffer(o+1);s=e.length}e[o++]=a;continue}if(256===a){this.bufferLength=o;return}a-=257;a=Ma[a];let n=a>>16;n>0&&(n=this.getBits(n));t=(65535&a)+n;a=this.getCode(i);a=Da[a];n=a>>16;n>0&&(n=this.getBits(n));const c=(65535&a)+n;if(o+t>=s){e=this.ensureBuffer(o+t);s=e.length}for(let a=0;a>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let a=e[t]>>1,r=1&e[t];const i=Na[a],n=i.qe;let s,o=this.a-n;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(0==(32768&o));this.a=o;e[t]=a<<1|r;return s}}class Jbig2Error extends sa{constructor(e){super(`JBIG2 error: ${e}`,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,a){this.data=e;this.start=t;this.end=a}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}const Ea=2**31-1,Pa=-(2**31);function decodeInteger(e,t,a){const r=e.getContexts(t);let i=1;function readBits(e){let t=0;for(let n=0;n>>0}const n=readBits(1),s=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===n?o=s:s>0&&(o=-s);return o>=Pa&&o<=Ea?o:null}function decodeIAID(e,t,a){const r=e.getContexts("IAID");let i=1;for(let e=0;e=v&&E=F){q=q<<1&m;for(p=0;p=0&&j=0){_=D[L][j];_&&(q|=_<=e?l<<=1:l=l<<1|S[o][c]}for(f=0;f=w||c<0||c>=y?l<<=1:l=l<<1|r[o][c]}const g=k.readBit(C,l);t[s]=g}}return S}function decodeTextRegion(e,t,a,r,i,n,s,o,c,l,h,u,d,f,g,p,m,b,y){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const w=[];let x,S;for(x=0;x1&&(i=e?y.readBits(b):decodeInteger(C,"IAIT",k));const n=s*v+i,F=e?f.symbolIDTable.decode(y):decodeIAID(C,k,c),O=t&&(e?y.readBit():decodeInteger(C,"IARI",k));let T=o[F],M=T[0].length,D=T.length;if(O){const e=decodeInteger(C,"IARDW",k),t=decodeInteger(C,"IARDH",k);M+=e;D+=t;T=decodeRefinement(M,D,g,T,(e>>1)+decodeInteger(C,"IARDX",k),(t>>1)+decodeInteger(C,"IARDY",k),!1,p,m)}let R=0;l?1&u?R=D-1:r+=D-1:u>1?r+=M-1:R=M-1;const N=n-(1&u?0:D-1),E=r-(2&u?M-1:0);let L,j,_;if(l)for(L=0;L>5&7;const c=[31&s];let l=t+6;if(7===s){o=536870911&readUint32(e,l-1);l+=3;let t=o+7>>3;c[0]=e[l++];for(;--t>0;)c.push(e[l++])}else if(5===s||6===s)throw new Jbig2Error("invalid referred-to flags");a.retainBits=c;let h=4;a.number<=256?h=1:a.number<=65536&&(h=2);const u=[];let d,f;for(d=0;d>>24&255;n[3]=t.height>>16&255;n[4]=t.height>>8&255;n[5]=255&t.height;for(d=l,f=e.length;d>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;l+=2;if(!e.huffman){c=0===e.template?4:1;s=[];for(o=0;o>2&3;h.stripSize=1<>4&3;h.transposed=!!(64&u);h.combinationOperator=u>>7&3;h.defaultPixelValue=u>>9&1;h.dsOffset=u<<17>>27;h.refinementTemplate=u>>15&1;if(h.huffman){const e=readUint16(r,l);l+=2;h.huffmanFS=3&e;h.huffmanDS=e>>2&3;h.huffmanDT=e>>4&3;h.huffmanRefinementDW=e>>6&3;h.huffmanRefinementDH=e>>8&3;h.huffmanRefinementDX=e>>10&3;h.huffmanRefinementDY=e>>12&3;h.huffmanRefinementSizeSelector=!!(16384&e)}if(h.refinement&&!h.refinementTemplate){s=[];for(o=0;o<2;o++){s.push({x:readInt8(r,l),y:readInt8(r,l+1)});l+=2}h.refinementAt=s}h.numberOfSymbolInstances=readUint32(r,l);l+=4;n=[h,a.referredTo,r,l,i];break;case 16:const d={},f=r[l++];d.mmr=!!(1&f);d.template=f>>1&3;d.patternWidth=r[l++];d.patternHeight=r[l++];d.maxPatternIndex=readUint32(r,l);l+=4;n=[d,a.number,r,l,i];break;case 22:case 23:const g={};g.info=readRegionSegmentInformation(r,l);l+=qa;const p=r[l++];g.mmr=!!(1&p);g.template=p>>1&3;g.enableSkip=!!(8&p);g.combinationOperator=p>>4&7;g.defaultPixelValue=p>>7&1;g.gridWidth=readUint32(r,l);l+=4;g.gridHeight=readUint32(r,l);l+=4;g.gridOffsetX=4294967295&readUint32(r,l);l+=4;g.gridOffsetY=4294967295&readUint32(r,l);l+=4;g.gridVectorX=readUint16(r,l);l+=2;g.gridVectorY=readUint16(r,l);l+=2;n=[g,a.referredTo,r,l,i];break;case 38:case 39:const m={};m.info=readRegionSegmentInformation(r,l);l+=qa;const b=r[l++];m.mmr=!!(1&b);m.template=b>>1&3;m.prediction=!!(8&b);if(!m.mmr){c=0===m.template?4:1;s=[];for(o=0;o>2&1;y.combinationOperator=w>>3&3;y.requiresBuffer=!!(32&w);y.combinationOperatorOverride=!!(64&w);n=[y];break;case 49:case 50:case 51:case 62:break;case 53:n=[a.number,r,l,i];break;default:throw new Jbig2Error(`segment type ${a.typeName}(${a.type}) is not implemented`)}const h="on"+a.typeName;h in t&&t[h].apply(t,n)}function processSegments(e,t){for(let a=0,r=e.length;a>3,a=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&a.fill(255);this.buffer=a}drawBitmap(e,t){const a=this.currentPageInfo,r=e.width,i=e.height,n=a.width+7>>3,s=a.combinationOperatorOverride?e.combinationOperator:a.combinationOperator,o=this.buffer,c=128>>(7&e.x);let l,h,u,d,f=e.y*n+(e.x>>3);switch(s){case 0:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;case 2:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;default:throw new Jbig2Error(`operator ${s} is not supported`)}}onImmediateGenericRegion(e,t,a,r){const i=e.info,n=new DecodingContext(t,a,r),s=decodeBitmap(e.mmr,i.width,i.height,e.template,e.prediction,null,e.at,n);this.drawBitmap(i,s)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,a,r,i,n){let s,o;if(e.huffman){s=function getSymbolDictionaryHuffmanTables(e,t,a){let r,i,n,s,o=0;switch(e.huffmanDHSelector){case 0:case 1:r=getStandardTable(e.huffmanDHSelector+4);break;case 3:r=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:i=getStandardTable(e.huffmanDWSelector+2);break;case 3:i=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){n=getCustomHuffmanTable(o,t,a);o++}else n=getStandardTable(1);s=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,a):getStandardTable(1);return{tableDeltaHeight:r,tableDeltaWidth:i,tableBitmapSize:n,tableAggregateInstances:s}}(e,a,this.customTables);o=new Reader(r,i,n)}let c=this.symbols;c||(this.symbols=c={});const l=[];for(const e of a){const t=c[e];t&&l.push(...t)}const h=new DecodingContext(r,i,n);c[t]=function decodeSymbolDictionary(e,t,a,r,i,n,s,o,c,l,h,u){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const d=[];let f=0,g=log2(a.length+r);const p=h.decoder,m=h.contextCache;let b,y;if(e){b=getStandardTable(1);y=[];g=Math.max(g,1)}for(;d.length1)w=decodeTextRegion(e,t,r,f,0,i,1,a.concat(d),g,0,0,1,0,n,c,l,h,0,u);else{const e=decodeIAID(m,p,g),t=decodeInteger(m,"IARDX",p),i=decodeInteger(m,"IARDY",p);w=decodeRefinement(r,f,c,e=32){let a,r,s;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");r=i.readBits(2)+3;a=n[e-1].prefixLength;break;case 33:r=i.readBits(3)+3;a=0;break;case 34:r=i.readBits(7)+11;a=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(s=0;s=0;m--){T=e?decodeMMRBitmap(O,c,l,!0):decodeBitmap(!1,c,l,a,!1,null,v,g);F[m]=T}for(M=0;M=0;b--){R^=F[b][M][D];N|=R<>8;j=u+M*d-D*f>>8;if(L>=0&&L+S<=r&&j>=0&&j+k<=i)for(m=0;m=i)){U=p[t];_=E[m];for(b=0;b=0&&e>1&7),c=1+(r>>4&7),l=[];let h,u,d=i;do{h=s.readBits(o);u=s.readBits(c);l.push(new HuffmanLine([d,h,u,0]));d+=1<>t&1;if(t<=0)this.children[a]=new HuffmanTreeNode(e);else{let r=this.children[a];r||(this.children[a]=r=new HuffmanTreeNode(null));r.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,a=e.length;t0&&this.rootNode.buildTree(a,a.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let a=0;for(let r=0;r=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,a=0;for(t=e-1;t>=0;t--)a|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,a){let r=0;for(let i=0,n=t.length;i>a&1;a--}}if(r&&!o){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,o);if(FeatureTest.isLittleEndian){for(;s>>24|t<<8|4278190080;a[r+2]=t>>>16|i<<16|4278190080;a[r+3]=i>>>8|4278190080}for(let t=4*s,i=e.length;t>>8|255;a[r+2]=t<<16|i>>>16|255;a[r+3]=i<<8|255}for(let t=4*s,i=e.length;t>3,u=7&r,d=e.length;a=new Uint32Array(a.buffer);let f=0;for(let r=0;r0&&!e[n-1];)n--;const s=[{children:[],index:0}];let o,c=s[0];for(a=0;a0;)c=s.pop();c.index++;s.push(c);for(;s.length<=a;){s.push(o={children:[],index:0});c.children[c.index]=o.children;c=o}i++}if(a+10){g--;return f>>g&1}f=e[t++];if(255===f){const r=e[t++];if(r){if(220===r&&l){const r=readUint16(e,t+=2);t+=2;if(r>0&&r!==a.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",r)}else if(217===r){if(l){const e=y*(8===a.precision?8:0);if(e>0&&Math.round(a.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(f<<8|r).toString(16)}`)}}g=7;return f>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){p--;return}let a=n;const r=s;for(;a<=r;){const r=decodeHuffman(e.huffmanTableAC),i=15&r,n=r>>4;if(0===i){if(n<15){p=receive(n)+(1<>4;if(0===i)if(l<15){p=receive(l)+(1<>4;if(0===r){if(n<15)break;i+=16;continue}i+=n;const s=za[i];e.blockData[t+s]=receiveAndExtend(r);i++}};let O,T=0;const M=1===w?r[0].blocksPerLine*r[0].blocksPerColumn:h*a.mcusPerColumn;let D,R;for(;T<=M;){const a=i?Math.min(M-T,i):M;if(a>0){for(S=0;S0?"unexpected":"excessive"} MCU data, current marker is: ${O.invalid}`);t=O.offset}if(!(O.marker>=65488&&O.marker<=65495))break;t+=2}return t-d}function quantizeAndInverse(e,t,a){const r=e.quantizationTable,i=e.blockData;let n,s,o,c,l,h,u,d,f,g,p,m,b,y,w,x,S;if(!r)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){f=i[t+e];g=i[t+e+1];p=i[t+e+2];m=i[t+e+3];b=i[t+e+4];y=i[t+e+5];w=i[t+e+6];x=i[t+e+7];f*=r[e];if(0!=(g|p|m|b|y|w|x)){g*=r[e+1];p*=r[e+2];m*=r[e+3];b*=r[e+4];y*=r[e+5];w*=r[e+6];x*=r[e+7];n=Ya*f+128>>8;s=Ya*b+128>>8;o=p;c=w;l=Za*(g-x)+128>>8;d=Za*(g+x)+128>>8;h=m<<4;u=y<<4;n=n+s+1>>1;s=n-s;S=o*Ja+c*Ka+128>>8;o=o*Ka-c*Ja+128>>8;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Va+d*Ga+2048>>12;l=l*Ga-d*Va+2048>>12;d=S;S=h*$a+u*Wa+2048>>12;h=h*Wa-u*$a+2048>>12;u=S;a[e]=n+d;a[e+7]=n-d;a[e+1]=s+u;a[e+6]=s-u;a[e+2]=o+h;a[e+5]=o-h;a[e+3]=c+l;a[e+4]=c-l}else{S=Ya*f+512>>10;a[e]=S;a[e+1]=S;a[e+2]=S;a[e+3]=S;a[e+4]=S;a[e+5]=S;a[e+6]=S;a[e+7]=S}}for(let e=0;e<8;++e){f=a[e];g=a[e+8];p=a[e+16];m=a[e+24];b=a[e+32];y=a[e+40];w=a[e+48];x=a[e+56];if(0!=(g|p|m|b|y|w|x)){n=Ya*f+2048>>12;s=Ya*b+2048>>12;o=p;c=w;l=Za*(g-x)+2048>>12;d=Za*(g+x)+2048>>12;h=m;u=y;n=4112+(n+s+1>>1);s=n-s;S=o*Ja+c*Ka+2048>>12;o=o*Ka-c*Ja+2048>>12;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Va+d*Ga+2048>>12;l=l*Ga-d*Va+2048>>12;d=S;S=h*$a+u*Wa+2048>>12;h=h*Wa-u*$a+2048>>12;u=S;f=n+d;x=n-d;g=s+u;w=s-u;p=o+h;y=o-h;m=c+l;b=c-l;f<16?f=0:f>=4080?f=255:f>>=4;g<16?g=0:g>=4080?g=255:g>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;b<16?b=0:b>=4080?b=255:b>>=4;y<16?y=0:y>=4080?y=255:y>>=4;w<16?w=0:w>=4080?w=255:w>>=4;x<16?x=0:x>=4080?x=255:x>>=4;i[t+e]=f;i[t+e+8]=g;i[t+e+16]=p;i[t+e+24]=m;i[t+e+32]=b;i[t+e+40]=y;i[t+e+48]=w;i[t+e+56]=x}else{S=Ya*f+8192>>14;S=S<-2040?0:S>=2024?255:S+2056>>4;i[t+e]=S;i[t+e+8]=S;i[t+e+16]=S;i[t+e+24]=S;i[t+e+32]=S;i[t+e+40]=S;i[t+e+48]=S;i[t+e+56]=S}}}function buildComponentData(e,t){const a=t.blocksPerLine,r=t.blocksPerColumn,i=new Int16Array(64);for(let e=0;e=r)return null;const n=readUint16(e,t);if(n>=65472&&n<=65534)return{invalid:null,marker:n,offset:t};let s=readUint16(e,i);for(;!(s>=65472&&s<=65534);){if(++i>=r)return null;s=readUint16(e,i)}return{invalid:n.toString(16),marker:s,offset:i}}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}parse(e,{dnlScanLines:t=null}={}){function readDataBlock(){const t=readUint16(e,i);i+=2;let a=i+t-2;const r=findNextFileMarker(e,a,i);if(r?.invalid){warn("readDataBlock - incorrect length, current marker is: "+r.invalid);a=r.offset}const n=e.subarray(i,a);i+=n.length;return n}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),a=Math.ceil(e.scanLines/8/e.maxV);for(const r of e.components){const i=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/e.maxH),n=Math.ceil(Math.ceil(e.scanLines/8)*r.v/e.maxV),s=t*r.h,o=64*(a*r.v)*(s+1);r.blockData=new Int16Array(o);r.blocksPerLine=i;r.blocksPerColumn=n}e.mcusPerLine=t;e.mcusPerColumn=a}let a,r,i=0,n=null,s=null,o=0;const c=[],l=[],h=[];let u=readUint16(e,i);i+=2;if(65496!==u)throw new JpegError("SOI not found");u=readUint16(e,i);i+=2;e:for(;65497!==u;){let d,f,g;switch(u){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const p=readDataBlock();65504===u&&74===p[0]&&70===p[1]&&73===p[2]&&70===p[3]&&0===p[4]&&(n={version:{major:p[5],minor:p[6]},densityUnits:p[7],xDensity:p[8]<<8|p[9],yDensity:p[10]<<8|p[11],thumbWidth:p[12],thumbHeight:p[13],thumbData:p.subarray(14,14+3*p[12]*p[13])});65518===u&&65===p[0]&&100===p[1]&&111===p[2]&&98===p[3]&&101===p[4]&&(s={version:p[5]<<8|p[6],flags0:p[7]<<8|p[8],flags1:p[9]<<8|p[10],transformCode:p[11]});break;case 65499:const m=readUint16(e,i);i+=2;const b=m+i-2;let y;for(;i>4==0)for(f=0;f<64;f++){y=za[f];a[y]=e[i++]}else{if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(f=0;f<64;f++){y=za[f];a[y]=readUint16(e,i);i+=2}}c[15&t]=a}break;case 65472:case 65473:case 65474:if(a)throw new JpegError("Only single frame JPEGs supported");i+=2;a={};a.extended=65473===u;a.progressive=65474===u;a.precision=e[i++];const w=readUint16(e,i);i+=2;a.scanLines=t||w;a.samplesPerLine=readUint16(e,i);i+=2;a.components=[];a.componentIds={};const x=e[i++];let S=0,k=0;for(d=0;d>4,n=15&e[i+1];S>4==0?h:l)[15&t]=buildHuffmanTable(a,n)}break;case 65501:i+=2;r=readUint16(e,i);i+=2;break;case 65498:const v=1==++o&&!t;i+=2;const F=e[i++],O=[];for(d=0;d>4];n.huffmanTableAC=l[15&s];O.push(n)}const T=e[i++],M=e[i++],D=e[i++];try{const t=decodeScan(e,i,a,O,r,T,M,D>>4,15&D,v);i+=t}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break e}throw t}break;case 65500:i+=4;break;case 65535:255!==e[i]&&i--;break;default:const R=findNextFileMarker(e,i-2,i-3);if(R?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+R.invalid);i=R.offset;break}if(!R||i>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break e}throw new JpegError("JpegImage.parse - unknown marker: "+u.toString(16))}u=readUint16(e,i);i+=2}if(!a)throw new JpegError("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine;this.height=a.scanLines;this.jfif=n;this.adobe=s;this.components=[];for(const e of a.components){const t=c[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/a.maxH,scaleY:e.v/a.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,a=!1){const r=this.width/e,i=this.height/t;let n,s,o,c,l,h,u,d,f,g,p,m=0;const b=this.components.length,y=e*t*b,w=new Uint8ClampedArray(y),x=new Uint32Array(e),S=4294967288;let k;for(u=0;u>8)+C[f+1];return w}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,a,r;for(let i=0,n=e.length;i4)throw new JpegError("Unsupported color mode");const n=this._getLinearizedBlockData(e,t,i);if(1===this.numComponents&&(a||r)){const e=n.length*(a?4:3),t=new Uint8ClampedArray(e);let r=0;if(a)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let a=0,r=e.length;a>24&255,n>>16&255,n>>8&255,255&n)}).`)}o&&(a+=s)}}parseImageProperties(e){let t=e.getByte();for(;t>=0;){const a=t;t=e.getByte();if(65361===(a<<8|t)){e.skip(4);const t=e.getInt32()>>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0;e.skip(16);const n=e.getUint16();this.width=t-r;this.height=a-i;this.componentsCount=n;this.bitsPerComponent=8;return}}throw new JpxError("No size marker found in JPX stream")}parseCodestream(e,t,a){const r={};let i=!1;try{let n=t;for(;n+1>5;o=[];for(;a>3;t.mu=0}else{t.epsilon=e[a]>>3;t.mu=(7&e[a])<<8|e[a+1];a+=2}o.push(t)}p.SPqcds=o;if(r.mainHeader)r.QCD=p;else{r.currentTile.QCD=p;r.currentTile.QCC=[]}break;case 65373:u=readUint16(e,n);const m={};a=n+2;let b;if(r.SIZ.Csiz<257)b=e[a++];else{b=readUint16(e,a);a+=2}s=e[a++];switch(31&s){case 0:c=8;l=!0;break;case 1:c=16;l=!1;break;case 2:c=16;l=!0;break;default:throw new Error("Invalid SQcd value "+s)}m.noQuantization=8===c;m.scalarExpounded=l;m.guardBits=s>>5;o=[];for(;a>3;t.mu=0}else{t.epsilon=e[a]>>3;t.mu=(7&e[a])<<8|e[a+1];a+=2}o.push(t)}m.SPqcds=o;r.mainHeader?r.QCC[b]=m:r.currentTile.QCC[b]=m;break;case 65362:u=readUint16(e,n);const y={};a=n+2;const w=e[a++];y.entropyCoderWithCustomPrecincts=!!(1&w);y.sopMarkerUsed=!!(2&w);y.ephMarkerUsed=!!(4&w);y.progressionOrder=e[a++];y.layersCount=readUint16(e,a);a+=2;y.multipleComponentTransform=e[a++];y.decompositionLevelsCount=e[a++];y.xcb=2+(15&e[a++]);y.ycb=2+(15&e[a++]);const x=e[a++];y.selectiveArithmeticCodingBypass=!!(1&x);y.resetContextProbabilities=!!(2&x);y.terminationOnEachCodingPass=!!(4&x);y.verticallyStripe=!!(8&x);y.predictableTermination=!!(16&x);y.segmentationSymbolUsed=!!(32&x);y.reversibleTransformation=e[a++];if(y.entropyCoderWithCustomPrecincts){const t=[];for(;a>4})}y.precinctsSizes=t}const S=[];y.selectiveArithmeticCodingBypass&&S.push("selectiveArithmeticCodingBypass");y.terminationOnEachCodingPass&&S.push("terminationOnEachCodingPass");y.verticallyStripe&&S.push("verticallyStripe");y.predictableTermination&&S.push("predictableTermination");if(S.length>0){i=!0;warn(`JPX: Unsupported COD options (${S.join(", ")}).`)}if(r.mainHeader)r.COD=y;else{r.currentTile.COD=y;r.currentTile.COC=[]}break;case 65424:u=readUint16(e,n);h={};h.index=readUint16(e,n+2);h.length=readUint32(e,n+4);h.dataEnd=h.length+n-2;h.partIndex=e[n+8];h.partsCount=e[n+9];r.mainHeader=!1;if(0===h.partIndex){h.COD=r.COD;h.COC=r.COC.slice(0);h.QCD=r.QCD;h.QCC=r.QCC.slice(0)}r.currentTile=h;break;case 65427:h=r.currentTile;if(0===h.partIndex){initializeTile(r,h.index);buildPackets(r)}u=h.dataEnd-n;parseTilePackets(r,e,n,u);break;case 65363:warn("JPX: Codestream code 0xFF53 (COC) is not implemented.");case 65365:case 65367:case 65368:case 65380:u=readUint16(e,n);break;default:throw new Error("Unknown codestream code: "+t.toString(16))}n+=u}}catch(e){if(i||this.failOnCorruptedImage)throw new JpxError(e.message);warn(`JPX: Trying to recover from: "${e.message}".`)}this.tiles=function transformComponents(e){const t=e.SIZ,a=e.components,r=t.Csiz,i=[];for(let t=0,n=e.tiles.length;t>2);c[b++]=e+m>>h;c[b++]=e>>h;c[b++]=e+p>>h}else for(d=0;d>h;c[b++]=g-.34413*p-.71414*m>>h;c[b++]=g+1.772*p>>h}if(e)for(d=0,b=3;d>h}else for(let e=0;e>h;b+=r}}i.push(l)}return i}(r);this.width=r.SIZ.Xsiz-r.SIZ.XOsiz;this.height=r.SIZ.Ysiz-r.SIZ.YOsiz;this.componentsCount=r.SIZ.Csiz}}function calculateComponentDimensions(e,t){e.x0=Math.ceil(t.XOsiz/e.XRsiz);e.x1=Math.ceil(t.Xsiz/e.XRsiz);e.y0=Math.ceil(t.YOsiz/e.YRsiz);e.y1=Math.ceil(t.Ysiz/e.YRsiz);e.width=e.x1-e.x0;e.height=e.y1-e.y0}function calculateTileGrids(e,t){const a=e.SIZ,r=[];let i;const n=Math.ceil((a.Xsiz-a.XTOsiz)/a.XTsiz),s=Math.ceil((a.Ysiz-a.YTOsiz)/a.YTsiz);for(let e=0;e0?Math.min(r.xcb,i.PPx-1):Math.min(r.xcb,i.PPx);i.ycb_=a>0?Math.min(r.ycb,i.PPy-1):Math.min(r.ycb,i.PPy);return i}function buildPrecincts(e,t,a){const r=1<t.trx0?Math.ceil(t.trx1/r)-Math.floor(t.trx0/r):0,l=t.try1>t.try0?Math.ceil(t.try1/i)-Math.floor(t.try0/i):0,h=c*l;t.precinctParameters={precinctWidth:r,precinctHeight:i,numprecinctswide:c,numprecinctshigh:l,numprecincts:h,precinctWidthInSubband:s,precinctHeightInSubband:o}}function buildCodeblocks(e,t,a){const r=a.xcb_,i=a.ycb_,n=1<>r,c=t.tby0>>i,l=t.tbx1+n-1>>r,h=t.tby1+s-1>>i,u=t.resolution.precinctParameters,d=[],f=[];let g,p,m,b;for(p=c;pe.cbxMax&&(e.cbxMax=g);pe.cbyMax&&(e.cbyMax=p)}else f[b]=e={cbxMin:g,cbyMin:p,cbxMax:g,cbyMax:p};m.precinct=e}t.codeblockParameters={codeblockWidth:r,codeblockHeight:i,numcodeblockwide:l-o+1,numcodeblockhigh:h-c+1};t.codeblocks=d;t.precincts=f}function createPacket(e,t,a){const r=[],i=e.subbands;for(let e=0,a=i.length;ee.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[c],a=t.precinctParameters.numprecincts;for(;he.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[o],a=t.precinctParameters.numprecincts;for(;he.codingStyleParameters.decompositionLevelsCount)continue;const t=e.resolutions[o],a=t.precinctParameters.numprecincts;if(!(l>=a)){for(;s=0;--e){const a=t.resolutions[e],r=g*a.precinctParameters.precinctWidth,i=g*a.precinctParameters.precinctHeight;h=Math.min(h,r);u=Math.min(u,i);d=Math.max(d,a.precinctParameters.numprecinctswide);f=Math.max(f,a.precinctParameters.numprecinctshigh);l[e]={width:r,height:i};g<<=1}a=Math.min(a,h);r=Math.min(r,u);i=Math.max(i,d);n=Math.max(n,f);s[o]={resolutions:l,minWidth:h,minHeight:u,maxNumWide:d,maxNumHigh:f}}return{components:s,minWidth:a,minHeight:r,maxNumWide:i,maxNumHigh:n}}function buildPackets(e){const t=e.SIZ,a=e.currentTile.index,r=e.tiles[a],i=t.Csiz;for(let e=0;e>>s&(1<0;){const e=i.shift();s=e.codeblock;void 0===s.data&&(s.data=[]);s.data.push({data:t,start:a+n,end:a+n+e.dataLength,codingpasses:e.codingpasses});n+=e.dataLength}}return n}function copyCoefficients(e,t,a,r,i,n,s,o,c){const l=r.tbx0,h=r.tby0,u=r.tbx1-r.tbx0,d=r.codeblocks,f="H"===r.type.charAt(0)?1:0,g="H"===r.type.charAt(1)?t:0;for(let a=0,p=d.length;a=n?_:_*(1<0?1-e:0)}const g=t.subbands[r],p=Qa[g.type];copyCoefficients(n,a,0,g,f?1:2**(d+p-s)*(1+i/2048),l+s-1,f,h,u)}p.push({width:a,height:i,items:n})}const b=g.calculate(p,r.tcx0,r.tcy0);return{left:r.tcx0,top:r.tcy0,width:b.width,height:b.height,items:b.items}}function initializeTile(e,t){const a=e.SIZ.Csiz,r=e.tiles[t];for(let t=0;t>=1;t>>=1;r++}r--;a=this.levels[r];a.items[a.index]=i;this.currentLevel=r;delete this.value}incrementValue(){const e=this.levels[this.currentLevel];e.items[e.index]++}nextLevel(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];e--;if(e<0){this.value=a;return!1}this.currentLevel=e;t=this.levels[e];t.items[t.index]=a;return!0}}class InclusionTree{constructor(e,t,a){const r=log2(Math.max(e,t))+1;this.levels=[];for(let i=0;ia){this.currentLevel=r;this.propagateValues();return!1}e>>=1;t>>=1;r++}this.currentLevel=r-1;return!0}incrementValue(e){const t=this.levels[this.currentLevel];t.items[t.index]=e+1;this.propagateValues()}propagateValues(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];for(;--e>=0;){t=this.levels[e];t.items[t.index]=a}}nextLevel(){let e=this.currentLevel,t=this.levels[e];const a=t.items[t.index];t.items[t.index]=255;e--;if(e<0)return!1;this.currentLevel=e;t=this.levels[e];t.items[t.index]=a;return!0}}class BitModel{static UNIFORM_CONTEXT=17;static RUNLENGTH_CONTEXT=18;static LLAndLHContextsLabel=new Uint8Array([0,5,8,0,3,7,8,0,4,7,8,0,0,0,0,0,1,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8,0,0,0,0,0,2,6,8,0,3,7,8,0,4,7,8]);static HLContextLabel=new Uint8Array([0,3,4,0,5,7,7,0,8,8,8,0,0,0,0,0,1,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8,0,0,0,0,0,2,3,4,0,6,7,7,0,8,8,8]);static HHContextLabel=new Uint8Array([0,1,2,0,1,2,2,0,2,2,2,0,0,0,0,0,3,4,5,0,4,5,5,0,5,5,5,0,0,0,0,0,6,7,7,0,7,7,7,0,7,7,7,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8,0,0,0,0,0,8,8,8,0,8,8,8,0,8,8,8]);constructor(e,t,a,r,i){this.width=e;this.height=t;let n;n="HH"===a?BitModel.HHContextLabel:"HL"===a?BitModel.HLContextLabel:BitModel.LLAndLHContextsLabel;this.contextLabelTable=n;const s=e*t;this.neighborsSignificance=new Uint8Array(s);this.coefficentsSign=new Uint8Array(s);let o;o=i>14?new Uint32Array(s):i>6?new Uint16Array(s):new Uint8Array(s);this.coefficentsMagnitude=o;this.processingFlags=new Uint8Array(s);const c=new Uint8Array(s);if(0!==r)for(let e=0;e0,o=t+10){c=a-i;s&&(r[c-1]+=16);o&&(r[c+1]+=16);r[c]+=4}if(e+1=a)break;s[d]&=-2;if(r[d]||!n[d])continue;const g=c[n[d]];if(e.readBit(o,g)){const e=this.decodeSignBit(t,u,d);i[d]=e;r[d]=1;this.setNeighborsSignificance(t,u,d);s[d]|=2}l[d]++;s[d]|=1}}}decodeSignBit(e,t,a){const r=this.width,i=this.height,n=this.coefficentsMagnitude,s=this.coefficentsSign;let o,c,l,h,u,d;h=t>0&&0!==n[a-1];if(t+10&&0!==n[a-r];if(e+1=0){u=9+o;d=this.decoder.readBit(this.contexts,u)}else{u=9-o;d=1^this.decoder.readBit(this.contexts,u)}return d}runMagnitudeRefinementPass(){const e=this.decoder,t=this.width,a=this.height,r=this.coefficentsMagnitude,i=this.neighborsSignificance,n=this.contexts,s=this.bitsDecoded,o=this.processingFlags,c=t*a,l=4*t;for(let a,h=0;h>1;let i,n,s,o;const c=-1.586134342059924,l=-.052980118572961,h=.882911075530934,u=.443506852043971,d=1.230174104914001;i=(t|=0)-3;for(n=r+4;n--;i+=2)e[i]*=.8128930661159609;i=t-2;s=u*e[i-1];for(n=r+3;n--;i+=2){o=u*e[i+1];e[i]=d*e[i]-s-o;if(!n--)break;i+=2;s=u*e[i+1];e[i]=d*e[i]-s-o}i=t-1;s=h*e[i-1];for(n=r+2;n--;i+=2){o=h*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=h*e[i+1];e[i]-=s+o}i=t;s=l*e[i-1];for(n=r+1;n--;i+=2){o=l*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=l*e[i+1];e[i]-=s+o}if(0!==r){i=t+1;s=c*e[i-1];for(n=r;n--;i+=2){o=c*e[i+1];e[i]-=s+o;if(!n--)break;i+=2;s=c*e[i+1];e[i]-=s+o}}}}class ReversibleTransform extends Transform{filter(e,t,a){const r=a>>1;let i,n;for(i=t|=0,n=r+1;n--;i+=2)e[i]-=e[i-1]+e[i+1]+2>>2;for(i=t+1,n=r;n--;i+=2)e[i]+=e[i-1]+e[i+1]>>1}}class JpxStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=a}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(){if(this.eof)return;const e=new JpxImage;e.parse(this.bytes);const t=e.width,a=e.height,r=e.componentsCount,i=e.tiles.length;if(1===i)this.buffer=e.tiles[0].items;else{const n=new Uint8ClampedArray(t*a*r);for(let a=0;a>>t&(1<0;if(e<256){d[0]=e;f=1}else{if(!(e>=258)){if(256===e){h=9;s=258;f=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){d[t]=o[a];a=l[a]}}else d[f++]=d[0]}if(i){l[s]=u;c[s]=c[u]+1;o[s]=d[0];s++;h=s+n&s+n-1?h:0|Math.min(Math.log(s+n)/.6931471805599453+1,12)}u=e;g+=f;if(r15))throw new FormatError(`Unsupported predictor: ${r}`);this.readBlock=2===r?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const i=this.colors=a.get("Colors")||1,n=this.bits=a.get("BPC","BitsPerComponent")||8,s=this.columns=a.get("Columns")||1;this.pixBytes=i*n+7>>3;this.rowBytes=s*i*n+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,a=this.ensureBuffer(t+e),r=this.bits,i=this.colors,n=this.str.getBytes(e);this.eof=!n.length;if(this.eof)return;let s,o=0,c=0,l=0,h=0,u=t;if(1===r&&1===i)for(s=0;s>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;a[u++]=e}else if(8===r){for(s=0;s>8&255;a[u++]=255&e}}else{const e=new Uint8Array(i+1),u=(1<>l-r)&u;l-=r;c=c<=8){a[f++]=c>>h-8&255;h-=8}}h>0&&(a[f++]=(c<<8-h)+(o&(1<<8-h)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,a=this.str.getByte(),r=this.str.getBytes(e);this.eof=!r.length;if(this.eof)return;const i=this.bufferLength,n=this.ensureBuffer(i+e);let s=n.subarray(i-e,i);0===s.length&&(s=new Uint8Array(e));let o,c,l,h=i;switch(a){case 0:for(o=0;o>1)+r[o];for(;o>1)+r[o]&255;h++}break;case 4:for(o=0;o0){const e=this.str.getBytes(r);t.set(e,a);a+=r}}else{r=257-r;const i=e[1];t=this.ensureBuffer(a+r+1);for(let e=0;e>")&&this.buf1!==da;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===da)break;r.set(t,this.getObj(e))}if(this.buf1===da){if(this.recoveryMode)return r;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(r,e):r;this.shift();return r;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,a=e.pos;let r,i,n=0;for(;-1!==(r=e.getByte());)if(0===n)n=69===r?1:0;else if(1===n)n=73===r?2:0;else if(32===r||10===r||13===r){i=e.pos;const a=e.peekBytes(15),s=a.length;if(0===s)break;for(let e=0;e127))){n=0;break}}if(2!==n)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(a.slice()),t);o._hexStringWarn=()=>{};let c=0;for(;;){const e=o.getObj();if(e===da){n=0;break}if(e instanceof Cmd){const a=t[e.cmd];if(!a){n=0;break}if(a.variableArgs?c<=a.numArgs:c===a.numArgs)break;c=0}else c++}if(2===n)break}else n=0;if(-1===r){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(i){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-i))}}let s=4;e.skip(-s);r=e.peekByte();e.skip(s);isWhiteSpace(r)||s--;return e.pos-s-a}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let a,r,i=!1;for(;-1!==(a=e.getByte());)if(255===a){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:i=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:r=e.getUint16();r>2?e.skip(r-2):e.skip(-2)}if(i)break}const n=e.pos-t;if(-1===a){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-n);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return n}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte());)if(126===a){const t=e.pos;a=e.peekByte();for(;isWhiteSpace(a);){e.skip();a=e.peekByte()}if(62===a){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const r=e.pos-t;if(-1===a){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte())&&62!==a;);const r=e.pos-t;if(-1===a){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}inlineStreamSkipEI(e){let t,a=0;for(;-1!==(t=e.getByte());)if(0===a)a=69===t?1:0;else if(1===a)a=73===t?2:0;else if(2===a)break}makeInlineImage(e){const t=this.lexer,a=t.stream,r=Object.create(null);let i;for(;!isCmd(this.buf1,"ID")&&this.buf1!==da;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===da)break;r[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(i=a.pos-t.beginInlineImagePos);const n=this.xref.fetchIfRef(r.F||r.Filter);let s;if(n instanceof Name)s=n.name;else if(Array.isArray(n)){const e=this.xref.fetchIfRef(n[0]);e instanceof Name&&(s=e.name)}const o=a.pos;let c,l;switch(s){case"DCT":case"DCTDecode":c=this.findDCTDecodeInlineStreamEnd(a);break;case"A85":case"ASCII85Decode":c=this.findASCII85DecodeInlineStreamEnd(a);break;case"AHx":case"ASCIIHexDecode":c=this.findASCIIHexDecodeInlineStreamEnd(a);break;default:c=this.findDefaultInlineStreamEnd(a)}if(c<1e3&&i>0){const e=a.pos;a.pos=t.beginInlineImagePos;l=function getInlineImageCacheKey(e){const t=[],a=e.length;let r=0;for(;r=r){a.pos+=s;return a.pos-e}s++}a.pos+=n}return-1}makeStream(e,t){const a=this.lexer;let r=a.stream;a.skipToNextLine();const i=r.pos-1;let n=e.get("Length");if(!Number.isInteger(n)){info(`Bad length "${n&&n.toString()}" in stream.`);n=0}r.pos=i+n;a.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{const e=new Uint8Array([101,110,100,115,116,114,101,97,109]);let t=this._findStreamLength(i,e);if(t<0){const a=1;for(let n=1;n<=a;n++){const a=e.length-n,s=e.slice(0,a),o=this._findStreamLength(i,s);if(o>=0){if(!isWhiteSpace(r.peekBytes(a+1)[a]))break;info(`Found "${bytesToString(s)}" when searching for endstream command.`);t=o;break}}if(t<0)throw new FormatError("Missing endstream command.")}n=t;a.nextChar();this.shift();this.shift()}this.shift();r=r.makeSubStream(i,n,e);t&&(r=t.createStream(r,n));r=this.filter(r,e,n);r.dict=e;return r}filter(e,t,a){let r=t.get("F","Filter"),i=t.get("DP","DecodeParms");if(r instanceof Name){Array.isArray(i)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,r.name,a,i)}let n=a;if(Array.isArray(r)){const t=r,a=i;for(let s=0,o=t.length;s=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,a=0,r=1;if(45===e){r=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){a=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let i=e-48,n=0,s=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const r=e-48;if(t)n=10*n+r;else{0!==a&&(a*=10);i=10*i+r}}else if(46===e){if(0!==a)break;a=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){s=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==a&&(i/=a);t&&(i*=10**(s*n));return r*i}getString(){let e=1,t=!1;const a=this.strBuf;a.length=0;let r=this.nextChar();for(;;){let i=!1;switch(0|r){case-1:warn("Unterminated string");t=!0;break;case 40:++e;a.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else a.push(")");break;case 92:r=this.nextChar();switch(r){case-1:warn("Unterminated string");t=!0;break;case 110:a.push("\n");break;case 114:a.push("\r");break;case 116:a.push("\t");break;case 98:a.push("\b");break;case 102:a.push("\f");break;case 92:case 40:case 41:a.push(String.fromCharCode(r));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&r;r=this.nextChar();i=!0;if(r>=48&&r<=55){e=(e<<3)+(15&r);r=this.nextChar();if(r>=48&&r<=55){i=!1;e=(e<<3)+(15&r)}}a.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:a.push(String.fromCharCode(r))}break;default:a.push(String.fromCharCode(r))}if(t)break;i||(r=this.nextChar())}return a.join("")}getName(){let e,t;const a=this.strBuf;a.length=0;for(;(e=this.nextChar())>=0&&!er[e];)if(35===e){e=this.nextChar();if(er[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");a.push("#");break}const r=toHexDigit(e);if(-1!==r){t=e;e=this.nextChar();const i=toHexDigit(e);if(-1===i){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);a.push("#",String.fromCharCode(t));if(er[e])break;a.push(String.fromCharCode(e));continue}a.push(String.fromCharCode(r<<4|i))}else a.push("#",String.fromCharCode(e))}else a.push(String.fromCharCode(e));a.length>127&&warn(`Name token is longer than allowed by the spec: ${a.length}`);return Name.get(a.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t,a,r=this.currentChar,i=!0;this._hexStringNumWarn=0;for(;;){if(r<0){warn("Unterminated hex string");break}if(62===r){this.nextChar();break}if(1!==er[r]){if(i){t=toHexDigit(r);if(-1===t){this._hexStringWarn(r);r=this.nextChar();continue}}else{a=toHexDigit(r);if(-1===a){this._hexStringWarn(r);r=this.nextChar();continue}e.push(String.fromCharCode(t<<4|a))}i=!i;r=this.nextChar()}else r=this.nextChar()}return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return da;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==er[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let a=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(a)}}const r=this.knownCommands;let i=void 0!==r?.[a];for(;(t=this.nextChar())>=0&&!er[t];){const e=a+String.fromCharCode(t);if(i&&void 0===r[e])break;if(128===a.length)throw new FormatError(`Command token too long: ${a.length}`);a=e;i=void 0!==r?.[a]}if("true"===a)return!0;if("false"===a)return!1;if("null"===a)return null;"BI"===a&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(a)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,a=!1){const r=e.get(t);if(Number.isInteger(r)&&(a?r>=0:r>0))return r;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),a=t.getObj(),r=t.getObj(),i=t.getObj(),n=t.getObj();let s,o;if(!(Number.isInteger(a)&&Number.isInteger(r)&&isCmd(i,"obj")&&n instanceof Dict&&"number"==typeof(s=n.get("Linearized"))&&s>0))return null;if((o=getInt(n,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let a;if(Array.isArray(t)&&(2===(a=t.length)||4===a)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:getInt(n,"O"),endFirst:getInt(n,"E"),numPages:getInt(n,"N"),mainXRefEntriesOffset:getInt(n,"T"),pageFirst:n.has("P")?getInt(n,"P",!0):0}}}const tr=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],ar=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,a){this.codespaceRanges[e-1].push(t,a);this.numCodespaceRanges++}mapCidRange(e,t,a){if(t-e>ar)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=a++}mapBfRange(e,t,a){if(t-e>ar)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const r=a.length-1;for(;e<=t;){this._map[e++]=a;const t=a.charCodeAt(r)+1;t>255?a=a.substring(0,r-1)+String.fromCharCode(a.charCodeAt(r-1)+1)+"\0":a=a.substring(0,r)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,a){if(t-e>ar)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const r=a.length;let i=0;for(;e<=t&&i>>0;const s=i[n];for(let e=0,t=s.length;e=t&&r<=i){a.charcode=r;a.length=n+1;return}}}a.charcode=0;a.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let a=0,r=t.length;a=i&&e<=n)return a+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,a){unreachable("should not call mapCidRange")}mapBfRange(e,t,a){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,a){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let a=0;a>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endbfchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=a;e.mapOne(r,i)}}function parseBfRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endbfrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();if(Number.isInteger(a)||"string"==typeof a){const t=Number.isInteger(a)?String.fromCharCode(a):a;e.mapBfRange(r,i,t)}else{if(!isCmd(a,"["))break;{a=t.getObj();const n=[];for(;!isCmd(a,"]")&&a!==da;){n.push(a);a=t.getObj()}e.mapBfRangeToArray(r,i,n)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcidchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectInt(a);const i=a;e.mapOne(r,i)}}function parseCidRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcidrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();expectInt(a);const n=a;e.mapCidRange(r,i,n)}}function parseCodespaceRange(e,t){for(;;){let a=t.getObj();if(a===da)break;if(isCmd(a,"endcodespacerange"))return;if("string"!=typeof a)break;const r=strToInt(a);a=t.getObj();if("string"!=typeof a)break;const i=strToInt(a);e.addCodespaceRange(a.length,r,i)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const a=t.getObj();Number.isInteger(a)&&(e.vertical=!!a)}function parseCMapName(e,t){const a=t.getObj();a instanceof Name&&(e.name=a.name)}async function parseCMap(e,t,a,r){let i,n;e:for(;;)try{const a=t.getObj();if(a===da)break;if(a instanceof Name){"WMode"===a.name?parseWMode(e,t):"CMapName"===a.name&&parseCMapName(e,t);i=a}else if(a instanceof Cmd)switch(a.cmd){case"endcmap":break e;case"usecmap":i instanceof Name&&(n=i.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!r&&n&&(r=n);return r?extendCMap(e,a,r):e}async function extendCMap(e,t,a){e.useCMap=await createBuiltInCMap(a,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let a=0;aextendCMap(i,t,e)));if(r===ke.NONE){const e=new Lexer(new Stream(a));return parseCMap(i,e,t,null)}throw new Error(`Invalid CMap "compressionType" value: ${r}`)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:a}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const r=await parseCMap(new CMap,new Lexer(e),t,a);return r.isIdentityCMap?createBuiltInCMap(r.name,t):r}throw new Error("Encoding required.")}}const rr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],ir=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],nr=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],sr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],or=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],cr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],lr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],hr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],ur=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],dr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return hr;case"StandardEncoding":return lr;case"MacRomanEncoding":return cr;case"SymbolSetEncoding":return ur;case"ZapfDingbatsEncoding":return dr;case"ExpertEncoding":return sr;case"MacExpertEncoding":return or;default:return null}}const fr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],gr=391,pr=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],mr=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,a){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!a}parse(){const e=this.properties,t=new CFF;this.cff=t;const a=this.parseHeader(),r=this.parseIndex(a.endPos),i=this.parseIndex(r.endPos),n=this.parseIndex(i.endPos),s=this.parseIndex(n.endPos),o=this.parseDict(i.obj.get(0)),c=this.createDict(CFFTopDict,o,t.strings);t.header=a.obj;t.names=this.parseNameIndex(r.obj);t.strings=this.parseStringIndex(n.obj);t.topDict=c;t.globalSubrIndex=s.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=c.hasName("ROS");const l=c.getByName("CharStrings"),h=this.parseIndex(l).obj,u=c.getByName("FontMatrix");u&&(e.fontMatrix=u);const d=c.getByName("FontBBox");if(d){e.ascent=Math.max(d[3],d[1]);e.descent=Math.min(d[1],d[3]);e.ascentScaled=!0}let f,g;if(t.isCIDFont){const e=this.parseIndex(c.getByName("FDArray")).obj;for(let a=0,r=e.count;a=t)throw new FormatError("Invalid CFF header");if(0!==a){info("cff data is shifted");e=e.subarray(a);this.bytes=e}const r=e[0],i=e[1],n=e[2],s=e[3];return{obj:new CFFHeader(r,i,n,s),endPos:n}}parseDict(e){let t=0;function parseOperand(){let a=e[t++];if(30===a)return function parseFloatOperand(){let a="";const r=15,i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],n=e.length;for(;t>4,o=15&n;if(s===r)break;a+=i[s];if(o===r)break;a+=i[o]}return parseFloat(a)}();if(28===a){a=e[t++];a=(a<<24|e[t++]<<16)>>16;return a}if(29===a){a=e[t++];a=a<<8|e[t++];a=a<<8|e[t++];a=a<<8|e[t++];return a}if(a>=32&&a<=246)return a-139;if(a>=247&&a<=250)return 256*(a-247)+e[t++]+108;if(a>=251&&a<=254)return-256*(a-251)-e[t++]-108;warn('CFFParser_parseDict: "'+a+'" is a reserved command.');return NaN}let a=[];const r=[];t=0;const i=e.length;for(;t10)return!1;let i=e.stackSize;const n=e.stack;let s=t.length;for(let o=0;o>16;o+=2;i++}else if(14===c){if(i>=4){i-=4;if(this.seacAnalysisEnabled){e.seac=n.slice(i,i+4);return!1}}l=pr[c]}else if(c>=32&&c<=246){n[i]=c-139;i++}else if(c>=247&&c<=254){n[i]=c<251?(c-247<<8)+t[o]+108:-(c-251<<8)-t[o]-108;o++;i++}else if(255===c){n[i]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;i++}else if(19===c||20===c){e.hints+=i>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}o+=e.hints+7>>3;i%=2;l=pr[c]}else{if(10===c||29===c){const t=10===c?a:r;if(!t){l=pr[c];warn("Missing subrsIndex for "+l.id);return!1}let s=32768;t.count<1240?s=107:t.count<33900&&(s=1131);const o=n[--i]+s;if(o<0||o>=t.count||isNaN(o)){l=pr[c];warn("Out of bounds subrIndex for "+l.id);return!1}e.stackSize=i;e.callDepth++;if(!this.parseCharString(e,t.get(o),a,r))return!1;e.callDepth--;i=e.stackSize;continue}if(11===c){e.stackSize=i;return!0}if(0===c&&o===t.length){t[o-1]=14;l=pr[14]}else{if(9===c){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}l=pr[c]}}if(l){if(l.stem){e.hints+=i>>1;if(3===c||23===c)e.hasVStems=!0;else if(e.hasVStems&&(1===c||18===c)){warn("CFF stem hints are in wrong order");t[o-1]=1===c?3:23}}if("min"in l&&!e.undefStack&&i=2&&l.stem?i%=2:i>1&&warn("Found too many parameters for stack-clearing command");i>0&&(e.width=n[i-1])}if("stackDelta"in l){"stackFn"in l&&l.stackFn(n,i);i+=l.stackDelta}else if(l.stackClearing)i=0;else if(l.resetStack){i=0;e.undefStack=!1}else if(l.undefStack){i=0;e.undefStack=!0;e.firstStackClearing=!1}}}s=i.length){warn("Invalid fd index for glyph index.");u=!1}if(u){f=i[e].privateDict;d=f.subrsIndex}}else t&&(d=t);u&&(u=this.parseCharString(h,c,d,a));if(null!==h.width){const e=f.getByName("nominalWidthX");o[l]=e+h.width}else{const e=f.getByName("defaultWidthX");o[l]=e}null!==h.seac&&(s[l]=h.seac);u||e.set(l,new Uint8Array([14]))}return{charStrings:e,seacs:s,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const a=t[0],r=t[1];if(0===a||r>=this.bytes.length){this.emptyPrivateDictionary(e);return}const i=r+a,n=this.bytes.subarray(r,i),s=this.parseDict(n),o=this.createDict(CFFPrivateDict,s,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const c=o.getByName("Subrs"),l=r+c;if(0===c||l>=this.bytes.length){this.emptyPrivateDictionary(e);return}const h=this.parseIndex(l);o.subrsIndex=h.obj}parseCharsets(e,t,a,r){if(0===e)return new CFFCharset(!0,wr.ISO_ADOBE,rr);if(1===e)return new CFFCharset(!0,wr.EXPERT,ir);if(2===e)return new CFFCharset(!0,wr.EXPERT_SUBSET,nr);const i=this.bytes,n=e,s=i[e++],o=[r?0:".notdef"];let c,l,h;t-=1;switch(s){case 0:for(h=0;h=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,a,r){this.major=e;this.minor=t;this.hdrSize=a;this.offSize=r}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?fr[e]:e-gr<=this.strings.length?this.strings[e-gr]:fr[0]}getSID(e){let t=fr.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+gr:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const a of t)if(isNaN(a)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const a=this.types[e];"num"!==a&&"sid"!==a&&"offset"!==a||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const a of e){const e=Array.isArray(a[0])?(a[0][0]<<8)+a[0][1]:a[0];t.keyToNameMap[e]=a[1];t.nameToKeyMap[a[1]]=e;t.types[e]=a[2];t.defaults[e]=a[3];t.opcodes[e]=Array.isArray(a[0])?a[0]:[a[0]];t.order.push(e)}return t}}const br=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(br))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const yr=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(yr))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const wr={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,a,r){this.predefined=e;this.format=t;this.charset=a;this.raw=r}}class CFFEncoding{constructor(e,t,a,r){this.predefined=e;this.format=t;this.encoding=a;this.raw=r}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,a){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const r=a.data,i=this.offsets[e];for(let e=0,a=t.length;e>24&255;r[s]=l>>16&255;r[o]=l>>8&255;r[c]=255&l}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},a=this.compileHeader(e.header);t.add(a);const r=this.compileNameIndex(e.names);t.add(r);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const a of e.fdArray){let e=t.slice(0);a.hasName("FontMatrix")&&(e=Util.transform(e,a.getByName("FontMatrix")));a.setByName("FontMatrix",e)}}const i=e.topDict.getByName("XUID");i?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let n=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(n.output);const s=n.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const c=this.compileIndex(e.globalSubrIndex);t.add(c);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)s.setEntryLocation("Encoding",[e.encoding.format],t);else{const a=this.compileEncoding(e.encoding);s.setEntryLocation("Encoding",[t.length],t);t.add(a)}const l=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);s.setEntryLocation("charset",[t.length],t);t.add(l);const h=this.compileCharStrings(e.charStrings);s.setEntryLocation("CharStrings",[t.length],t);t.add(h);if(e.isCIDFont){s.setEntryLocation("FDSelect",[t.length],t);const a=this.compileFDSelect(e.fdSelect);t.add(a);n=this.compileTopDicts(e.fdArray,t.length,!0);s.setEntryLocation("FDArray",[t.length],t);t.add(n.output);const r=n.trackers;this.compilePrivateDicts(e.fdArray,r,t)}this.compilePrivateDicts([e.topDict],[s],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const a=CFFCompiler.EncodeFloatRegExp.exec(t);if(a){const r=parseFloat("1e"+((a[2]?+a[2]:0)+a[1].length));t=(Math.round(e*r)/r).toString()}let r,i,n="";for(r=0,i=t.length;r=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const a of e){const e=Math.min(a.length,127);let r=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");r[t]=e}r=r.join("");""===r&&(r="Bad_Font_Name");t.add(stringToBytes(r))}return this.compileIndex(t)}compileTopDicts(e,t,a){const r=[];let i=new CFFIndex;for(const n of e){if(a){n.removeByName("CIDFontVersion");n.removeByName("CIDFontRevision");n.removeByName("CIDFontType");n.removeByName("CIDCount");n.removeByName("UIDBase")}const e=new CFFOffsetTracker,s=this.compileDict(n,e);r.push(e);i.add(s);e.offset(t)}i=this.compileIndex(i,r);return{trackers:r,output:i}}compilePrivateDicts(e,t,a){for(let r=0,i=e.length;r>8&255,255&n]);else{i=new Uint8Array(1+2*n);i[0]=0;let t=0;const r=e.charset.length;let s=!1;for(let n=1;n>8&255;i[n+1]=255&o}}return this.compileTypedArray(i)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let a,r;switch(t){case 0:a=new Uint8Array(1+e.fdSelect.length);a[0]=t;for(r=0;r>8&255,255&i,n];for(r=1;r>8&255,255&r,t);n=t}}const o=(s.length-3)/3;s[1]=o>>8&255;s[2]=255&o;s.push(r>>8&255,255&r);a=new Uint8Array(s)}return this.compileTypedArray(a)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const a=e.objects,r=a.length;if(0===r)return[0,0];const i=[r>>8&255,255&r];let n,s,o=1;for(n=0;n>8&255,255&c):3===s?i.push(c>>16&255,c>>8&255,255&c):i.push(c>>>24&255,c>>16&255,c>>8&255,255&c);a[n]&&(c+=a[n].length)}for(n=0;n=5&&t<=7))return-1;r=e.substring(1)}if(r===r.toUpperCase()){a=parseInt(r,16);if(a>=0)return a}}return-1}const Ar=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const a=Ar[t];for(let r=0,i=a.length;r=a[r]&&e<=a[r+1])return t}for(let t=0,a=Ar.length;t=a[r]&&e<=a[r+1])return t}return-1}const Cr=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),vr=new Map;const Fr=!0,Ir=1,Or=2,Tr=4,Mr=32,Dr=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const a=getUnicodeForGlyph(e,t);if(-1!==a)for(const e in t)if(t[e]===a)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,a){const r=Object.create(null);let i,n,s;const o=!!(e.flags&Tr);if(e.isInternalFont){s=t;for(n=0;n=0?i:0}}else if(e.baseEncodingName){s=getEncoding(e.baseEncodingName);for(n=0;n=0?i:0}}else if(o)for(n in t)r[n]=t[n];else{s=lr;for(n=0;n=0?i:0}}const c=e.differences;let l;if(c)for(n in c){const e=c[n];i=a.indexOf(e);if(-1===i){l||(l=xr());const t=recoverGlyphName(e,l);t!==e&&(i=a.indexOf(t))}r[n]=i>=0?i:0}return r}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Rr=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),Nr=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),Er=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Pr=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),Lr=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),jr=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),_r=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Ur=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Rr()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Rr()[t]||Er()[t]||Pr()[t]||Lr()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].charCodeAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const a in t)if(t[a]===e)return 0|a;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,a=this.lastChar;t<=a;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const a=new CFFParser(e,t,Fr);this.cff=a.parse();this.cff.duplicateFirstGlyph();const r=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=r.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:a,cMap:r}=t,i=e.charset.charset;let n,s;if(t.composite){let t,o;if(a?.length>0){t=Object.create(null);for(let e=0,r=a.length;e=0){const r=a[t];r&&(i[e]=r)}}i.length>0&&(this.properties.builtInEncoding=i)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let a=32768;t<1240?a=107:t<33900&&(a=1131);return a}function parseCmap(e,t,a){const r=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),i=getUint16(e,t+r);let n,s,o;if(4===i){getUint16(e,t+r+2);const a=getUint16(e,t+r+6)>>1;s=t+r+14;n=[];for(o=0;o>1;a0;)h.push({flags:n})}for(a=0;a>1;y=!0;break;case 4:s+=i.pop();moveTo(n,s);y=!0;break;case 5:for(;i.length>0;){n+=i.shift();s+=i.shift();lineTo(n,s)}break;case 6:for(;i.length>0;){n+=i.shift();lineTo(n,s);if(0===i.length)break;s+=i.shift();lineTo(n,s)}break;case 7:for(;i.length>0;){s+=i.shift();lineTo(n,s);if(0===i.length)break;n+=i.shift();lineTo(n,s)}break;case 8:for(;i.length>0;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 10:m=i.pop();b=null;if(a.isCFFCIDFont){const e=a.fdSelect.getFDIndex(r);if(e>=0&&eMath.abs(s-t)?n+=i.shift():s+=i.shift();bezierCurveTo(l,u,h,d,n,s);break;default:throw new FormatError(`unknown operator: 12 ${w}`)}break;case 14:if(i.length>=4){const e=i.pop(),r=i.pop();s=i.pop();n=i.pop();t.push({cmd:"save"},{cmd:"translate",args:[n,s]});let o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[e]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId);t.push({cmd:"restore"});o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[r]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId)}return;case 19:case 20:o+=i.length>>1;c+=o+7>>3;y=!0;break;case 21:s+=i.pop();n+=i.pop();moveTo(n,s);y=!0;break;case 22:n+=i.pop();moveTo(n,s);y=!0;break;case 24:for(;i.length>2;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}n+=i.shift();s+=i.shift();lineTo(n,s);break;case 25:for(;i.length>6;){n+=i.shift();s+=i.shift();lineTo(n,s)}l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s);break;case 26:i.length%2&&(n+=i.shift());for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h;s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 27:i.length%2&&(s+=i.shift());for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d;bezierCurveTo(l,u,h,d,n,s)}break;case 28:i.push((e[c]<<24|e[c+1]<<16)>>16);c+=2;break;case 29:m=i.pop()+a.gsubrsBias;b=a.gsubrs[m];b&&parse(b);break;case 30:for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;case 31:for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;default:if(w<32)throw new FormatError(`unknown operator: ${w}`);if(w<247)i.push(w-139);else if(w<251)i.push(256*(w-247)+e[c++]+108);else if(w<255)i.push(256*-(w-251)-e[c++]-108);else{i.push((e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3])/65536);c+=4}}y&&(i.length=0)}}(e)}const Xr=[];class CompiledFont{constructor(e){this.constructor===CompiledFont&&unreachable("Cannot initialize CompiledFont.");this.fontMatrix=e;this.compiledGlyphs=Object.create(null);this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(e){const{charCode:t,glyphId:a}=lookupCmap(this.cmap,e);let r=this.compiledGlyphs[a];if(!r)try{r=this.compileGlyph(this.glyphs[a],a);this.compiledGlyphs[a]=r}catch(e){this.compiledGlyphs[a]=Xr;void 0===this.compiledCharCodeToGlyphId[t]&&(this.compiledCharCodeToGlyphId[t]=a);throw e}void 0===this.compiledCharCodeToGlyphId[t]&&(this.compiledCharCodeToGlyphId[t]=a);return r}compileGlyph(e,t){if(!e||0===e.length||14===e[0])return Xr;let a=this.fontMatrix;if(this.isCFFCIDFont){const e=this.fdSelect.getFDIndex(t);if(e>=0&&e2*getUint16(e,t)}const n=[];let s=i(t,0);for(let a=r;ae+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),a=e>131070,r=a?4:2,i=new DataView(new ArrayBuffer((this.glyphs.length+1)*r));a?i.setUint32(0,0):i.setUint16(0,0);let n=0,s=0;for(const e of this.glyphs){n+=e.write(n,t);n=n+3&-4;s+=r;a?i.setUint32(s,n):i.setUint16(s,n>>1)}return{isLocationLong:a,loca:new Uint8Array(i.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,a=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const a=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const a of this.composites)e+=a.write(e,t);return e-a}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const a of this.composites)a.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:a,xMax:r,yMax:i}){this.numberOfContours=e;this.xMin=t;this.yMin=a;this.xMax=r;this.yMax=i}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:a}){this.xCoordinates=t;this.yCoordinates=a;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,a){const r=[];for(let i=0;i255?e+=2:o>0&&(e+=1);t=n;o=Math.abs(s-a);o>255?e+=2:o>0&&(e+=1);a=s}}return e}write(e,t){const a=e,r=[],i=[],n=[];let s=0,o=0;for(const a of this.contours){for(let e=0,t=a.xCoordinates.length;e=0?18:2;r.push(e)}else r.push(l)}s=c;const h=a.yCoordinates[e];l=h-o;if(0===l){t|=32;i.push(0)}else{const e=Math.abs(l);if(e<=255){t|=l>=0?36:4;i.push(e)}else i.push(l)}o=h;n.push(t)}t.setUint16(e,r.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const a of n)t.setUint8(e++,a);for(let a=0,i=r.length;a=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const a=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-a}scale(e,t){}}function writeInt16(e,t,a){e[t]=a>>8&255;e[t+1]=255&a}function writeInt32(e,t,a){e[t]=a>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}function writeData(e,t,a){if(a instanceof Uint8Array)e.set(a,t);else if("string"==typeof a)for(let r=0,i=a.length;ra;){a<<=1;r++}const i=a*t;return{range:i,entry:r,rangeShift:t*e-i}}toArray(){let e=this.sfnt;const t=this.tables,a=Object.keys(t);a.sort();const r=a.length;let i,n,s,o,c,l=12+16*r;const h=[l];for(i=0;i>>0;h.push(l)}const u=new Uint8Array(l);for(i=0;i>>0}writeInt32(u,l+4,e);writeInt32(u,l+8,h[i]);writeInt32(u,l+12,t[c].length);l+=16}return u}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const zr=[4],Wr=[5],$r=[6],Gr=[7],Vr=[8],Kr=[12,35],Jr=[14],Yr=[21],Zr=[22],Qr=[30],ei=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,a){const r=e.length;let i,n,s,o=!1;for(let c=0;cr)return!0;const i=r-e;for(let e=i;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);a?this.stack.splice(i,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,a){if(a>=e.length)return new Uint8Array(0);let r,i,n=0|t;for(r=0;r>8;n=52845*(t+n)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,a){if(t){const t=e.getBytes(),a=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(a?decrypt(t,55665,4):function decryptAscii(e,t,a){let r=0|t;const i=e.length,n=new Uint8Array(i>>>1);let s,o;for(s=0,o=0;s>8;r=52845*(e+r)+22719&65535}}return n.slice(a,o)}(t,55665,4))}this.seacAnalysisEnabled=!!a;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let a="";do{a+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return a}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,a=[],r=[],i=Object.create(null);i.lenIV=4;const n={subrs:[],charstrings:[],properties:{privateData:i}};let s,o,c,l;for(;null!==(s=this.getToken());)if("/"===s){s=this.getToken();switch(s){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){s=this.getToken();if(null===s||"end"===s)break;if("/"!==s)continue;const e=this.getToken();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const a=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s?this.getToken():"/"===s&&this.prevChar();r.push({glyph:e,encoded:a})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const r=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s&&this.getToken();a[e]=r}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":n.properties.privateData[s]=this.readNumberArray();break;case"StdHW":case"StdVW":n.properties.privateData[s]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":n.properties.privateData[s]=this.readNumber();break;case"ExpansionFactor":n.properties.privateData[s]=this.readNumber()||.06;break;case"ForceBold":n.properties.privateData[s]=this.readBoolean()}}for(const{encoded:t,glyph:i}of r){const r=new Type1CharString,s=r.convert(t,a,this.seacAnalysisEnabled);let o=r.output;s&&(o=[14]);const c={glyphName:i,charstring:o,width:r.width,lsb:r.lsb,seac:r.seac};".notdef"===i?n.charstrings.unshift(c):n.charstrings.push(c);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(i);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=r.width)}}return n}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const a=this.readNumberArray();e.fontMatrix=a;break;case"Encoding":const r=this.getToken();let i;if(/^\d+$/.test(r)){i=[];const e=0|parseInt(r,10);this.getToken();for(let a=0;a=i){s+=a;for(;s=0&&(r[e]=i)}}return type1FontGlyphMapping(e,r,a)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let a=0,r=e.length;a0;e--)t[e]-=t[e-1];f.setByName(e,t)}n.topDict.privateDict=f;const p=new CFFIndex;for(h=0,u=r.length;h0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,a,r,i,n,s,o,c){this.originalCharCode=e;this.fontChar=t;this.unicode=a;this.accent=r;this.width=i;this.vmetric=n;this.operatorListId=s;this.isSpace=o;this.isInFont=c}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=vr.get(e);if(t)return t;const a=e.match(Cr),r={isWhitespace:!!a?.[1],isZeroWidthDiacritic:!!a?.[2],isInvisibleFormatMark:!!a?.[3]};vr.set(e,r);return r}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,a){e[t+1]=a;e[t]=a>>>8}function signedInt16(e,t){const a=(e<<8)+t;return 32768&a?a-65536:a}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:a,composite:r}){let i,n;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))i=r?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))i=r?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))i=r?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(r){i="CIDFontType0";n="CIDFontType0C"}else{i="MMType1"===t?"MMType1":"Type1";n="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");i=t;n=a}return[i,n]}function applyStandardFontGlyphMap(e,t){for(const a in t)e[+a]=t[a]}function buildToFontChar(e,t,a){const r=[];let i;for(let a=0,n=e.length;ah){c++;if(c>=ti.length){warn("Ran out of space in font private use area.");break}l=ti[c][0];h=ti[c][1]}const g=l++;0===f&&(f=a);let p=r.get(d);"string"==typeof p&&(p=p.codePointAt(0));if(p&&!(u=p,ti[0][0]<=u&&u<=ti[0][1]||ti[1][0]<=u&&u<=ti[1][1])&&!o.has(f)){n.set(p,f);o.add(f)}i[g]=f;s[d]=g}var u;return{toFontChar:s,charCodeToGlyphId:i,toUnicodeExtraMap:n,nextAvailableFontCharCode:l}}function createCmapTable(e,t,a){const r=function getRanges(e,t,a){const r=[];for(const t in e)e[t]>=a||r.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,i]of t)i>=a||r.push({fontCharCode:e,glyphId:i});0===r.length&&r.push({fontCharCode:0,glyphId:0});r.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const i=[],n=r.length;for(let e=0;e65535?2:1;let n,s,o,c,l="\0\0"+string16(i)+"\0\0"+string32(4+8*i);for(n=r.length-1;n>=0&&!(r[n][0]<=65535);--n);const h=n+1;r[n][0]<65535&&65535===r[n][1]&&(r[n][1]=65534);const u=r[n][1]<65535?1:0,d=h+u,f=OpenTypeFileBuilder.getSearchParams(d,2);let g,p,m,b,y="",w="",x="",S="",k="",C=0;for(n=0,s=h;n0){w+="ÿÿ";y+="ÿÿ";x+="\0";S+="\0\0"}const v="\0\0"+string16(2*d)+string16(f.range)+string16(f.entry)+string16(f.rangeShift)+w+"\0\0"+y+x+S+k;let F="",O="";if(i>1){l+="\0\0\n"+string32(4+8*i+4+v.length);F="";for(n=0,s=r.length;ne||!c)&&(c=e);l 123 are reserved for internal usage");o|=1<65535&&(l=65535)}else{c=0;l=255}const u=e.bbox||[0,0,0,0],d=a.unitsPerEm||1/(e.fontMatrix||r)[0],f=e.ascentScaled?1:d/ai,g=a.ascent||Math.round(f*(e.ascent||u[3]));let p=a.descent||Math.round(f*(e.descent||u[1]));p>0&&e.descent>0&&u[1]<0&&(p=-p);const m=a.yMax||g,b=-a.yMin||-p;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(i)+string32(n)+string32(s)+string32(o)+"*21*"+string16(e.italicAngle?1:0)+string16(c||e.firstChar)+string16(l||e.lastChar)+string16(g)+string16(p)+"\0d"+string16(m)+string16(b)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(c||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const a=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],r=[];let i,n,s,o,c;for(i=0,n=a.length;i0;if((s||o)&&"CIDFontType2"===a&&this.cidEncoding.startsWith("Identity-")){const a=e.cidToGidMap,r=[];applyStandardFontGlyphMap(r,jr());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(r,_r()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(r,Ur());if(a){for(const e in r){const t=r[e];void 0!==a[t]&&(r[+e]=a[t])}a.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const i=r[e];void 0===a[i]&&(r[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){r[+e]=t}));this.toFontChar=r;this.toUnicode=new ToUnicodeMap(r)}else if(/Symbol/i.test(r))this.toFontChar=buildToFontChar(ur,xr(),this.differences);else if(/Dingbats/i.test(r))this.toFontChar=buildToFontChar(dr,Sr(),this.differences);else if(s){const e=buildToFontChar(this.defaultEncoding,xr(),this.differences);"CIDFontType2"!==a||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,a){e[+t]=a}));this.toFontChar=e}else{const e=xr(),a=[];this.toUnicode.forEach(((t,r)=>{if(!this.composite){const a=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==a&&(r=a)}a[+t]=r}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(a,jr());this.toFontChar=a}amendFallbackToUnicode(e);this.loadedName=r.split("-",1)[0]}checkAndRepair(e,t,a){const r=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const a=Object.create(null);a["OS/2"]=null;a.cmap=null;a.head=null;a.hhea=null;a.hmtx=null;a.maxp=null;a.name=null;a.post=null;for(let i=0;i>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0,n=e.pos;e.pos=e.start||0;e.skip(r);const s=e.getBytes(i);e.pos=n;if("head"===t){s[8]=s[9]=s[10]=s[11]=0;s[17]|=32}return{tag:t,checksum:a,length:i,offset:r,data:s}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,a,r,i,n){const s={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||a>e.length||a-t<=12)return s;const o=e.subarray(t,a),c=signedInt16(o[2],o[3]),l=signedInt16(o[4],o[5]),h=signedInt16(o[6],o[7]),u=signedInt16(o[8],o[9]);if(c>h){writeSignedInt16(o,2,h);writeSignedInt16(o,6,c)}if(l>u){writeSignedInt16(o,4,u);writeSignedInt16(o,8,l)}const d=signedInt16(o[0],o[1]);if(d<0){if(d<-1)return s;r.set(o,i);s.length=o.length;return s}let f,g=10,p=0;for(f=0;fo.length)return s;if(!n&&b>0){r.set(o.subarray(0,m),i);r.set([0,0],i+m);r.set(o.subarray(y,x),i+m+2);x-=b;o.length-x>3&&(x=x+3&-4);s.length=x;return s}if(o.length-x>3){x=x+3&-4;r.set(o.subarray(0,x),i);s.length=x;return s}r.set(o,i);s.length=o.length;return s}function readNameTable(e){const a=(t.start||0)+e.offset;t.pos=a;const r=[[],[]],i=[],n=e.length,s=a+n;if(0!==t.getUint16()||n<6)return[r,i];const o=t.getUint16(),c=t.getUint16();let l,h;for(l=0;ls)continue;t.pos=n;const o=e.name;if(e.encoding){let a="";for(let r=0,i=e.length;r0&&(l+=e-1)}}else{if(m||y){warn("TT: nested FDEFs not allowed");p=!0}m=!0;u=l;s=d.pop();t.functionsDefined[s]={data:c,i:l}}else if(!m&&!y){s=d.at(-1);if(isNaN(s))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[s]=!0;if(s in t.functionsStackDeltas){const e=d.length+t.functionsStackDeltas[s];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}d.length=e}else if(s in t.functionsDefined&&!g.includes(s)){f.push({data:c,i:l,stackTop:d.length-1});g.push(s);o=t.functionsDefined[s];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}c=o.data;l=o.i}}}if(!m&&!y){let t=0;e<=142?t=i[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){r=d.pop();isNaN(r)||(t=2*-r)}for(;t<0&&d.length>0;){d.pop();t++}for(;t>0;){d.push(NaN);t--}}}t.tooComplexToFollowFunctions=p;const w=[c];l>c.length&&w.push(new Uint8Array(l-c.length));if(u>h){warn("TT: complementing a missing function tail");w.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let a,r,i=0;for(a=0,r=t.length;a>>0,n=[];for(let t=0;t>>0);const s={ttcTag:t,majorVersion:a,minorVersion:r,numFonts:i,offsetTable:n};switch(a){case 1:return s;case 2:s.dsigTag=e.getInt32()>>>0;s.dsigLength=e.getInt32()>>>0;s.dsigOffset=e.getInt32()>>>0;return s}throw new FormatError(`Invalid TrueType Collection majorVersion: ${a}.`)}(e),i=t.split("+");let n;for(let s=0;s0||!(a.cMap instanceof IdentityCMap));if("OTTO"===n.version&&!t||!s.head||!s.hhea||!s.maxp||!s.post){c=new Stream(s["CFF "].data);o=new CFFFont(c,a);adjustWidths(a);return this.convert(e,o,a)}delete s.glyf;delete s.loca;delete s.fpgm;delete s.prep;delete s["cvt "];this.isOpenType=!0}if(!s.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+s.maxp.offset;let h=t.getInt32();const u=t.getUint16();if(65536!==h&&20480!==h){if(6===s.maxp.length)h=20480;else{if(!(s.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');h=65536}!function writeUint32(e,t,a){e[t+3]=255&a;e[t+2]=a>>>8;e[t+1]=a>>>16;e[t]=a>>>24}(s.maxp.data,0,h)}if(a.scaleFactors?.length===u&&l){const{scaleFactors:e}=a,t=int16(s.head.data[50],s.head.data[51]),r=new GlyfTable({glyfTable:s.glyf.data,isGlyphLocationsLong:t,locaTable:s.loca.data,numGlyphs:u});r.scale(e);const{glyf:i,loca:n,isLocationLong:o}=r.write();s.glyf.data=i;s.loca.data=n;if(o!==!!t){s.head.data[50]=0;s.head.data[51]=o?1:0}const c=s.hmtx.data;for(let t=0;t>8&255;c[a+1]=255&r;writeSignedInt16(c,a+2,Math.round(e[t]*signedInt16(c[a+2],c[a+3])))}}let d=u+1,f=!0;if(d>65535){f=!1;d=u;warn("Not enough space in glyfs to duplicate first glyph.")}let g=0,p=0;if(h>=65536&&s.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){s.maxp.data[14]=0;s.maxp.data[15]=2}t.pos+=4;g=t.getUint16();t.pos+=4;p=t.getUint16()}s.maxp.data[4]=d>>8;s.maxp.data[5]=255&d;const m=function sanitizeTTPrograms(e,t,a,r){const i={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,i);t&&sanitizeTTProgram(t,i);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let a=0,r=e.functionsUsed.length;at){warn("TT: invalid function id: "+a);e.hintsValid=!1;return}if(e.functionsUsed[a]&&!e.functionsDefined[a]){warn("TT: undefined function: "+a);e.hintsValid=!1;return}}}(i,r);if(a&&1&a.length){const e=new Uint8Array(a.length+1);e.set(a.data);a.data=e}return i.hintsValid}(s.fpgm,s.prep,s["cvt "],g);if(!m){delete s.fpgm;delete s.prep;delete s["cvt "]}!function sanitizeMetrics(e,t,a,r,i,n){if(!t){a&&(a.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const s=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==s){if(!(2&int16(r.data[44],r.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>i){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${i}).`);o=i;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const c=i-o-(a.length-4*o>>1);if(c>0){const e=new Uint8Array(a.length+2*c);e.set(a.data);if(n){e[a.length]=a.data[2];e[a.length+1]=a.data[3]}a.data=e}}(t,s.hhea,s.hmtx,s.head,d,f);if(!s.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,a){const r=e.data,i=function int32(e,t,a,r){return(e<<24)+(t<<16)+(a<<8)+r}(r[0],r[1],r[2],r[3]);if(i>>16!=1){info("Attempting to fix invalid version in head table: "+i);r[0]=0;r[1]=1;r[2]=0;r[3]=0}const n=int16(r[50],r[51]);if(n<0||n>1){info("Attempting to fix invalid indexToLocFormat in head table: "+n);const e=t+1;if(a===e<<1){r[50]=0;r[51]=0}else{if(a!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+n);r[50]=0;r[51]=1}}}(s.head,u,l?s.loca.length:0);let b=Object.create(null);if(l){const e=int16(s.head.data[50],s.head.data[51]),t=function sanitizeGlyphLocations(e,t,a,r,i,n,s){let o,c,l;if(r){o=4;c=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};l=function fontItemEncodeLong(e,t,a){e[t]=a>>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}}else{o=2;c=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};l=function fontItemEncode(e,t,a){e[t]=a>>9&255;e[t+1]=a>>1&255}}const h=n?a+1:a,u=o*(1+h),d=new Uint8Array(u);d.set(e.data.subarray(0,u));e.data=d;const f=t.data,g=f.length,p=new Uint8Array(g);let m,b;const y=[];for(m=0,b=0;mg&&(e=g);y.push({index:m,offset:e,endOffset:0})}y.sort(((e,t)=>e.offset-t.offset));for(m=0;me.index-t.index));for(m=0;ms&&(s=e.sizeOfInstructions);S+=t;l(d,b,S)}if(0===S){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(m=0,b=o;ma+S)t.data=p.subarray(0,a+S);else{t.data=new Uint8Array(a+S);t.data.set(p.subarray(0,S))}t.data.set(p.subarray(0,a),S);l(e.data,d.length-o,S+a)}else t.data=p.subarray(0,S);return{missingGlyphs:x,maxSizeOfInstructions:s}}(s.loca,s.glyf,u,e,m,f,p);b=t.missingGlyphs;if(h>=65536&&s.maxp.length>=32){s.maxp.data[26]=t.maxSizeOfInstructions>>8;s.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!s.hhea)throw new FormatError('Required "hhea" table is not found');if(0===s.hhea.data[10]&&0===s.hhea.data[11]){s.hhea.data[10]=255;s.hhea.data[11]=255}const y={unitsPerEm:int16(s.head.data[18],s.head.data[19]),yMax:signedInt16(s.head.data[42],s.head.data[43]),yMin:signedInt16(s.head.data[38],s.head.data[39]),ascent:signedInt16(s.hhea.data[4],s.hhea.data[5]),descent:signedInt16(s.hhea.data[6],s.hhea.data[7]),lineGap:signedInt16(s.hhea.data[8],s.hhea.data[9])};this.ascent=y.ascent/y.unitsPerEm;this.descent=y.descent/y.unitsPerEm;this.lineGap=y.lineGap/y.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;s.post&&function readPostScriptTable(e,a,r){const i=(t.start||0)+e.offset;t.pos=i;const n=i+e.length,s=t.getInt32();t.skip(28);let o,c,l=!0;switch(s){case 65536:o=Dr;break;case 131072:const e=t.getUint16();if(e!==r){l=!1;break}const i=[];for(c=0;c=32768){l=!1;break}i.push(e)}if(!l)break;const h=[],u=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let i=-1;t?i=r:void 0!==e[r]&&(i=e[r]);i>=0&&i>>0;let h=!1;if(o?.platformId!==i||o?.encodingId!==n){if(0!==i||0!==n&&1!==n&&3!==n)if(1===i&&0===n)h=!0;else if(3!==i||1!==n||!r&&o){if(a&&3===i&&0===n){h=!0;let a=!0;if(e>3;e.push(r);a=Math.max(r,a)}const r=[];for(let e=0;e<=a;e++)r.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let a=0;a<256;a++)if(0===e[a]){t.pos=r[0].idRangePos+2*a;f=t.getUint16();u.push({charCode:a,glyphId:f})}else{const i=r[e[a]];for(d=0;d>1;t.skip(6);const a=[];let r;for(r=0;r>1)-(e-r);i.offsetIndex=s;o=Math.max(o,s+i.end-i.start+1)}else i.offsetIndex=-1}const c=[];for(d=0;d>>0;for(d=0;d>>0,a=t.getInt32()>>>0;let r=t.getInt32()>>>0;for(let t=e;t<=a;t++)u.push({charCode:t,glyphId:r++})}}}u.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);w[t]=e.glyphId}else for(const e of n)w[e.charCode]=e.glyphId;if(a.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!c&&void 0!==w[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const r=a.glyphNames.indexOf(t);r>0&&hasGlyph(r)&&(w[e]=r)}}0===w.length&&(w[0]=0);let x=d-1;f||(x=0);if(!a.cssFontInfo){const e=adjustMapping(w,hasGlyph,x,this.toUnicode);this.toFontChar=e.toFontChar;s.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,d)};s["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const a=t.getUint16();t.skip(60);const r=t.getUint16();if(a<4&&768&r)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(s["OS/2"],t)||(s["OS/2"]={tag:"OS/2",data:createOS2Table(a,e.charCodeToGlyphId,y)})}if(!l)try{c=new Stream(s["CFF "].data);o=new CFFParser(c,a,Fr).parse();o.duplicateFirstGlyph();const e=new CFFCompiler(o);s["CFF "].data=e.compile()}catch{warn("Failed to compile font "+a.loadedName)}if(s.name){const[t,r]=readNameTable(s.name);s.name.data=createNameTable(e,t);this.psName=t[0][6]||null;a.composite||function adjustTrueTypeToUnicode(e,t,a){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===a.length)return;if(e.defaultEncoding===hr)return;for(const e of a)if(!isWinNameRecord(e))return;const r=hr,i=[],n=xr();for(const e in r){const t=r[e];if(""===t)continue;const a=n[t];void 0!==a&&(i[e]=String.fromCharCode(a))}i.length>0&&e.toUnicode.amend(i)}(a,this.isSymbolicFont,r)}else s.name={tag:"name",data:createNameTable(this.name)};const S=new OpenTypeFileBuilder(n.version);for(const e in s)S.addTable(e,s[e].data);return S.toArray()}convert(e,t,a){a.fixedPitch=!1;a.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const a=[],r=xr();for(const i in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[i]))continue;const n=getUnicodeForGlyph(t[i],r);-1!==n&&(a[i]=String.fromCharCode(n))}a.length>0&&e.toUnicode.amend(a)}(a,a.builtInEncoding);let i=1;t instanceof CFFFont&&(i=t.numGlyphs-1);const n=t.getGlyphMapping(a);let s=null,o=n,c=null;if(!a.cssFontInfo){s=adjustMapping(n,t.hasGlyphId.bind(t),i,this.toUnicode);this.toFontChar=s.toFontChar;o=s.charCodeToGlyphId;c=s.toUnicodeExtraMap}const l=t.numGlyphs;function getCharCodes(e,t){let a=null;for(const r in e)t===e[r]&&(a||=[]).push(0|r);return a}function createCharCode(e,t){for(const a in e)if(t===e[a])return 0|a;s.charCodeToGlyphId[s.nextAvailableFontCharCode]=t;return s.nextAvailableFontCharCode++}const h=t.seacs;if(s&&h?.length){const e=a.fontMatrix||r,i=t.getCharset(),o=Object.create(null);for(let t in h){t|=0;const a=h[t],r=lr[a[2]],c=lr[a[3]],l=i.indexOf(r),u=i.indexOf(c);if(l<0||u<0)continue;const d={x:a[0]*e[0]+a[1]*e[2]+e[4],y:a[0]*e[1]+a[1]*e[3]+e[5]},f=getCharCodes(n,t);if(f)for(const e of f){const t=s.charCodeToGlyphId,a=createCharCode(t,l),r=createCharCode(t,u);o[e]={baseFontCharCode:a,accentFontCharCode:r,accentOffset:d}}}a.seacMap=o}const u=1/(a.fontMatrix||r)[0],d=new OpenTypeFileBuilder("OTTO");d.addTable("CFF ",t.data);d.addTable("OS/2",createOS2Table(a,o));d.addTable("cmap",createCmapTable(o,c,l));d.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(u)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(a.descent)+"ÿ"+safeString16(a.ascent)+string16(a.italicAngle?2:0)+"\0\0\0\0\0\0\0");d.addTable("hhea","\0\0\0"+safeString16(a.ascent)+safeString16(a.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(a.capHeight)+safeString16(Math.tan(a.italicAngle)*a.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(l));d.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,a=t.cff?t.cff.widths:null;let r="\0\0\0\0";for(let t=1,i=l;t=65520&&e<=65535?0:e>=62976&&e<=63743?kr()[e]||e:173===e?45:e}(a)}this.isType3Font&&(i=a);let h=null;if(this.seacMap?.[e]){l=!0;const t=this.seacMap[e];a=t.baseFontCharCode;h={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let u="";"number"==typeof a&&(a<=1114111?u=String.fromCodePoint(a):warn(`charToGlyph - invalid fontCharCode: ${a}`));n=new fonts_Glyph(e,u,c,h,r,o,i,t,l);return this._glyphCache[e]=n}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const a=Object.create(null),r=e.length;let i=0;for(;it.length%2==1,r=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let i=0,n=e.length;i55295&&(n<57344||n>65533)&&i++;if(this.toUnicode){const e=r(n);if(-1!==e){if(hasCurrentBufErrors()){t.push(a.join(""));a.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)a.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(a.join(""));a.length=0}a.push(String.fromCodePoint(n))}t.push(a.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const ni=2,si=3,oi=4,ci=5,li=6,hi=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,a,r,i){const n=e instanceof BaseStream?e.dict:e,s=n.get("ShadingType");try{switch(s){case ni:case si:return new RadialAxialShading(n,t,a,r,i);case oi:case ci:case li:case hi:return new MeshShading(e,t,a,r,i);default:throw new FormatError("Unsupported ShadingType: "+s)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;constructor(){this.constructor===BaseShading&&unreachable("Cannot initialize BaseShading.")}getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,a,r,i){super();this.coordsArr=e.getArray("Coords");this.shadingType=e.get("ShadingType");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:a,pdfFunctionFactory:r,localColorSpaceCache:i}),s=e.getArray("BBox");this.bbox=Array.isArray(s)&&4===s.length?Util.normalizeRect(s):null;let o=0,c=1;if(e.has("Domain")){const t=e.getArray("Domain");o=t[0];c=t[1]}let l=!1,h=!1;if(e.has("Extend")){const t=e.getArray("Extend");l=t[0];h=t[1]}if(!(this.shadingType!==si||l&&h)){const[e,t,a,r,i,n]=this.coordsArr,s=Math.hypot(e-r,t-i);a<=n+s&&n<=a+s&&warn("Unsupported radial gradient.")}this.extendStart=l;this.extendEnd=h;const u=e.getRaw("Function"),d=r.createFromArray(u),f=(c-o)/840,g=this.colorStops=[];if(o>=c||f<=0){info("Bad shading domain.");return}const p=new Float32Array(n.numComps),m=new Float32Array(1);let b,y=0;m[0]=o;d(m,0,p,0);let w=n.getRgb(p,0);const x=Util.makeHexColor(w[0],w[1],w[2]);g.push([0,x]);let S=1;m[0]=o+f;d(m,0,p,0);let k=n.getRgb(p,0),C=k[0]-w[0]+1,v=k[1]-w[1]+1,F=k[2]-w[2]+1,O=k[0]-w[0]-1,T=k[1]-w[1]-1,M=k[2]-w[2]-1;for(let e=2;e<840;e++){m[0]=o+e*f;d(m,0,p,0);b=n.getRgb(p,0);const t=e-y;C=Math.min(C,(b[0]-w[0]+1)/t);v=Math.min(v,(b[1]-w[1]+1)/t);F=Math.min(F,(b[2]-w[2]+1)/t);O=Math.max(O,(b[0]-w[0]-1)/t);T=Math.max(T,(b[1]-w[1]-1)/t);M=Math.max(M,(b[2]-w[2]-1)/t);if(!(O<=C&&T<=v&&M<=F)){const e=Util.makeHexColor(k[0],k[1],k[2]);g.push([S/840,e]);C=b[0]-k[0]+1;v=b[1]-k[1]+1;F=b[2]-k[2]+1;O=b[0]-k[0]-1;T=b[1]-k[1]-1;M=b[2]-k[2]-1;y=S;w=k}S=e;k=b}const D=Util.makeHexColor(k[0],k[1],k[2]);g.push([1,D]);let R="transparent";if(e.has("Background")){b=n.getRgb(e.get("Background"),0);R=Util.makeHexColor(b[0],b[1],b[2])}if(!l){g.unshift([0,R]);g[1][0]+=BaseShading.SMALL_NUMBER}if(!h){g.at(-1)[0]-=BaseShading.SMALL_NUMBER;g.push([1,R])}this.colorStops=g}getIR(){const e=this.coordsArr,t=this.shadingType;let a,r,i,n,s;if(t===ni){r=[e[0],e[1]];i=[e[2],e[3]];n=null;s=null;a="axial"}else if(t===si){r=[e[0],e[1]];i=[e[3],e[4]];n=e[2];s=e[5];a="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",a,this.bbox,this.colorStops,r,i,n,s]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const a=t.numComps;this.tmpCompsBuf=new Float32Array(a);const r=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(r):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,a=this.bufferLength;if(32===e){if(0===a)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>a)>>>0}if(8===e&&0===a)return this.stream.getByte();for(;a>a}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),a=this.readBits(e),r=this.context.decode,i=e<32?1/((1<n?n:e;t=t>s?s:t;a=ae*i[t])):a;let s,o=-2;const c=[];for(const[e,t]of r.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===o+1){s.push(n[t]);o+=1}else{o=e;s=[n[t]];c.push(e,s)}return c}(e),a=new Dict(null);a.set("BaseFont",Name.get(e));a.set("Type",Name.get("Font"));a.set("Subtype",Name.get("CIDFontType2"));a.set("Encoding",Name.get("Identity-H"));a.set("CIDToGIDMap",Name.get("Identity"));a.set("W",t);a.set("FirstChar",t[0]);a.set("LastChar",t.at(-2)+t.at(-1).length-1);const r=new Dict(null);a.set("FontDescriptor",r);const i=new Dict(null);i.set("Ordering","Identity");i.set("Registry","Adobe");i.set("Supplement",0);a.set("CIDSystemInfo",i);return a}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(tn.LBRACE);this.parseBlock();this.expect(tn.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(tn.NUMBER))this.operators.push(this.prev.value);else if(this.accept(tn.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(tn.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(tn.RBRACE);if(this.accept(tn.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(tn.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const a=this.operators.length;this.parseBlock();this.expect(tn.RBRACE);this.expect(tn.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=a;this.operators[e+1]="jz"}}}}const tn={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(tn.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(tn.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(tn.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(tn.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(tn.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return da;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(tn.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const a=this.strBuf;a.length=0;a[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)a.push(String.fromCharCode(t));const r=a.join("");switch(r.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(r)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const a=parseFloat(t.join(""));if(isNaN(a))throw new FormatError(`Invalid floating point number: ${a}`);return a}}class BaseLocalCache{constructor(e){this.constructor===BaseLocalCache&&unreachable("Cannot initialize BaseLocalCache.");this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,a){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,a){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get _byteSize(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get _cacheLimitReached(){return!(this._imageCache.size>c)*h;l&=(1<a?e=a:e0&&(d=n[u-1]);let f=r[1];u>1,l=i.length>>1,h=new PostScriptEvaluator(o),u=Object.create(null);let d=8192;const f=new Float32Array(l);return function constructPostScriptFn(e,t,a,r){let i,s,o="";const g=f;for(i=0;ie&&(s=e)}m[i]=s}if(d>0){d--;u[o]=m}a.set(m,r)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let a=t.length-e,r=e-1;r>=0;r--,a++)t.push(t[a])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const a=this.stack,r=a.length-e,i=a.length-1,n=r+(t-Math.floor(t/e)*e);for(let e=r,t=i;e0?t.push(s<>o);break;case"ceiling":s=t.pop();t.push(Math.ceil(s));break;case"copy":s=t.pop();t.copy(s);break;case"cos":s=t.pop();t.push(Math.cos(s%360/180*Math.PI));break;case"cvi":s=0|t.pop();t.push(s);break;case"cvr":break;case"div":o=t.pop();s=t.pop();t.push(s/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();s=t.pop();t.push(s===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();s=t.pop();t.push(s**o);break;case"false":t.push(!1);break;case"floor":s=t.pop();t.push(Math.floor(s));break;case"ge":o=t.pop();s=t.pop();t.push(s>=o);break;case"gt":o=t.pop();s=t.pop();t.push(s>o);break;case"idiv":o=t.pop();s=t.pop();t.push(s/o|0);break;case"index":s=t.pop();t.index(s);break;case"le":o=t.pop();s=t.pop();t.push(s<=o);break;case"ln":s=t.pop();t.push(Math.log(s));break;case"log":s=t.pop();t.push(Math.log10(s));break;case"lt":o=t.pop();s=t.pop();t.push(s=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,a){const r=[],i=[],n=t.length>>1,s=a.length>>1;let o,c,l,h,u,d,f,g,p=0;for(let e=0;et.min){o.unshift("Math.max(",n,", ");o.push(")")}if(s4){r=!0;t=0}else{r=!1;t=1}const c=[];for(n=0;n=0&&"ET"===sn[e];--e)sn[e]="EN";for(let e=n+1;e0&&(t=sn[n-1]);let a=u;e+1g&&isOdd(g)&&(m=g)}for(g=p;g>=m;--g){let e=-1;for(n=0,s=c.length;n=0){reverseValues(nn,e,n);e=-1}}else e<0&&(e=n);e>=0&&reverseValues(nn,e,c.length)}for(n=0,s=nn.length;n"!==e||(nn[n]="")}return createBidiText(nn.join(""),r)}const on={style:"normal",weight:"normal"},cn={style:"normal",weight:"bold"},ln={style:"italic",weight:"normal"},hn={style:"italic",weight:"bold"},un=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:on,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:cn,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:ln,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:hn,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:on,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:cn,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:ln,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:hn,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:on,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:cn,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:ln,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:hn,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:on,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:cn,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:ln,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:hn,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:on,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:cn,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:ln,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:hn,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:on}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),dn=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:a,fallback:r,style:i,ultimate:n},s,o,c=!0,l=!0,h=""){const u={style:null,ultimate:null};if(t){const e=h?` ${h}`:"";for(const a of t)s.push(`local(${a}${e})`)}if(e){const t=un.get(e),n=h||function getStyleToAppend(e){switch(e){case cn:return"Bold";case ln:return"Italic";case hn:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(i);Object.assign(u,generateFont(t,s,o,c&&!r,l&&!a,n))}i&&(u.style=i);n&&(u.ultimate=n);if(c&&r){const e=un.get(r),{ultimate:t}=generateFont(e,s,o,c,l&&!a,h);u.ultimate||=t}l&&a&&o&&s.push(`url(${o}${a})`);return u}function getFontSubstitution(e,t,a,r,i){if(r.startsWith("InvalidPDFjsFont_"))return null;const n=r=normalizeFontName(r);let s=e.get(n);if(s)return s;let o=un.get(r);if(!o)for(const[e,t]of dn)if(r.startsWith(e)){r=`${t}${r.substring(e.length)}`;o=un.get(r);break}let c=!1;if(!o){o=un.get(i);c=!0}const l=`${t.getDocId()}_s${t.createFontId()}`;if(!o){if(!validateFontName(r)){e.set(n,null);return null}const t=/bold/gi.test(r),a=/oblique|italic/gi.test(r),i=t&&a&&hn||t&&cn||a&&ln||on;s={css:`"${getFamilyName(r)}",${l}`,guessFallback:!0,loadedName:l,baseFontName:r,src:`local(${r})`,style:i};e.set(n,s);return s}const h=[];c&&validateFontName(r)&&h.push(`local(${r})`);const{style:u,ultimate:d}=generateFont(o,h,a),f=null===d,g=f?"":`,${d}`;s={css:`"${getFamilyName(r)}",${l}${g}`,guessFallback:f,loadedName:l,baseFontName:r,src:h.join(","),style:u};e.set(n,s);return s}class ImageResizer{constructor(e,t){this._imgData=e;this._isMask=t}static needsToBeResized(e,t){if(e<=this._goodSquareLength&&t<=this._goodSquareLength)return!1;const{MAX_DIM:a}=this;if(e>a||t>a)return!0;const r=e*t;if(this._hasMaxArea)return r>this.MAX_AREA;if(r(this.MAX_AREA=this._goodSquareLength**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(ImageResizer._goodSquareLength,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setMaxArea(e){this._hasMaxArea||(this.MAX_AREA=e>>2)}static _areGoodDims(e,t){try{const a=new OffscreenCanvas(e,t),r=a.getContext("2d");r.fillRect(0,0,1,1);const i=r.getImageData(0,0,1,1).data[3];a.width=a.height=1;return 0!==i}catch{return!1}}static _guessMax(e,t,a,r){for(;e+a+1>3,s=a+3&-4;if(a!==s){const e=new Uint8Array(s*t);let r=0;for(let n=0,o=t*a;n>>8;t[a++]=255&i}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();a=t.byteLength}const r=a>>2,i=a-4*r,n=new Uint32Array(t.buffer,0,r);let s=0,o=0,c=this.h1,l=this.h2;const h=3432918353,u=461845907,d=11601,f=13715;for(let e=0;e>>17;s=s*u&gn|s*f&pn;c^=s;c=c<<13|c>>>19;c=5*c+3864292196}else{o=n[e];o=o*h&gn|o*d&pn;o=o<<15|o>>>17;o=o*u&gn|o*f&pn;l^=o;l=l<<13|l>>>19;l=5*l+3864292196}s=0;switch(i){case 3:s^=t[4*r+2]<<16;case 2:s^=t[4*r+1]<<8;case 1:s^=t[4*r];s=s*h&gn|s*d&pn;s=s<<15|s>>>17;s=s*u&gn|s*f&pn;1&r?c^=s:l^=s}this.h1=c;this.h2=l}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&gn|36045*e&pn;t=4283543511*t&gn|(2950163797*(t<<16|e>>>16)&gn)>>>16;e^=t>>>1;e=444984403*e&gn|60499*e&pn;t=3301882366*t&gn|(3120437893*(t<<16|e>>>16)&gn)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,a,r,i){let n=e;for(let e=0,a=t.length-1;e1e3){l=Math.max(l,d);f+=u+2;d=0;u=0}h.push({transform:t,x:d,y:f,w:a.width,h:a.height});d+=a.width+2;u=Math.max(u,a.height)}const g=Math.max(l,d)+1,p=f+u+1,m=new Uint8Array(g*p*4),b=g<<2;for(let e=0;e=0;){t[n-4]=t[n];t[n-3]=t[n+1];t[n-2]=t[n+2];t[n-1]=t[n+3];t[n+a]=t[n+a-4];t[n+a+1]=t[n+a-3];t[n+a+2]=t[n+a-2];t[n+a+3]=t[n+a-1];n-=b}}const y={width:g,height:p};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(g,p);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(m.buffer),g,p),0,0);y.bitmap=e.transferToImageBitmap();y.data=null}else{y.kind=v;y.data=m}a.splice(n,4*c,Zt);r.splice(n,4*c,[y,h]);return n+1}));addState(mn,[Be,Ne,Vt,Re],null,(function iterateImageMaskGroup(e,t){const a=e.fnArray,r=(t-(e.iCurr-3))%4;switch(r){case 0:return a[t]===Be;case 1:return a[t]===Ne;case 2:return a[t]===Vt;case 3:return a[t]===Re}throw new Error(`iterateImageMaskGroup - invalid pos: ${r}`)}),(function foundImageMaskGroup(e,t){const a=e.fnArray,r=e.argsArray,i=e.iCurr,n=i-3,s=i-2,o=i-1;let c=Math.floor((t-n)/4);if(c<10)return t-(t-n)%4;let l,h,u=!1;const d=r[o][0],f=r[s][0],g=r[s][1],p=r[s][2],m=r[s][3];if(g===p){u=!0;l=s+4;let e=o+4;for(let t=1;t=4&&a[n-4]===a[s]&&a[n-3]===a[o]&&a[n-2]===a[c]&&a[n-1]===a[l]&&r[n-4][0]===h&&r[n-4][1]===u){d++;f-=5}let g=f+4;for(let e=1;e=a)break}r=(r||mn)[e[t]];if(r&&!Array.isArray(r)){n.iCurr=t;t++;if(!r.checkFn||(0,r.checkFn)(n)){i=r;r=null}else r=null}else t++}this.state=r;this.match=i;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&f?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===Re||e===et))&&this.flush()}addImageOps(e,t,a){void 0!==a&&this.addOp(jt,["OC",a]);this.addOp(e,t);void 0!==a&&this.addOp(_t,[])}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(Ae,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,a=e.length;tr&&(e=r);return e}function resizeImageMask(e,t,a,r,i,n){const s=i*n;let o;o=t<=8?new Uint8Array(s):t<=16?new Uint16Array(s):new Uint32Array(s);const c=a/i,l=r/n;let h,u,d,f,g=0;const p=new Uint16Array(i),m=a;for(h=0;h0&&Number.isInteger(a.height)&&a.height>0&&(a.width!==d||a.height!==f)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");d=a.width;f=a.height}if(d<1||f<1)throw new FormatError(`Invalid image width: ${d} or height: ${f}`);this.width=d;this.height=f;this.interpolate=l.get("I","Interpolate");this.imageMask=l.get("IM","ImageMask")||!1;this.matte=l.get("Matte")||!1;let g=a.bitsPerComponent;if(!g){g=l.get("BPC","BitsPerComponent");if(!g){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);g=1}}this.bpc=g;if(!this.imageMask){let i=l.getRaw("CS")||l.getRaw("ColorSpace");if(!i){info("JPX images (which do not require color spaces)");switch(a.numComps){case 1:i=Name.get("DeviceGray");break;case 3:i=Name.get("DeviceRGB");break;case 4:i=Name.get("DeviceCMYK");break;default:throw new Error(`JPX images with ${a.numComps} color components not supported.`)}}this.colorSpace=ColorSpace.parse({cs:i,xref:e,resources:r?t:null,pdfFunctionFactory:o,localColorSpaceCache:c});this.numComps=this.colorSpace.numComps}this.decode=l.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,g)||s&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*a,o=e.byteLength;let c,l;if(!r||i&&!(s===o))if(i){c=new Uint8Array(s);c.set(e);c.fill(255,o)}else c=new Uint8Array(e);else c=e;if(i)for(l=0;l>7&1;s[d+1]=u>>6&1;s[d+2]=u>>5&1;s[d+3]=u>>4&1;s[d+4]=u>>3&1;s[d+5]=u>>2&1;s[d+6]=u>>1&1;s[d+7]=1&u;d+=8}if(d>=1}}}}else{let a=0;u=0;for(d=0,h=n;d>r;i<0?i=0:i>l&&(i=l);s[d]=i;u&=(1<s[r+1]){t=255;break}}o[h]=t}}}if(o)for(h=0,d=3,u=t*r;h>3,h=t&&ImageResizer.needsToBeResized(a,r);if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===c?e=k:"DeviceRGB"!==this.colorSpace.name||8!==c||this.needsDecode||(e=C);if(e&&!this.smask&&!this.mask&&a===s&&r===o){const n=this.getImageBytes(o*l,{});if(t)return h?ImageResizer.createImage({data:n,kind:e,width:a,height:r,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,s,o,n);i.kind=e;i.data=n;if(this.needsDecode){assert(e===k,"PDFImage.createImageData: The image must be grayscale.");const t=i.data;for(let e=0,a=t.length;e>3,s=this.getImageBytes(r*n,{internal:!0}),o=this.getComponents(s);let c,l;if(1===i){l=a*r;if(this.needsDecode)for(c=0;c0&&e.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedu){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let d;o.has("OC")&&(d=await this.parseMarkedContentProps(o.get("OC"),e));let f,g;if(o.get("IM","ImageMask")||!1){const e=o.get("I","Interpolate"),a=l+7>>3,s=t.getBytes(a*h),u=o.getArray("D","Decode");if(this.parsingType3Font){f=PDFImage.createRawMask({imgArray:s,width:l,height:h,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:u?.[0]>0,interpolate:e});f.cached=!!i;g=[f];r.addImageOps(Vt,g,d);if(i){const e={fn:Vt,args:g,optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}f=await PDFImage.createMask({imgArray:s,width:l,height:h,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:u?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(f.isSingleOpaquePixel){r.addImageOps(ta,[],d);if(i){const e={fn:ta,args:[],optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}const p=`mask_${this.idFactory.createObjId()}`;r.addDependency(p);f.dataLen=f.bitmap?f.width*f.height*4:f.data.length;this._sendImgData(p,f);g=[{data:p,width:f.width,height:f.height,interpolate:f.interpolate,count:1}];r.addImageOps(Vt,g,d);if(i){const e={fn:Vt,args:g,optionalContent:d};n.set(i,c,e);c&&this._regionalImageCache.set(null,c,e)}return}if(a&&!o.has("SMask")&&!o.has("Mask")&&l+h<200){try{const i=new PDFImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:s});f=await i.createImageData(!0,!1);r.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;r.addImageOps(Yt,[f],d)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let p=`img_${this.idFactory.createObjId()}`,m=!1;if(this.parsingType3Font)p=`${this.idFactory.getDocId()}_type3_${p}`;else if(i&&c){m=this.globalImageCache.shouldCache(c,this.pageIndex);if(m){assert(!a,"Cannot cache an inline image globally.");p=`${this.idFactory.getDocId()}_${p}`}}r.addDependency(p);g=[p,l,h];r.addImageOps(Jt,g,d);if(m&&l*h>25e4){const e=await this.handler.sendWithPromise("commonobj",[p,"CopyLocalImage",{imageRef:c}]);if(e){this.globalImageCache.setData(c,{objId:p,fn:Jt,args:g,optionalContent:d,byteSize:0});this.globalImageCache.addByteSize(c,e);return}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:s}).then((async e=>{f=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);f.dataLen=f.bitmap?f.width*f.height*4:f.data.length;f.ref=c;m&&this.globalImageCache.addByteSize(c,f.dataLen);return this._sendImgData(p,f,m)})).catch((e=>{warn(`Unable to decode image "${p}": "${e}".`);return this._sendImgData(p,null,m)}));if(i){const e={fn:Jt,args:g,optionalContent:d};n.set(i,c,e);if(c){this._regionalImageCache.set(null,c,e);m&&this.globalImageCache.setData(c,{objId:p,fn:Jt,args:g,optionalContent:d,byteSize:0})}}}handleSMask(e,t,a,r,i,n){const s=e.get("G"),o={subtype:e.get("S").name,backdrop:e.get("BC")},c=e.get("TR");if(isPDFFunction(c)){const e=this._pdfFunctionFactory.create(c),t=new Uint8Array(256),a=new Float32Array(1);for(let r=0;r<256;r++){a[0]=r/255;e(a,0,a,0);t[r]=255*a[0]|0}o.transferMap=t}return this.buildFormXObject(t,s,o,a,r,i.state.clone(),n)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const a=[];let r=0,i=0;for(const e of t){const t=this.xref.fetchIfRef(e);r++;if(isName(t,"Identity")){a.push(null);continue}if(!isPDFFunction(t))return null;const n=this._pdfFunctionFactory.create(t),s=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;n(o,0,o,0);s[e]=255*o[0]|0}a.push(s);i++}return 1!==r&&4!==r||0===i?null:a}handleTilingType(e,t,a,r,i,n,s,o){const c=new OperatorList,l=Dict.merge({xref:this.xref,dictArray:[i.get("Resources"),a]});return this.getOperatorList({stream:r,task:s,resources:l,operatorList:c}).then((function(){const a=c.getIR(),r=getTilingPatternIR(a,i,t);n.addDependencies(c.dependencies);n.addOp(e,r);i.objId&&o.set(null,i.objId,{operatorListIR:a,dict:i})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,a,r,i,n,s=null,o=null){const c=t?.[0]instanceof Name?t[0].name:null;let l=await this.loadFont(c,a,e,s,o);if(l.font.isType3Font)try{await l.loadType3Data(this,e,i);r.addDependencies(l.type3Dependencies)}catch(e){l=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:l.font,evaluatorOptions:this.options})}n.font=l.font;l.send(this.handler);return l.loadedName}handleText(e,t){const a=t.font,r=a.charsToGlyphs(e);if(a.data){(!!(t.textRenderingMode&S)||"Pattern"===t.fillColorSpace.name||a.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(a,r,this.handler,this.options)}return r}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:a,cacheKey:r,task:i,stateManager:n,localGStateCache:s,localColorSpaceCache:o}){const c=t.objId;let l=!0;const h=[];let u=Promise.resolve();for(const r of t.getKeys()){const s=t.get(r);switch(r){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":h.push([r,s]);break;case"Font":l=!1;u=u.then((()=>this.handleSetFont(e,null,s[0],a,i,n.state).then((function(e){a.addDependency(e);h.push([r,[e,s[1]]])}))));break;case"BM":h.push([r,normalizeBlendMode(s)]);break;case"SMask":if(isName(s,"None")){h.push([r,!1]);break}if(s instanceof Dict){l=!1;u=u.then((()=>this.handleSMask(s,e,a,i,n,o)));h.push([r,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(s);h.push([r,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+r);break;default:info("Unknown graphic state operator "+r)}}await u;h.length>0&&a.addOp(De,[h]);l&&s.set(r,c,h)}loadFont(e,t,a,r=null,i=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let n;if(t)t instanceof Ref&&(n=t);else{const t=a.get("Font");t&&(n=t.getRaw(e))}if(n){if(this.parsingType3Font&&this.type3FontRefs.has(n))return errorFont();if(this.fontCache.has(n))return this.fontCache.get(n);t=this.xref.fetchIfRef(n)}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=r||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:s,resolve:o}=Promise.withResolvers();let c;try{c=this.preEvaluateFont(t);c.cssFontInfo=i}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:l,hash:h}=c,u=n instanceof Ref;let d;if(h&&l instanceof Dict){const e=l.fontAliases||=Object.create(null);if(e[h]){const t=e[h].aliasRef;if(u&&t&&this.fontCache.has(t)){this.fontCache.putAlias(n,t);return this.fontCache.get(n)}}else e[h]={fontID:this.idFactory.createFontId()};u&&(e[h].aliasRef=n);d=e[h].fontID}else d=this.idFactory.createFontId();assert(d?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(u)this.fontCache.put(n,s);else{t.cacheKey=`cacheKey_${d}`;this.fontCache.put(t.cacheKey,s)}t.loadedName=`${this.idFactory.getDocId()}_${d}`;this.translateFont(c).then((e=>{o(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);o(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return s}buildPath(e,t,a,r=!1){const i=e.length-1;a||(a=[]);if(i<0||e.fnArray[i]!==aa){if(r){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(Be,null)}let i;switch(t){case Xe:const e=a[0]+a[2],t=a[1]+a[3];i=[Math.min(a[0],e),Math.min(a[1],t),Math.max(a[0],e),Math.max(a[1],t)];break;case Ee:case Pe:i=[a[0],a[1],a[0],a[1]];break;default:i=[1/0,1/0,-1/0,-1/0]}e.addOp(aa,[[t],a,i]);r&&e.addOp(Re,null)}else{const r=e.argsArray[i];r[0].push(t);r[1].push(...a);const n=r[2];switch(t){case Xe:const e=a[0]+a[2],t=a[1]+a[3];n[0]=Math.min(n[0],a[0],e);n[1]=Math.min(n[1],a[1],t);n[2]=Math.max(n[2],a[0],e);n[3]=Math.max(n[3],a[1],t);break;case Ee:case Pe:n[0]=Math.min(n[0],a[0]);n[1]=Math.min(n[1],a[1]);n[2]=Math.max(n[2],a[0]);n[3]=Math.max(n[3],a[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:a}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:a}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:a,localShadingPatternCache:r}){let i,n=r.get(e);if(n)return n;try{i=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,a).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);r.set(e,null);return null}throw t}n=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(n=`${this.idFactory.getDocId()}_type3_${n}`);r.set(e,n);this.parsingType3Font?this.handler.send("commonobj",[n,"Pattern",i]):this.handler.send("obj",[n,this.pageIndex,"Pattern",i]);return n}handleColorN(e,t,a,r,i,n,s,o,c,l){const h=a.pop();if(h instanceof Name){const u=i.getRaw(h.name),d=u instanceof Ref&&c.getByRef(u);if(d)try{const i=r.base?r.base.getRgb(a,0):null,n=getTilingPatternIR(d.operatorListIR,d.dict,i);e.addOp(t,n);return}catch{}const f=this.xref.fetchIfRef(u);if(f){const i=f instanceof BaseStream?f.dict:f,h=i.get("PatternType");if(h===yn){const o=r.base?r.base.getRgb(a,0):null;return this.handleTilingType(t,o,n,f,i,e,s,c)}if(h===wn){const a=i.get("Shading"),r=this.parseShading({shading:a,resources:n,localColorSpaceCache:o,localShadingPatternCache:l});if(r){const a=i.getArray("Matrix");e.addOp(t,["Shading",r,a])}return}throw new FormatError(`Unknown PatternType: ${h}`)}}throw new FormatError(`Unknown PatternName: ${h}`)}_parseVisibilityExpression(e,t,a){if(++t>10){warn("Visibility expression is too deeply nested");return}const r=e.length,i=this.xref.fetchIfRef(e[0]);if(!(r<2)&&i instanceof Name){switch(i.name){case"And":case"Or":case"Not":a.push(i.name);break;default:warn(`Invalid operator ${i.name} in visibility expression`);return}for(let i=1;i0)return{type:"OCMD",expression:t}}const t=a.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const a of t)e.push(a.toString());else e.push(t.objId);return{type:r,ids:e,policy:a.get("P")instanceof Name?a.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:r,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:a,operatorList:r,initialState:i=null,fallbackFontDict:n=null}){a||=Dict.empty;i||=new EvalState;if(!r)throw new Error('getOperatorList: missing "operatorList" parameter');const s=this,o=this.xref;let c=!1;const l=new LocalImageCache,h=new LocalColorSpaceCache,u=new LocalGStateCache,d=new LocalTilingPatternCache,f=new Map,g=a.get("XObject")||Dict.empty,p=a.get("Pattern")||Dict.empty,m=new StateManager(i),b=new EvaluatorPreprocessor(e,o,m),y=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=b.savedStatesDepth;e0&&r.addOp(De,[t]);e=null;continue}}next(new Promise((function(e,i){if(!F)throw new FormatError("GState must be referred to by name.");const n=a.get("ExtGState");if(!(n instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const o=n.get(v);if(!(o instanceof Dict))throw new FormatError("GState should be a dictionary.");s.setGState({resources:a,gState:o,operatorList:r,cacheKey:v,task:t,stateManager:m,localGStateCache:u,localColorSpaceCache:h}).then(e,i)})).catch((function(e){if(!(e instanceof AbortException)){if(!s.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case Ee:case Pe:case Le:case je:case _e:case Ue:case Xe:s.buildPath(r,i,e,c);continue;case Et:case Pt:case Ut:case Xt:continue;case jt:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);r.addOp(jt,["OC",null]);continue}if("OC"===e[0].name){next(s.parseMarkedContentProps(e[1],a).then((e=>{r.addOp(jt,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!s.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);r.addOp(jt,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(S=0,k=e.length;S{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:i,stateManager:n=null,includeMarkedContent:s=!1,sink:o,seenStyles:c=new Set,viewBox:l,markedContentData:h=null,disableNormalization:u=!1,keepWhiteSpace:d=!1}){i||=Dict.empty;n||=new StateManager(new TextState);s&&(h||={level:0});const f={items:[],styles:Object.create(null)},g={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},p=[" "," "];let m=0;function saveLastChar(e){const t=(m+1)%2,a=" "!==p[m]&&" "===p[t];p[m]=e;m=t;return!d&&a}function shouldAddWhitepsace(){return!d&&" "!==p[m]&&" "===p[(m+1)%2]}function resetLastChars(){p[0]=p[1]=" ";m=0}const b=this,y=this.xref,w=[];let x=null;const S=new LocalImageCache,k=new LocalGStateCache,C=new EvaluatorPreprocessor(e,y,n);let v;function pushWhitespace({width:e=0,height:t=0,transform:a=g.prevTransform,fontName:r=g.fontName}){f.items.push({str:" ",dir:"ltr",width:e,height:t,transform:a,fontName:r,hasEOL:!1})}function getCurrentTextTransform(){const e=v.font,t=[v.fontSize*v.textHScale,0,0,v.fontSize,0,v.textRise];if(e.isType3Font&&(v.fontSize<=1||e.isCharBBox)&&!isArrayEqual(v.fontMatrix,r)){const a=e.bbox[3]-e.bbox[1];a>0&&(t[3]*=a*v.fontMatrix[3])}return Util.transform(v.ctm,Util.transform(v.textMatrix,t))}function ensureTextContentItem(){if(g.initialized)return g;const{font:e,loadedName:t}=v;if(!c.has(t)){c.add(t);f.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(b.options.fontExtraProperties&&e.systemFontInfo){const a=f.styles[t];a.fontSubstitution=e.systemFontInfo.css;a.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}g.fontName=t;const a=g.transform=getCurrentTextTransform();if(e.vertical){g.width=g.totalWidth=Math.hypot(a[0],a[1]);g.height=g.totalHeight=0;g.vertical=!0}else{g.width=g.totalWidth=0;g.height=g.totalHeight=Math.hypot(a[2],a[3]);g.vertical=!1}const r=Math.hypot(v.textLineMatrix[0],v.textLineMatrix[1]),i=Math.hypot(v.ctm[0],v.ctm[1]);g.textAdvanceScale=i*r;const{fontSize:n}=v;g.trackingSpaceMin=.102*n;g.notASpace=.03*n;g.negativeSpaceMax=-.2*n;g.spaceInFlowMin=.102*n;g.spaceInFlowMax=.6*n;g.hasEOL=!1;g.initialized=!0;return g}function updateAdvanceScale(){if(!g.initialized)return;const e=Math.hypot(v.textLineMatrix[0],v.textLineMatrix[1]),t=Math.hypot(v.ctm[0],v.ctm[1])*e;if(t!==g.textAdvanceScale){if(g.vertical){g.totalHeight+=g.height*g.textAdvanceScale;g.height=0}else{g.totalWidth+=g.width*g.textAdvanceScale;g.width=0}g.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");u||(t=function normalizeUnicode(e){if(!la){la=/([\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;ha=new Map([["ſt","ſt"]])}return e.replaceAll(la,((e,t,a)=>t?t.normalize("NFKC"):ha.get(a)))}(t));const a=bidi(t,-1,e.vertical);return{str:a.str,dir:a.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,a){const n=await b.loadFont(e,a,i);if(n.font.isType3Font)try{await n.loadType3Data(b,i,t)}catch{}v.loadedName=n.loadedName;v.font=n.font;v.fontMatrix=n.font.fontMatrix||r}function applyInverseRotation(e,t,a){const r=Math.hypot(a[0],a[1]);return[(a[0]*e+a[1]*t)/r,(a[2]*e+a[3]*t)/r]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let a=t[4],r=t[5];if(v.font?.vertical){if(al[2]||r+el[3])return!1}else if(a+el[2]||rl[3])return!1;if(!v.font||!g.prevTransform)return!0;let i=g.prevTransform[4],n=g.prevTransform[5];if(i===a&&n===r)return!0;let s=-1;t[0]&&0===t[1]&&0===t[2]?s=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(s=t[1]>0?90:270);switch(s){case 0:break;case 90:[a,r]=[r,a];[i,n]=[n,i];break;case 180:[a,r,i,n]=[-a,-r,-i,-n];break;case 270:[a,r]=[-r,-a];[i,n]=[-n,-i];break;default:[a,r]=applyInverseRotation(a,r,t);[i,n]=applyInverseRotation(i,n,g.prevTransform)}if(v.font.vertical){const e=(n-r)/g.textAdvanceScale,t=a-i,s=Math.sign(g.height);if(e.5*g.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>g.width){appendEOL();return!0}e<=s*g.notASpace&&resetLastChars();if(e<=s*g.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else g.height+=e;else if(!addFakeSpaces(e,g.prevTransform,s))if(0===g.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else g.height+=e;Math.abs(t)>.25*g.width&&flushTextContentItem();return!0}const o=(a-i)/g.textAdvanceScale,c=r-n,h=Math.sign(g.width);if(o.5*g.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(c)>g.height){appendEOL();return!0}o<=h*g.notASpace&&resetLastChars();if(o<=h*g.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else g.width+=o;else if(!addFakeSpaces(o,g.prevTransform,h))if(0===g.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else g.width+=o;Math.abs(c)>.25*g.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const a=v.font;if(!e){const e=v.charSpacing+t;e&&(a.vertical?v.translateTextMatrix(0,-e):v.translateTextMatrix(e*v.textHScale,0));d&&compareWithLastPosition(0);return}const r=a.charsToGlyphs(e),i=v.fontMatrix[0]*v.fontSize;for(let e=0,n=r.length;e0){const e=w.join("");w.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case dt:if(!n.state.font){b.ensureStateFont(n.state);continue}buildTextContentItem({chars:m[0],extraSpacing:0});break;case gt:if(!n.state.font){b.ensureStateFont(n.state);continue}v.carriageReturn();buildTextContentItem({chars:m[0],extraSpacing:0});break;case pt:if(!n.state.font){b.ensureStateFont(n.state);continue}v.wordSpacing=m[0];v.charSpacing=m[1];v.carriageReturn();buildTextContentItem({chars:m[2],extraSpacing:0});break;case Nt:flushTextContentItem();x||(x=i.get("XObject")||Dict.empty);var M=m[0]instanceof Name,D=m[0].name;if(M&&S.getByName(D))break;next(new Promise((function(e,a){if(!M)throw new FormatError("XObject must be referred to by name.");let r=x.getRaw(D);if(r instanceof Ref){if(S.getByRef(r)){e();return}if(b.globalImageCache.getData(r,b.pageIndex)){e();return}r=y.fetch(r)}if(!(r instanceof BaseStream))throw new FormatError("XObject should be a stream");const f=r.dict.get("Subtype");if(!(f instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==f.name){S.set(D,r.dict.objId,!0);e();return}const g=n.state.clone(),p=new StateManager(g),m=r.dict.getArray("Matrix");Array.isArray(m)&&6===m.length&&p.transform(m);enqueueChunk();const w={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;o.enqueue(e,t)},get desiredSize(){return o.desiredSize},get ready(){return o.ready}};b.getTextContent({stream:r,task:t,resources:r.dict.get("Resources")||i,stateManager:p,includeMarkedContent:s,sink:w,seenStyles:c,viewBox:l,markedContentData:h,disableNormalization:u,keepWhiteSpace:d}).then((function(){w.enqueueInvoked||S.set(D,r.dict.objId,!0);e()}),a)})).catch((function(e){if(!(e instanceof AbortException)){if(!b.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case De:M=m[0]instanceof Name;D=m[0].name;if(M&&k.getByName(D))break;next(new Promise((function(e,t){if(!M)throw new FormatError("GState must be referred to by name.");const a=i.get("ExtGState");if(!(a instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const r=a.get(D);if(!(r instanceof Dict))throw new FormatError("GState should be a dictionary.");const n=r.get("Font");if(n){flushTextContentItem();v.fontName=null;v.fontSize=n[1];handleSetFont(null,n[0]).then(e,t)}else{k.set(D,r.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!b.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Lt:flushTextContentItem();if(s){h.level++;f.items.push({type:"beginMarkedContent",tag:m[0]instanceof Name?m[0].name:null})}break;case jt:flushTextContentItem();if(s){h.level++;let e=null;m[1]instanceof Dict&&(e=m[1].get("MCID"));f.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${b.idFactory.getPageObjId()}_mc${e}`:null,tag:m[0]instanceof Name?m[0].name:null})}break;case _t:flushTextContentItem();if(s){if(0===h.level)break;h.level--;f.items.push({type:"endMarkedContent"})}break;case Re:!e||e.font===v.font&&e.fontSize===v.fontSize&&e.fontName===v.fontName||flushTextContentItem()}if(f.items.length>=o.desiredSize){p=!0;break}}if(p)next(xn);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const a=this.xref;let r;const i=this.readToUnicode(t.toUnicode);if(t.composite){const a=e.get("CIDSystemInfo");a instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(a.get("Registry")),ordering:stringToPDFString(a.get("Ordering")),supplement:a.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(r=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const n=[];let s,o=null;if(e.has("Encoding")){s=e.get("Encoding");if(s instanceof Dict){o=s.get("BaseEncoding");o=o instanceof Name?o.name:null;if(s.has("Differences")){const e=s.get("Differences");let t=0;for(const r of e){const e=a.fetchIfRef(r);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);n[t++]=e.name}}}}else if(s instanceof Name)o=s.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const c=!t.file||t.isInternalFont,l=Lr()[t.name];o&&c&&l&&(o=null);if(o)t.defaultEncoding=getEncoding(o);else{const e=!!(t.flags&Tr),a=!!(t.flags&Mr);s=lr;"TrueType"!==t.type||a||(s=hr);if(e||l){s=cr;c&&(/Symbol/i.test(t.name)?s=ur:/Dingbats/i.test(t.name)?s=dr:/Wingdings/i.test(t.name)&&(s=hr))}t.defaultEncoding=s}t.differences=n;t.baseEncodingName=o;t.hasEncoding=!!o||n.length>0;t.dict=e;t.toUnicode=await i;const h=await this.buildToUnicode(t);t.toUnicode=h;r&&(t.cidToGidMap=this.readCidToGidMap(r,h));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const a=[],r=e.defaultEncoding.slice(),i=e.baseEncodingName,n=e.differences;for(const e in n){const t=n[e];".notdef"!==t&&(r[e]=t)}const s=xr();for(const n in r){let o=r[n];if(""===o)continue;let c=s[o];if(void 0!==c){a[n]=String.fromCharCode(c);continue}let l=0;switch(o[0]){case"G":3===o.length&&(l=parseInt(o.substring(1),16));break;case"g":5===o.length&&(l=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const a=o.substring(1);if(t){l=parseInt(a,16);break}l=+a;if(Number.isNaN(l)&&Number.isInteger(parseInt(a,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":c=getUnicodeForGlyph(o,s);-1!==c&&(l=c);break;default:switch(o){case"f_h":case"f_t":case"T_h":a[n]=o.replaceAll("_","");continue}}if(l>0&&l<=1114111&&Number.isInteger(l)){if(i&&l===+n){const e=getEncoding(i);if(e&&(o=e[n])){a[n]=String.fromCharCode(s[o]);continue}}a[n]=String.fromCodePoint(l)}}return a}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:a}=e.cidSystemInfo,r=Name.get(`${t}-${a}-UCS2`),i=await CMapFactory.create({encoding:r,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),n=[],s=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const a=i.lookup(t);if(a){s.length=0;for(let e=0,t=a.length;e>1;(0!==i||t.has(n))&&(a[n]=i)}return a}extractWidths(e,t,a){const r=this.xref;let i=[],n=0;const s=[];let o,c,l,h,u,d,f,g;if(a.composite){n=e.has("DW")?e.get("DW"):1e3;g=e.get("W");if(g)for(c=0,l=g.length;c{const t=c.get(e),i=new OperatorList;return r.getOperatorList({stream:t,task:a,resources:l,operatorList:i}).then((()=>{i.fnArray[0]===bt&&this._removeType3ColorOperators(i,g);h[e]=i.getIR();for(const e of i.dependencies)s.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const a=new OperatorList;h[e]=a.getIR()}))}));this.type3Loaded=o.then((()=>{n.charProcOperatorList=h;if(this._bbox){n.isCharBBox=!0;n.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const a=Util.normalizeRect(e.argsArray[0].slice(2)),r=a[2]-a[0],i=a[3]-a[1],n=Math.hypot(r,i);if(0===r||0===i){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(n/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],a[0]);this._bbox[1]=Math.min(this._bbox[1],a[1]);this._bbox[2]=Math.max(this._bbox[2],a[2]);this._bbox[3]=Math.max(this._bbox[3],a[3])}let s=0,o=e.length;for(;s=Ee&&n<=Je;if(i.variableArgs)o>s&&info(`Command ${r}: expected [0, ${s}] args, but received ${o} args.`);else{if(o!==s){const e=this.nonProcessedArgs;for(;o>s;){e.push(t.shift());o--}for(;oEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(n,t);e.fn=n;e.args=t;return!0}if(a===da)return!1;if(null!==a){null===t&&(t=[]);t.push(a);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case Be:this.stateManager.save();break;case Re:this.stateManager.restore();break;case Ne:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:a,args:r}=e;switch(0|a){case nt:const[e,a]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof a&&a>0&&(t.fontSize=a);break;case It:ColorSpace.singletons.rgb.getRgbItem(r,0,t.fontColor,0);break;case vt:ColorSpace.singletons.gray.getRgbItem(r,0,t.fontColor,0);break;case Tt:ColorSpace.singletons.cmyk.getRgbItem(r,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,a){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=a;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},a=!1;const r=[];try{for(;;){e.args.length=0;if(a||!this.read(e))break;const{fn:i,args:n}=e;switch(0|i){case Be:r.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case Re:t=r.pop()||t;break;case ht:t.scaleFactor*=Math.hypot(n[0],n[1]);break;case nt:const[e,i]=n;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i*t.scaleFactor);break;case wt:t.fillColorSpace=ColorSpace.parse({cs:n[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case kt:t.fillColorSpace.getRgbItem(n,0,t.fontColor,0);break;case It:ColorSpace.singletons.rgb.getRgbItem(n,0,t.fontColor,0);break;case vt:ColorSpace.singletons.gray.getRgbItem(n,0,t.fontColor,0);break;case Tt:ColorSpace.singletons.cmyk.getRgbItem(n,0,t.fontColor,0);break;case dt:case ft:case gt:case pt:a=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const a=new OffscreenCanvas(1,1);this.ctxMeasure=a.getContext("2d");FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],a=[...this.widths.entries()].sort();let r=null,i=null;for(const[e,n]of a)if(r)if(e===r+i.length)i.push(n);else{t.push(r,i);r=e;i=[n]}else{r=e;i=[n]}r&&t.push(r,i);e.set("W",t);const n=new Dict(this.xref);n.set("Ordering","Identity");n.set("Registry","Adobe");n.set("Supplement",0);e.set("CIDSystemInfo",n);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const a of e.split(/\r\n?|\n/))for(const e of a.split("")){const a=e.charCodeAt(0);if(this.widths.has(a))continue;const r=t.measureText(e),i=Math.ceil(r.width);this.widths.set(a,i);this.firstChar=Math.min(a,this.firstChar);this.lastChar=Math.max(a,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,a){const[r,s,o,c]=e;let l=o-r,h=c-s;t%180!=0&&([l,h]=[h,l]);const u=i*a;return{coords:[0,h+n*a-u],bbox:[0,0,l,h],matrix:0!==t?getRotationMatrix(t,h,u):void 0}}createAppearance(e,t,a,r,s,o){const c=this._createContext(),l=[];let h=-1/0;for(const t of e.split(/\r\n?|\n/)){l.push(t);const e=c.measureText(t).width;h=Math.max(h,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let a=this.widths.get(e);if(void 0===a){const r=c.measureText(t);a=Math.ceil(r.width);this.widths.set(e,a);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}h*=r/1e3;const[u,d,f,g]=t;let p=f-u,m=g-d;a%180!=0&&([p,m]=[m,p]);let b=1;h>p&&(b=p/h);let y=1;const w=i*r,x=n*r,S=w*l.length;S>m&&(y=m/S);const k=r*Math.min(b,y),C=["q",`0 0 ${numberToString(p)} ${numberToString(m)} re W n`,"BT",`1 0 0 1 0 ${numberToString(m+x)} Tm 0 Tc ${getPdfColor(s,!0)}`,`/${this.fontName.name} ${numberToString(k)} Tf`],{resources:v}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){C.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.set("Type",Name.get("ExtGState"));e.set("R0",t);v.set("ExtGState",e)}const F=numberToString(w);for(const e of l)C.push(`0 -${F} Td <${stringToUTF16HexString(e)}> Tj`);C.push("ET","Q");const O=C.join("\n"),T=new Dict(this.xref);T.set("Subtype",Name.get("Form"));T.set("Type",Name.get("XObject"));T.set("BBox",[0,0,p,m]);T.set("Length",O.length);T.set("Resources",v);if(a){const e=getRotationMatrix(a,p,m);T.set("Matrix",e)}const M=new StringStream(O);M.dict=T;return M}}class NameOrNumberTree{constructor(e,t,a){this.constructor===NameOrNumberTree&&unreachable("Cannot initialize NameOrNumberTree.");this.root=e;this.xref=t;this._type=a}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,a=new RefSet;a.put(this.root);const r=[this.root];for(;r.length>0;){const i=t.fetchIfRef(r.shift());if(!(i instanceof Dict))continue;if(i.has("Kids")){const e=i.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(a.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);r.push(t);a.put(t)}continue}const n=i.get(this._type);if(Array.isArray(n))for(let a=0,r=n.length;a10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const i=a.get("Kids");if(!Array.isArray(i))return null;let n=0,s=i.length-1;for(;n<=s;){const r=n+s>>1,o=t.fetchIfRef(i[r]),c=o.get("Limits");if(et.fetchIfRef(c[1]))){a=o;break}n=r+1}}if(n>s)return null}const i=a.get(this._type);if(Array.isArray(i)){let a=0,r=i.length-2;for(;a<=r;){const n=a+r>>1,s=n+(1&n),o=t.fetchIfRef(i[s]);if(eo))return t.fetchIfRef(i[s+1]);a=s+2}}}return null}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){ui=Object.create(null)}();!function clearPrimitiveCaches(){fa=Object.create(null);ga=Object.create(null);pa=Object.create(null)}();!function clearUnicodeCaches(){vr.clear()}()}function pickPlatformItem(e){return e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null}class FileSpec{#A=!1;constructor(e,t,a=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));this.description=e.has("Desc")?stringToPDFString(e.get("Desc")):"";e.has("RF")&&warn("Related file specifications are not supported");a||(e.has("EF")?this.#A=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){if(!this._filename&&this.root){const e=pickPlatformItem(this.root)||"unnamed";this._filename=stringToPDFString(e).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/")}return this._filename}get content(){if(!this.#A)return null;!this.contentRef&&this.root&&(this.contentRef=pickPlatformItem(this.root.get("EF")));let e=null;if(this.contentRef){const t=this.xref.fetchIfRef(this.contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have a content");return e}get serializable(){return{filename:this.filename,content:this.content}}}const Sn=0,kn=-2,An=-3,Cn=-4,vn=-5,Fn=-6,In=-9;function isWhitespace(e,t){const a=e[t];return" "===a||"\n"===a||"\r"===a||"\t"===a}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const a=[];let r=t;function skipWs(){for(;r"!==e[r]&&"/"!==e[r];)++r;const i=e.substring(t,r);skipWs();for(;r"!==e[r]&&"/"!==e[r]&&"?"!==e[r];){skipWs();let t="",i="";for(;r"!==e[a]&&"?"!==e[a]&&"/"!==e[a];)++a;const r=e.substring(t,a);!function skipWs(){for(;a"!==e[a+1]);)++a;return{name:r,value:e.substring(i,a),parsed:a-t}}parseXml(e){let t=0;for(;t",a);if(t<0){this.onError(In);return}this.onEndElement(e.substring(a,t));a=t+1;break;case"?":++a;const r=this._parseProcessingInstruction(e,a);if("?>"!==e.substring(a+r.parsed,a+r.parsed+2)){this.onError(An);return}this.onPi(r.name,r.value);a+=r.parsed+2;break;case"!":if("--"===e.substring(a+1,a+3)){t=e.indexOf("--\x3e",a+3);if(t<0){this.onError(vn);return}this.onComment(e.substring(a+3,t));a=t+3}else if("[CDATA["===e.substring(a+1,a+8)){t=e.indexOf("]]>",a+8);if(t<0){this.onError(kn);return}this.onCdata(e.substring(a+8,t));a=t+3}else{if("DOCTYPE"!==e.substring(a+1,a+8)){this.onError(Fn);return}{const r=e.indexOf("[",a+8);let i=!1;t=e.indexOf(">",a+8);if(t<0){this.onError(Cn);return}if(r>0&&t>r){t=e.indexOf("]>",a+8);if(t<0){this.onError(Cn);return}i=!0}const n=e.substring(a+8,t+(i?1:0));this.onDoctype(n);a=t+(i?2:1)}}break;default:const i=this._parseContent(e,a);if(null===i){this.onError(Fn);return}let n=!1;if("/>"===e.substring(a+i.parsed,a+i.parsed+2))n=!0;else if(">"!==e.substring(a+i.parsed,a+i.parsed+1)){this.onError(In);return}this.onBeginElement(i.name,i.attributes,n);a+=i.parsed+(n?2:1)}}else{for(;a0}searchNode(e,t){if(t>=e.length)return this;const a=e[t];if(a.name.startsWith("#")&&t0){r.push([i,0]);i=i.childNodes[0]}else{if(0===r.length)return null;for(;0!==r.length;){const[e,t]=r.pop(),a=t+1;if(a");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=Sn;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=Sn;this.parseXml(e);if(this._errorCode!==Sn)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,a=e.length;t\\376\\377([^<]+)/g,(function(e,t){const a=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,a,r){return String.fromCharCode(64*t+8*a+1*r)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),r=[">"];for(let e=0,t=a.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?r.push(String.fromCharCode(t)):r.push("&#x"+(65536+t).toString(16).substring(1)+";")}return r.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,a=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,a.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}class DecryptStream extends DecodeStream{constructor(e,t,a){super(t);this.str=e;this.dict=e.dict;this.decrypt=a;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e||0===e.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const a=this.bufferLength,r=a+e.length;this.ensureBuffer(r).set(e,a);this.bufferLength=r}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),a=e.length;for(let e=0;e<256;++e)t[e]=e;for(let r=0,i=0;r<256;++r){const n=t[r];i=i+n+e[r%a]&255;t[r]=t[i];t[i]=n}this.s=t}encryptBlock(e){let t=this.a,a=this.b;const r=this.s,i=e.length,n=new Uint8Array(i);for(let s=0;s>5&255;h[u++]=i>>13&255;h[u++]=i>>21&255;h[u++]=i>>>29&255;h[u++]=0;h[u++]=0;h[u++]=0;const g=new Int32Array(16);for(u=0;u>>32-o)|0;i=n}n=n+i|0;s=s+l|0;o=o+f|0;c=c+p|0}return new Uint8Array([255&n,n>>8&255,n>>16&255,n>>>24&255,255&s,s>>8&255,s>>16&255,s>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255,255&c,c>>8&255,c>>16&255,c>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,a;if(32&e){a=this.low;t=this.high}else{t=this.low;a=this.high}e&=31;this.low=t>>>e|a<<32-e;this.high=a>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let a=(this.high>>>0)+(e.high>>>0);t>4294967295&&(a+=1);this.low=0|t;this.high=0|a}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const Tn=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,a){return e&t^~e&a}function maj(e,t,a){return e&t^e&a^t&a}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,a,r){let i=1779033703,n=3144134277,s=1013904242,o=2773480762,c=1359893119,l=2600822924,h=528734635,u=1541459225;const d=64*Math.ceil((r+9)/64),f=new Uint8Array(d);let g,p;for(g=0;g>>29&255;f[g++]=r>>21&255;f[g++]=r>>13&255;f[g++]=r>>5&255;f[g++]=r<<3&255;const b=new Uint32Array(64);for(g=0;g>>10)+b[p-7]+littleSigma(b[p-15])+b[p-16]|0;let t,a,r=i,d=n,m=s,w=o,x=c,S=l,k=h,C=u;for(p=0;p<64;++p){t=C+sigmaPrime(x)+ch(x,S,k)+e[p]+b[p];a=sigma(r)+maj(r,d,m);C=k;k=S;S=x;x=w+t|0;w=m;m=d;d=r;r=t+a|0}i=i+r|0;n=n+d|0;s=s+m|0;o=o+w|0;c=c+x|0;l=l+S|0;h=h+k|0;u=u+C|0}var y;return new Uint8Array([i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,l>>24&255,l>>16&255,l>>8&255,255&l,h>>24&255,h>>16&255,h>>8&255,255&h,u>>24&255,u>>16&255,u>>8&255,255&u])}}(),Mn=function calculateSHA512Closure(){function ch(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.not();i.and(r);e.xor(i)}function maj(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.and(r);e.xor(i);i.assign(a);i.and(r);e.xor(i)}function sigma(e,t,a){e.assign(t);e.rotateRight(28);a.assign(t);a.rotateRight(34);e.xor(a);a.assign(t);a.rotateRight(39);e.xor(a)}function sigmaPrime(e,t,a){e.assign(t);e.rotateRight(14);a.assign(t);a.rotateRight(18);e.xor(a);a.assign(t);a.rotateRight(41);e.xor(a)}function littleSigma(e,t,a){e.assign(t);e.rotateRight(1);a.assign(t);a.rotateRight(8);e.xor(a);a.assign(t);a.shiftRight(7);e.xor(a)}function littleSigmaPrime(e,t,a){e.assign(t);e.rotateRight(19);a.assign(t);a.rotateRight(61);e.xor(a);a.assign(t);a.shiftRight(6);e.xor(a)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,a,r,i=!1){let n,s,o,c,l,h,u,d;if(i){n=new Word64(3418070365,3238371032);s=new Word64(1654270250,914150663);o=new Word64(2438529370,812702999);c=new Word64(355462360,4144912697);l=new Word64(1731405415,4290775857);h=new Word64(2394180231,1750603025);u=new Word64(3675008525,1694076839);d=new Word64(1203062813,3204075428)}else{n=new Word64(1779033703,4089235720);s=new Word64(3144134277,2227873595);o=new Word64(1013904242,4271175723);c=new Word64(2773480762,1595750129);l=new Word64(1359893119,2917565137);h=new Word64(2600822924,725511199);u=new Word64(528734635,4215389547);d=new Word64(1541459225,327033209)}const f=128*Math.ceil((r+17)/128),g=new Uint8Array(f);let p,m;for(p=0;p>>29&255;g[p++]=r>>21&255;g[p++]=r>>13&255;g[p++]=r>>5&255;g[p++]=r<<3&255;const y=new Array(80);for(p=0;p<80;p++)y[p]=new Word64(0,0);let w=new Word64(0,0),x=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0),C=new Word64(0,0),v=new Word64(0,0),F=new Word64(0,0),O=new Word64(0,0);const T=new Word64(0,0),M=new Word64(0,0),D=new Word64(0,0),R=new Word64(0,0);let N,E;for(p=0;p=1;--e){a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e)n[e]=this._inv_s[n[e]];for(let a=0,r=16*e;a<16;++a,++r)n[a]^=t[r];for(let e=0;e<16;e+=4){const t=this._mix[n[e]],r=this._mix[n[e+1]],i=this._mix[n[e+2]],s=this._mix[n[e+3]];a=t^r>>>8^r<<24^i>>>16^i<<16^s>>>24^s<<8;n[e]=a>>>24&255;n[e+1]=a>>16&255;n[e+2]=a>>8&255;n[e+3]=255&a}}a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e){n[e]=this._inv_s[n[e]];n[e]^=t[e]}return n}_encrypt(e,t){const a=this._s;let r,i,n;const s=new Uint8Array(16);s.set(e);for(let e=0;e<16;++e)s[e]^=t[e];for(let e=1;e=r;--a)if(e[a]!==t){t=0;break}o-=t;n[n.length-1]=e.subarray(0,16-t)}}const c=new Uint8Array(o);for(let e=0,t=0,a=n.length;e=256&&(o=255&(27^o))}for(let t=0;t<4;++t){a[e]=r^=a[e-32];e++;a[e]=i^=a[e-32];e++;a[e]=n^=a[e-32];e++;a[e]=s^=a[e-32];e++}}return a}}class PDF17{checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(Tn(i,0,i.length),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(Tn(r,0,r.length),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=Tn(i,0,i.length);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=Tn(r,0,r.length);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,a){let r=Tn(t,0,t.length).subarray(0,32),i=[0],n=0;for(;n<64||i.at(-1)>n-32;){const t=e.length+r.length+a.length,l=new Uint8Array(t);let h=0;l.set(e,h);h+=e.length;l.set(r,h);h+=r.length;l.set(a,h);const u=new Uint8Array(64*t);for(let e=0,a=0;e<64;e++,a+=t)u.set(l,a);i=new AES128Cipher(r.subarray(0,16)).encrypt(u,r.subarray(16,32));const d=i.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===d?r=Tn(i,0,i.length):1===d?r=(s=i,o=0,c=i.length,Mn(s,o,c,!0)):2===d&&(r=Mn(i,0,i.length));n++}var s,o,c;return r.subarray(0,32)}checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(this._hash(e,i,a),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(this._hash(e,r,[]),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=this._hash(e,i,a);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=this._hash(e,r,[]);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const a=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return a.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let a=stringToBytes(e);a=t.decryptBlock(a,!0);return bytesToString(a)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const a=16-e.length%16;e+=String.fromCharCode(a).repeat(a);const r=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(r);else for(let e=0;e<16;e++)r[e]=Math.floor(256*Math.random());let i=stringToBytes(e);i=t.encrypt(i,r);const n=new Uint8Array(16+i.length);n.set(r);n.set(i,16);return bytesToString(n)}let a=stringToBytes(e);a=t.encrypt(a);return bytesToString(a)}}class CipherTransformFactory{static#C=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#v(e,t,a,r,i,n,s,o,c,l,h,u){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const d=6===e?new PDF20:new PDF17;return d.checkUserPassword(t,o,s)?d.getUserKey(t,c,h):t.length&&d.checkOwnerPassword(t,r,n,a)?d.getOwnerKey(t,i,n,l):null}#F(e,t,a,r,i,n,s,o){const c=40+a.length+e.length,l=new Uint8Array(c);let h,u,d=0;if(t){u=Math.min(32,t.length);for(;d>8&255;l[d++]=i>>16&255;l[d++]=i>>>24&255;for(h=0,u=e.length;h=4&&!o){l[d++]=255;l[d++]=255;l[d++]=255;l[d++]=255}let f=On(l,0,d);const g=s>>3;if(n>=3)for(h=0;h<50;++h)f=On(f,0,g);const p=f.subarray(0,g);let m,b;if(n>=3){for(d=0;d<32;++d)l[d]=CipherTransformFactory.#C[d];for(h=0,u=e.length;h>3;if(a>=3)for(o=0;o<50;++o)c=On(c,0,c.length);let h,u;if(a>=3){u=t;const e=new Uint8Array(l);for(o=19;o>=0;o--){for(let t=0;t>8&255;i[s++]=e>>16&255;i[s++]=255&t;i[s++]=t>>8&255;if(r){i[s++]=115;i[s++]=65;i[s++]=108;i[s++]=84}return On(i,0,s).subarray(0,Math.min(a.length+5,16))}#T(e,t,a,r,i){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const n=this,s=e.get(t.name),o=s?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(n.#O(a,r,i,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(n.#O(a,r,i,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(i)};throw new FormatError("Unknown crypto method")}constructor(e,t,a){const r=e.get("Filter");if(!isName(r,"Standard"))throw new FormatError("unknown encryption method");this.filterName=r.name;this.dict=e;const i=e.get("V");if(!Number.isInteger(i)||1!==i&&2!==i&&4!==i&&5!==i)throw new FormatError("unsupported encryption algorithm");this.algorithm=i;let n=e.get("Length");if(!n)if(i<=3)n=40;else{const t=e.get("CF"),a=e.get("StmF");if(t instanceof Dict&&a instanceof Name){t.suppressEncryption=!0;const e=t.get(a.name);n=e?.get("Length")||128;n<40&&(n<<=3)}}if(!Number.isInteger(n)||n<40||n%8!=0)throw new FormatError("invalid key length");const s=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),c=s.subarray(0,32),l=o.subarray(0,32),h=e.get("P"),u=e.get("R"),d=(4===i||5===i)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=d;const f=stringToBytes(t);let g,p;if(a){if(6===u)try{a=utf8StringToString(a)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}g=stringToBytes(a)}if(5!==i)p=this.#F(f,g,c,l,h,u,n,d);else{const t=s.subarray(32,40),a=s.subarray(40,48),r=o.subarray(0,48),i=o.subarray(32,40),n=o.subarray(40,48),h=stringToBytes(e.get("OE")),d=stringToBytes(e.get("UE")),f=stringToBytes(e.get("Perms"));p=this.#v(u,g,c,t,a,r,l,i,n,h,d,f)}if(!p&&!a)throw new PasswordException("No password given",ra);if(!p&&a){const e=this.#I(g,c,u,n);p=this.#F(f,e,c,l,h,u,n,d)}if(!p)throw new PasswordException("Incorrect Password",ia);this.encryptionKey=p;if(i>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#T(this.cf,this.strf,e,t,this.encryptionKey),this.#T(this.cf,this.stmf,e,t,this.encryptionKey));const a=this.#O(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(a)};return new CipherTransform(cipherConstructor,cipherConstructor)}}async function writeObject(e,t,a,{encrypt:r=null}){const i=r?.createCipherTransform(e.num,e.gen);a.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,a,i):t instanceof BaseStream?await writeStream(t,a,i):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,a,i);a.push("\nendobj\n")}async function writeDict(e,t,a){t.push("<<");for(const r of e.getKeys()){t.push(` /${escapePDFName(r)} `);await writeValue(e.getRaw(r),t,a)}t.push(">>")}async function writeStream(e,t,a){let r=e.getBytes();const{dict:i}=e,[n,s]=await Promise.all([i.getAsync("Filter"),i.getAsync("DecodeParms")]),o=isName(Array.isArray(n)?await i.xref.fetchIfRefAsync(n[0]):n,"FlateDecode");if("undefined"!=typeof CompressionStream&&(r.length>=256||o))try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();t.write(r);t.close();const a=await new Response(e.readable).arrayBuffer();r=new Uint8Array(a);let c,l;if(n){if(!o){c=Array.isArray(n)?[Name.get("FlateDecode"),...n]:[Name.get("FlateDecode"),n];s&&(l=Array.isArray(s)?[null,...s]:[null,s])}}else c=Name.get("FlateDecode");c&&i.set("Filter",c);l&&i.set("DecodeParms",l)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let c=bytesToString(r);a&&(c=a.encryptString(c));i.set("Length",c.length);await writeDict(i,t,a);t.push(" stream\n",c,"\nendstream")}async function writeArray(e,t,a){t.push("[");let r=!0;for(const i of e){r?r=!1:t.push(" ");await writeValue(i,t,a)}t.push("]")}async function writeValue(e,t,a){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,a);else if("string"==typeof e){a&&(e=a.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,a):e instanceof BaseStream?await writeStream(e,t,a):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,a,r){for(let i=t+a-1;i>a-1;i--){r[i]=255&e;e>>=8}return a+t}function writeString(e,t,a){for(let r=0,i=e.length;r1&&(n=a.documentElement.searchNode([i.at(-1)],0));n?n.childNodes=Array.isArray(r)?r.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",r)]:warn(`Node not found for path: ${t}`)}const r=[];a.documentElement.dump(r);return r.join("")}(r.fetchIfRef(t).getString(),a)}const i=r.encrypt;if(i){e=i.createCipherTransform(t.num,t.gen).encryptString(e)}const n=`${t.num} ${t.gen} obj\n<< /Type /EmbeddedFile /Length ${e.length}>>\nstream\n`+e+"\nendstream\nendobj\n";a.push({ref:t,data:n})}function getIndexes(e){const t=[];for(const{ref:a}of e)a.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(a.num,1);return t}function computeIDs(e,t,a){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const r=function computeMD5(e,t){const a=Math.floor(Date.now()/1e3),r=t.filename||"",i=[a.toString(),r,e.toString()];let n=i.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){i.push(e);n+=e.length}const s=new Uint8Array(n);let o=0;for(const e of i){writeString(e,o,s);o+=e.length}return bytesToString(On(s))}(e,t);a.set("ID",[t.fileIds[0],r])}}async function incrementalUpdate({originalData:e,xrefInfo:t,newRefs:a,xref:r=null,hasXfa:i=!1,xfaDatasetsRef:n=null,hasXfaDatasetsEntry:s=!1,needAppearances:o,acroFormRef:c=null,acroForm:l=null,xfaData:h=null,useXrefStream:u=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:a,hasXfa:r,hasXfaDatasetsEntry:i,xfaDatasetsRef:n,needAppearances:s,newRefs:o}){!r||i||n||warn("XFA - Cannot save it");if(!s&&(!r||!n||i))return;const c=t.clone();if(r&&!i){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,n);c.set("XFA",e)}s&&c.set("NeedAppearances",!0);const l=[];await writeObject(a,c,l,e);o.push({ref:a,data:l.join("")})}({xref:r,acroForm:l,acroFormRef:c,hasXfa:i,hasXfaDatasetsEntry:s,xfaDatasetsRef:n,needAppearances:o,newRefs:a});i&&updateXFA({xfaData:h,xfaDatasetsRef:n,newRefs:a,xref:r});let d,f;const g=e.at(-1);if(10===g||13===g){d=[];f=e.length}else{d=["\n"];f=e.length+1}const p=function getTrailerDict(e,t,a){const r=new Dict(null);r.set("Prev",e.startXRef);const i=e.newRef;if(a){t.push({ref:i,data:""});r.set("Size",i.num+1);r.set("Type",Name.get("XRef"))}else r.set("Size",i.num);null!==e.rootRef&&r.set("Root",e.rootRef);null!==e.infoRef&&r.set("Info",e.infoRef);null!==e.encryptRef&&r.set("Encrypt",e.encryptRef);return r}(t,a,u);a=a.sort(((e,t)=>e.ref.num-t.ref.num));for(const{data:e}of a)d.push(e);await(u?async function getXRefStreamTable(e,t,a,r,i){const n=[];let s=0,o=0;for(const{ref:e,data:r}of a){s=Math.max(s,t);const a=Math.min(e.gen,65535);o=Math.max(o,a);n.push([1,t,a]);t+=r.length}r.set("Index",getIndexes(a));const c=[1,getSizeInBytes(s),getSizeInBytes(o)];r.set("W",c);computeIDs(t,e,r);const l=c.reduce(((e,t)=>e+t),0),h=new Uint8Array(l*n.length),u=new Stream(h);u.dict=r;let d=0;for(const[e,t,a]of n){d=writeInt(e,c[0],d,h);d=writeInt(t,c[1],d,h);d=writeInt(a,c[2],d,h)}await writeObject(e.newRef,u,i,{});i.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,f,a,p,d):async function getXRefTable(e,t,a,r,i){i.push("xref\n");const n=getIndexes(a);let s=0;for(const{ref:e,data:r}of a){if(e.num===n[s]){i.push(`${n[s]} ${n[s+1]}\n`);s+=2}i.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=r.length}computeIDs(t,e,r);i.push("trailer\n");await writeDict(r,i);i.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,f,a,p,d));const m=d.reduce(((e,t)=>e+t.length),e.length),b=new Uint8Array(m);b.set(e);let y=e.length;for(const e of d){writeString(e,y,b);y+=e.length}return b}const Dn=1,Bn=2,Rn=3,Nn=4,En=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#M(e,t,a){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let r=this.structParentIds.get(e);if(!r){r=[];this.structParentIds.put(e,r)}r.push([t,a])}addAnnotationIdToPage(e,t){this.#M(e,t,Nn)}readRoleMap(){const e=this.dict.get("RoleMap");e instanceof Dict&&e.forEach(((e,t)=>{t instanceof Name&&this.roleMap.set(e,t.name)}))}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:a}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let r=0,i=!0;for(const[e,n]of a){const{ref:a}=await t.getPage(e);if(!(a instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);i=!0;break}for(const e of n)if(e.accessibilityData?.type){e.parentTreeId=r++;i=!1}}if(i){for(const e of a.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:a,pdfManager:r,newRefs:i}){const n=r.catalog.cloneDict(),s=t.getNewTemporaryRef();n.set("StructTreeRoot",s);const o=[];await writeObject(a,n,o,t);i.push({ref:a,data:o.join("")});const c=new Dict(t);c.set("Type",Name.get("StructTreeRoot"));const l=t.getNewTemporaryRef();c.set("ParentTree",l);const h=[];c.set("K",h);const u=new Dict(t),d=[];u.set("Nums",d);const f=await this.#D({newAnnotationsByPage:e,structTreeRootRef:s,kids:h,nums:d,xref:t,pdfManager:r,newRefs:i,buffer:o});c.set("ParentTreeNextKey",f);o.length=0;await writeObject(l,u,o,t);i.push({ref:l,data:o.join("")});o.length=0;await writeObject(s,c,o,t);i.push({ref:s,data:o.join("")})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:a}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let r=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(r)||r<0){warn("Cannot update the struct tree: invalid next key.");return!1}const i=this.dict.get("ParentTree");if(!(i instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const n=i.get("Nums");if(!Array.isArray(n)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const s=new NumberTree(i,t);for(const t of a.keys()){const{pageDict:a}=await e.getPage(t);if(!a.has("StructParents"))continue;const r=a.get("StructParents");if(!Number.isInteger(r)||!Array.isArray(s.get(r))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let o=!0;for(const[t,i]of a){const{pageDict:a}=await e.getPage(t);StructTreeRoot.#B({elements:i,xref:this.dict.xref,pageDict:a,numberTree:s});for(const e of i)if(e.accessibilityData?.type){e.parentTreeId=r++;o=!1}}if(o){for(const e of a.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,newRefs:a}){const r=this.dict.xref,i=this.dict.clone(),n=this.ref;let s,o=i.getRaw("ParentTree");if(o instanceof Ref)s=r.fetch(o);else{s=o;o=r.getNewTemporaryRef();i.set("ParentTree",o)}s=s.clone();let c=s.getRaw("Nums"),l=null;if(c instanceof Ref){l=c;c=r.fetch(l)}c=c.slice();l||s.set("Nums",c);let h=i.getRaw("K"),u=null;if(h instanceof Ref){u=h;h=r.fetch(u)}else{u=r.getNewTemporaryRef();i.set("K",u)}h=Array.isArray(h)?h.slice():[h];const d=[],f=await StructTreeRoot.#D({newAnnotationsByPage:e,structTreeRootRef:n,kids:h,nums:c,xref:r,pdfManager:t,newRefs:a,buffer:d});i.set("ParentTreeNextKey",f);d.length=0;await writeObject(u,h,d,r);a.push({ref:u,data:d.join("")});if(l){d.length=0;await writeObject(l,c,d,r);a.push({ref:l,data:d.join("")})}d.length=0;await writeObject(o,s,d,r);a.push({ref:o,data:d.join("")});d.length=0;await writeObject(n,i,d,r);a.push({ref:n,data:d.join("")})}static async#D({newAnnotationsByPage:e,structTreeRootRef:t,kids:a,nums:r,xref:i,pdfManager:n,newRefs:s,buffer:o}){const c=Name.get("OBJR");let l=-1/0;for(const[h,u]of e){const{ref:e}=await n.getPage(h),d=e instanceof Ref;for(const{accessibilityData:n,ref:h,parentTreeId:f,structTreeParent:g}of u){if(!n?.type)continue;const{type:u,title:p,lang:m,alt:b,expanded:y,actualText:w}=n;l=Math.max(l,f);const x=i.getNewTemporaryRef(),S=new Dict(i);S.set("S",Name.get(u));p&&S.set("T",p);m&&S.set("Lang",m);b&&S.set("Alt",b);y&&S.set("E",y);w&&S.set("ActualText",w);g?await this.#R({structTreeParent:g,tagDict:S,newTagRef:x,fallbackRef:t,xref:i,newRefs:s,buffer:o}):S.set("P",t);const k=new Dict(i);S.set("K",k);k.set("Type",c);d&&k.set("Pg",e);k.set("Obj",h);o.length=0;await writeObject(x,S,o,i);s.push({ref:x,data:o.join("")});r.push(f,x);a.push(x)}}return l+1}static#B({elements:e,xref:t,pageDict:a,numberTree:r}){const i=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);i.set(e,t)}const n=a.get("StructParents");if(!Number.isInteger(n))return;const s=r.get(n),updateElement=(e,a,r)=>{const n=i.get(e);if(n){const e=a.getRaw("P"),i=t.fetchIfRef(e);e instanceof Ref&&i instanceof Dict&&(n.structTreeParent={ref:r,dict:a});return!0}return!1};for(const e of s){if(!(e instanceof Ref))continue;const a=t.fetch(e),r=a.get("K");if(Number.isInteger(r))updateElement(r,a,e);else if(Array.isArray(r))for(let i of r){i=t.fetchIfRef(i);if(Number.isInteger(i)&&updateElement(i,a,e))break}}}static async#R({structTreeParent:{ref:e,dict:t},tagDict:a,newTagRef:r,fallbackRef:i,xref:n,newRefs:s,buffer:o}){const c=t.getRaw("P");let l=n.fetchIfRef(c);a.set("P",c);let h,u=!1,d=l.getRaw("K");if(d instanceof Ref)h=n.fetch(d);else{h=d;d=n.getNewTemporaryRef();l=l.clone();l.set("K",d);u=!0}if(Array.isArray(h)){const t=h.indexOf(e);if(!(t>=0)){warn("Cannot update the struct tree: parent kid not found.");a.set("P",i);return}h=h.slice();h.splice(t+1,0,r)}else if(h instanceof Dict){h=[d,r];d=n.getNewTemporaryRef();l.set("K",d);u=!0}o.length=0;await writeObject(d,h,o,n);s.push({ref:d,data:o.join("")});if(u){o.length=0;await writeObject(c,l,o,n);s.push({ref:c,data:o.join("")})}}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:a}=this.tree;return a.roleMap.has(t)?a.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const a=this.dict.get("K");if(Array.isArray(a))for(const t of a){const a=this.parseKid(e,t);a&&this.kids.push(a)}else{const t=this.parseKid(e,a);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Dn,mcid:t,pageObjId:e});let a=null;t instanceof Ref?a=this.dict.xref.fetch(t):t instanceof Dict&&(a=t);if(!a)return null;const r=a.getRaw("Pg");r instanceof Ref&&(e=r.toString());const i=a.get("Type")instanceof Name?a.get("Type").name:null;if("MCR"===i){if(this.tree.pageDict.objId!==e)return null;const t=a.getRaw("Stm");return new StructElement({type:Bn,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:a.get("MCID")})}if("OBJR"===i){if(this.tree.pageDict.objId!==e)return null;const t=a.getRaw("Obj");return new StructElement({type:Rn,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:En,dict:a})}}class StructElement{constructor({type:e,dict:t=null,mcid:a=null,pageObjId:r=null,refObjId:i=null}){this.type=e;this.dict=t;this.mcid=a;this.pageObjId=r;this.refObjId=i;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}parse(e){if(!this.root||!this.rootDict)return;const t=this.rootDict.get("ParentTree");if(!t)return;const a=this.pageDict.get("StructParents"),r=e instanceof Ref&&this.root.structParentIds?.get(e);if(!Number.isInteger(a)&&!r)return;const i=new Map,n=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(a)){const e=n.get(a);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),i)}if(r)for(const[e,t]of r){const a=n.get(e);if(a){const e=this.addNode(this.rootDict.xref.fetchIfRef(a),i);1===e?.kids?.length&&e.kids[0].type===Rn&&(e.kids[0].type=t)}}}addNode(e,t,a=0){if(a>40){warn("StructTree MAX_DEPTH reached.");return null}if(t.has(e))return t.get(e);const r=new StructElementNode(this,e);t.set(e,r);const i=e.get("P");if(!i||isName(i.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,r)||t.delete(e);return r}const n=this.addNode(i,t,a+1);if(!n)return r;let s=!1;for(const t of n.kids)if(t.type===En&&t.dict===e){t.parentNode=r;s=!0}s||t.delete(e);return r}addTopLevelNode(e,t){const a=this.rootDict.get("K");if(!a)return!1;if(a instanceof Dict){if(a.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(a))return!0;let r=!1;for(let i=0;i40){warn("StructTree too deep to be fully serialized.");return}const r=Object.create(null);r.role=e.role;r.children=[];t.children.push(r);const i=e.dict.get("Alt");"string"==typeof i&&(r.alt=stringToPDFString(i));const n=e.dict.get("Lang");"string"==typeof n&&(r.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===En?t.parentNode:null;e?nodeToSerializable(e,r,a+1):t.type===Dn||t.type===Bn?r.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Rn?r.children.push({type:"object",id:t.refObjId}):t.type===Nn&&r.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function fetchDestination(e){e instanceof Dict&&(e=e.get("D"));return Array.isArray(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(Array.isArray(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(ba.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang","string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const a=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(a instanceof BaseStream&&a.dict instanceof Dict){const e=a.dict.get("Type"),r=a.dict.get("Subtype");if(isName(e,"Metadata")&&isName(r,"XML")){const e=stringToUTF8String(a.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const a in t){const r=e.get(a);"boolean"==typeof r&&(t[a]=r)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const a=new StructTreeRoot(t,e);a.init();return a}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},a=[{obj:e,parent:t}],r=new RefSet;r.put(e);const i=this.xref,n=new Uint8ClampedArray(3);for(;a.length>0;){const t=a.shift(),s=i.fetchIfRef(t.obj);if(null===s)continue;s.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:s,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const c=s.get("Title"),l=s.get("F")||0,h=s.getArray("C"),u=s.get("Count");let d=n;!Array.isArray(h)||3!==h.length||0===h[0]&&0===h[1]&&0===h[2]||(d=ColorSpace.singletons.rgb.getRgb(h,0));const f={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof c?stringToPDFString(c):"",color:d,count:Number.isInteger(u)?u:void 0,bold:!!(2&l),italic:!!(1&l),items:[]};t.parent.items.push(f);e=s.getRaw("First");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:f});r.put(e)}e=s.getRaw("Next");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:t.parent});r.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const a=[];for(const e in w){const r=w[e];t&r&&a.push(r)}return a}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const a=t.get("D");if(!a)return shadow(this,"optionalContentConfig",null);const r=t.get("OCGs");if(!Array.isArray(r))return shadow(this,"optionalContentConfig",null);const i=[],n=new RefSet;for(const e of r)if(e instanceof Ref&&!n.has(e)){n.put(e);i.push(this.#N(e))}e=this.#E(a,n);e.groups=i}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#N(e){const t=this.xref.fetch(e),a={id:e.toString(),name:null,intent:null,usage:{print:null,view:null}},r=t.get("Name");"string"==typeof r&&(a.name=stringToPDFString(r));let i=t.getArray("Intent");Array.isArray(i)||(i=[i]);i.every((e=>e instanceof Name))&&(a.intent=i.map((e=>e.name)));const n=t.get("Usage");if(!(n instanceof Dict))return a;const s=a.usage,o=n.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.print={printState:e.name}}}const c=n.get("View");if(c instanceof Dict){const e=c.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.view={viewState:e.name}}}return a}#E(e,t){function parseOnOff(e){const a=[];if(Array.isArray(e))for(const r of e)r instanceof Ref&&t.has(r)&&a.push(r.toString());return a}function parseOrder(e,a=0){if(!Array.isArray(e))return null;const i=[];for(const n of e){if(n instanceof Ref&&t.has(n)){r.put(n);i.push(n.toString());continue}const e=parseNestedOrder(n,a);e&&i.push(e)}if(a>0)return i;const n=[];for(const e of t)r.has(e)||n.push(e.toString());n.length&&i.push({name:null,order:n});return i}function parseNestedOrder(e,t){if(++t>i){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const r=a.fetchIfRef(e);if(!Array.isArray(r))return null;const n=a.fetchIfRef(r[0]);if("string"!=typeof n)return null;const s=parseOrder(r.slice(1),t);return s&&s.length?{name:stringToPDFString(n),order:s}:null}const a=this.xref,r=new RefSet,i=10;return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:null}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[a,r]of e.getAll()){const e=fetchDestination(r);e&&(t[stringToPDFString(a)]=e)}else e instanceof Dict&&e.forEach((function(e,a){const r=fetchDestination(a);r&&(t[e]=r)}));return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const a=fetchDestination(t.get(e));if(a)return a;const r=this.destinations[e];if(r){warn(`Found "${e}" at an incorrect position in the NameTree.`);return r}}else if(t instanceof Dict){const a=fetchDestination(t.get(e));if(a)return a}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let a=null,r="";const i=new NumberTree(e,this.xref).getAll();let n="",s=1;for(let e=0,o=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");s=e}else s=1}switch(a){case"D":n=s;break;case"R":case"r":n=toRomanNumerals(s,"r"===a);break;case"A":case"a":const e=26,t="a"===a?97:65,r=s-1;n=String.fromCharCode(t+r%e).repeat(Math.floor(r/e)+1);break;default:if(a)throw new FormatError(`Invalid style "${a}" in PageLabel dictionary.`);n=""}t[e]=r+n;s++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const a of e.getKeys()){const r=e.get(a);let i;switch(a){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof r&&(i=r);break;case"NonFullScreenPageMode":if(r instanceof Name)switch(r.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":i=r.name;break;default:i="UseNone"}break;case"Direction":if(r instanceof Name)switch(r.name){case"L2R":case"R2L":i=r.name;break;default:i="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(r instanceof Name)switch(r.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":i=r.name;break;default:i="CropBox"}break;case"PrintScaling":if(r instanceof Name)switch(r.name){case"None":case"AppDefault":i=r.name;break;default:i="AppDefault"}break;case"Duplex":if(r instanceof Name)switch(r.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":i=r.name;break;default:i="None"}break;case"PrintPageRange":if(Array.isArray(r)&&r.length%2==0){r.every(((e,t,a)=>Number.isInteger(e)&&e>0&&(0===t||e>=a[t-1])&&e<=this.numPages))&&(i=r)}break;case"NumCopies":Number.isInteger(r)&&r>0&&(i=r);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${a}.`);continue}if(void 0!==i){t||(t=Object.create(null));t[a]=i}else warn(`Bad value, for key "${a}", in ViewerPreferences: ${r}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const a=new Dict(this.xref);a.set("A",e);const r={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:a,resultObj:r});Array.isArray(r.dest)?t.dest=r.dest:r.action&&(t.action=r.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const a=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,r]of a.getAll()){const a=new FileSpec(r,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=a.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const a=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,r]of a.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),r)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,a){if(!(a instanceof Dict))return;if(!isName(a.get("S"),"JavaScript"))return;let r=a.get("JS");if(r instanceof BaseStream)r=r.getString();else if("string"!=typeof r)return;r=stringToPDFString(r).replaceAll("\0","");r&&(t||=new Map).set(e,r)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,a]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),a)}const a=this._catDict.get("OpenAction");a&&appendIfJavaScriptDict("OpenAction",a);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,we);if(e){t||=Object.create(null);for(const[a,r]of e)a in t?t[a].push(r):t[a]=[r]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const a=await Promise.all(this.fontCache);for(const r of a)if(r.loadedName===e){r.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],a=new RefSet,r=this._catDict.getRaw("Pages");r instanceof Ref&&a.put(r);const i=this.xref,n=this.pageKidsCountCache,s=this.pageIndexCache;let o=0;for(;t.length;){const r=t.pop();if(r instanceof Ref){const c=n.get(r);if(c>=0&&o+c<=e){o+=c;continue}if(a.has(r))throw new FormatError("Pages tree contains circular reference.");a.put(r);const l=await i.fetchAsync(r);if(l instanceof Dict){let t=l.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!l.has("Kids")){n.has(r)||n.put(r,1);s.has(r)||s.put(r,o);if(o===e)return[l,r];o++;continue}}t.push(l);continue}if(!(r instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=r;let l=r.getRaw("Count");l instanceof Ref&&(l=await i.fetchAsync(l));if(Number.isInteger(l)&&l>=0){c&&!n.has(c)&&n.put(c,l);if(o+l<=e){o+=l;continue}}let h=r.getRaw("Kids");h instanceof Ref&&(h=await i.fetchAsync(h));if(!Array.isArray(h)){let t=r.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!r.has("Kids")){if(o===e)return[r,null];o++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--)t.push(h[e])}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,a=[{currentNode:this.toplevelPagesDict,posInKids:0}],r=new RefSet,i=this._catDict.getRaw("Pages");i instanceof Ref&&r.put(i);const n=new Map,s=this.xref,o=this.pageIndexCache;let c=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,c);n.set(c++,[e,t])}function addPageError(a){if(a instanceof XRefEntryException&&!e)throw a;if(e&&t&&0===c){warn(`getAllPageDicts - Skipping invalid first page: "${a}".`);a=Dict.empty}n.set(c++,[a,null])}for(;a.length>0;){const e=a.at(-1),{currentNode:t,posInKids:i}=e;let n=t.getRaw("Kids");if(n instanceof Ref)try{n=await s.fetchAsync(n)}catch(e){addPageError(e);break}if(!Array.isArray(n)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(i>=n.length){a.pop();continue}const o=n[i];let c;if(o instanceof Ref){if(r.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}r.put(o);try{c=await s.fetchAsync(o)}catch(e){addPageError(e);break}}else c=o;if(!(c instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let l=c.getRaw("Type");if(l instanceof Ref)try{l=await s.fetchAsync(l)}catch(e){addPageError(e);break}isName(l,"Page")||!c.has("Kids")?addPageDict(c,o instanceof Ref?o:null):a.push({currentNode:c,posInKids:0});e.posInKids++}return n}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const a=this.xref;let r=0;const next=t=>function pagesBeforeRef(t){let r,i=0;return a.fetchAsync(t).then((function(a){if(isRefsEqual(t,e)&&!isDict(a,"Page")&&!(a instanceof Dict&&!a.has("Type")&&a.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!a)return null;if(!(a instanceof Dict))throw new FormatError("Node must be a dictionary.");r=a.getRaw("Parent");return a.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const n=[];let s=!1;for(const r of e){if(!(r instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(r,t)){s=!0;break}n.push(a.fetchAsync(r).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?i+=e.get("Count"):i++})))}if(!s)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(n).then((function(){return[i,r]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,r);return r}const[a,i]=t;r+=a;return next(i)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:a=null,docAttachments:r=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let i,n,s=e.get("A");if(!(s instanceof Dict))if(e.has("Dest"))s=e.get("Dest");else{s=e.get("AA");s instanceof Dict&&(s.has("D")?s=s.get("D"):s.has("U")&&(s=s.get("U")))}if(s instanceof Dict){const e=s.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const a=e.name;switch(a){case"ResetForm":const e=s.get("Flags"),o=0==(1&("number"==typeof e?e:0)),c=[],l=[];for(const e of s.get("Fields")||[])e instanceof Ref?l.push(e.toString()):"string"==typeof e&&c.push(stringToPDFString(e));t.resetForm={fields:c,refs:l,include:o};break;case"URI":i=s.get("URI");i instanceof Name&&(i="/"+i.name);break;case"GoTo":n=s.get("D");break;case"Launch":case"GoToR":const h=s.get("F");if(h instanceof Dict){const e=new FileSpec(h,null,!0),{filename:t}=e.serializable;i=t}else"string"==typeof h&&(i=h);const u=fetchRemoteDest(s);u&&"string"==typeof i&&(i=i.split("#",1)[0]+"#"+u);const d=s.get("NewWindow");"boolean"==typeof d&&(t.newWindow=d);break;case"GoToE":const f=s.get("T");let g;if(r&&f instanceof Dict){const e=f.get("R"),t=f.get("N");isName(e,"C")&&"string"==typeof t&&(g=r[stringToPDFString(t)])}if(g){t.attachment=g;const e=fetchRemoteDest(s);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const p=s.get("N");p instanceof Name&&(t.action=p.name);break;case"SetOCGState":const m=s.get("State"),b=s.get("PreserveRB");if(!Array.isArray(m)||0===m.length)break;const y=[];for(const e of m)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":y.push(e.name)}else e instanceof Ref&&y.push(e.toString());if(y.length!==m.length)break;t.setOCGState={state:y,preserveRB:"boolean"!=typeof b||b};break;case"JavaScript":const w=s.get("JS");let x;w instanceof BaseStream?x=w.getString():"string"==typeof w&&(x=w);const S=x&&recoverJsURL(stringToPDFString(x));if(S){i=S.url;t.newWindow=S.newWindow;break}default:if("JavaScript"===a||"SubmitForm"===a)break;warn(`parseDestDictionary - unsupported action: "${a}".`)}}else e.has("Dest")&&(n=e.get("Dest"));if("string"==typeof i){const e=createValidAbsoluteUrl(i,a,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=i}if(n){n instanceof Name&&(n=n.name);"string"==typeof n?t.dest=stringToPDFString(n):Array.isArray(n)&&(t.dest=n)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const r of e)((a=r)instanceof Ref||a instanceof Dict||a instanceof BaseStream||Array.isArray(a))&&t.push(r);var a}class ObjectLoader{constructor(e,t,a){this.dict=e;this.keys=t;this.xref=a;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const a=[];for(const r of e){const e=t.getRaw(r);void 0!==e&&a.push(e)}return this._walk(a)}async _walk(e){const t=[],a=[];for(;e.length;){let r=e.pop();if(r instanceof Ref){if(this.refSet.has(r))continue;try{this.refSet.put(r);r=this.xref.fetch(r)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(r);a.push({begin:e.begin,end:e.end})}}if(r instanceof BaseStream){const e=r.getBaseStreams();if(e){let i=!1;for(const t of e)if(!t.isDataLoaded){i=!0;a.push({begin:t.start,end:t.end})}i&&t.push(r)}}addChildren(r,e)}if(a.length){await this.xref.stream.manager.requestRanges(a);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const Pn=Symbol(),Ln=Symbol(),jn=Symbol(),_n=Symbol(),Un=Symbol(),Xn=Symbol(),qn=Symbol(),Hn=Symbol(),zn=Symbol(),Wn=Symbol("content"),$n=Symbol("data"),Gn=Symbol(),Vn=Symbol("extra"),Kn=Symbol(),Jn=Symbol(),Yn=Symbol(),Zn=Symbol(),Qn=Symbol(),es=Symbol(),ts=Symbol(),as=Symbol(),rs=Symbol(),is=Symbol(),ns=Symbol(),ss=Symbol(),os=Symbol(),cs=Symbol(),ls=Symbol(),hs=Symbol(),us=Symbol(),ds=Symbol(),fs=Symbol(),gs=Symbol(),ps=Symbol(),ms=Symbol(),bs=Symbol(),ys=Symbol(),ws=Symbol(),xs=Symbol(),Ss=Symbol(),ks=Symbol(),As=Symbol(),Cs=Symbol(),vs=Symbol(),Fs=Symbol(),Is=Symbol("namespaceId"),Os=Symbol("nodeName"),Ts=Symbol(),Ms=Symbol(),Ds=Symbol(),Bs=Symbol(),Rs=Symbol(),Ns=Symbol(),Es=Symbol(),Ls=Symbol(),js=Symbol("root"),_s=Symbol(),Us=Symbol(),Xs=Symbol(),qs=Symbol(),Hs=Symbol(),zs=Symbol(),Ws=Symbol(),$s=Symbol(),Gs=Symbol(),Vs=Symbol(),Ks=Symbol(),Js=Symbol("uid"),Ys=Symbol(),Zs={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},Qs={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},eo=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseInt(e,10);return!isNaN(r)&&a(r)?r:t}function getFloat({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseFloat(e);return!isNaN(r)&&a(r)?r:t}function getKeyword({data:e,defaultValue:t,validate:a}){return e&&a(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const a=e.trim().match(eo);if(!a)return getMeasurement(t);const[,r,i]=a,n=parseFloat(r);if(isNaN(n))return getMeasurement(t);if(0===n)return 0;const s=Qs[i];return s?s(n):n}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[a,r]=t;return{num:a,den:r}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,a,r){this.success=e;this.html=t;this.bbox=a;this.breakNode=r}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const a=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,a)}addPdfFont(e){const t=e.cssFontInfo,a=t.fontFamily;let r=this.fonts.get(a);if(!r){r=Object.create(null);this.fonts.set(a,r);this.defaultFont||(this.defaultFont=r)}let i="";const n=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?i=n>=700?"bolditalic":"italic":n>=700&&(i="bold");if(!i){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(i="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(i+="italic")}i||(i="regular");r[i]=e}getDefault(){return this.defaultFont}find(e,t=!0){let a=this.fonts.get(e)||this.cache.get(e);if(a)return a;const r=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let i=e.replaceAll(r,"");a=this.fonts.get(i);if(a){this.cache.set(e,a);return a}i=i.toLowerCase();const n=[];for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t);if(0===n.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(0===n.length){i=i.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t)}if(0===n.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(n.length>=1){1!==n.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,n[0]);return n[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,a,r){this.lineHeight=a;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(r);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const i=r.find(e.typeface);if(i){this.pdfFont=selectFont(e,i);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(r))}else[this.pdfFont,this.xfaFont]=this.defaultFont(r)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,a,r){this.fontFinder=r;this.stack=[new FontInfo(e,t,a,r)]}pushData(e,t,a){const r=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=r.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=r.paraMargin[e]);const i=new FontInfo(e,t,a||r.lineHeight,this.fontFinder);i.pdfFont||(i.pdfFont=r.pdfFont);this.stack.push(i)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,a,r){this.glyphs=[];this.fontSelector=new FontSelector(e,t,a,r);this.extraHeight=0}pushData(e,t,a){this.fontSelector.pushData(e,t,a)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),a=t.xfaFont.size;if(t.pdfFont){const r=t.xfaFont.letterSpacing,i=t.pdfFont,n=i.lineHeight||1.2,s=t.lineHeight||Math.max(1.2,n)*a,o=n-(void 0===i.lineGap?.2:i.lineGap),c=Math.max(1,o)*a,l=a/1e3,h=i.defaultWidth||i.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=i.encodeString(t).join(""),a=i.charsToGlyphs(e);for(const e of a){const t=e.width||h;this.glyphs.push([t*l+r,s,c,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([a,1.2*a,a,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,a=0,r=0,i=0,n=0,s=0,o=!1,c=!0;for(let l=0,h=this.glyphs.length;le){r=Math.max(r,n);n=0;i+=s;s=m;t=-1;a=0;o=!0;c=!1}else{s=Math.max(m,s);a=n;n+=h;t=l}else if(n+h>e){i+=s;s=m;if(-1!==t){l=t;r=Math.max(r,a);n=0;t=-1;a=0}else{r=Math.max(r,n);n=h}o=!0;c=!1}else{n+=h;s=Math.max(m,s)}}r=Math.max(r,n);i+=s+this.extraHeight;return{width:1.02*r,height:i,isBroken:o}}}const to=/^[^.[]+/,ao=/^[^\]]+/,ro={dot:0,dotDot:1,dotHash:2,dotBracket:3,dotParen:4},io=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[ss]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),no=new WeakMap;function parseExpression(e,t,a=!0){let r=e.match(to);if(!r)return null;let[i]=r;const n=[{name:i,cacheName:"."+i,index:0,js:null,formCalc:null,operator:ro.dot}];let s=i.length;for(;s0&&h.push(e)}if(0!==h.length||o||0!==c)e=isFinite(l)?h.filter((e=>le[l])):h.flat();else{const a=t[hs]();if(!(t=a))return null;c=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,a){const r=parseExpression(a);if(!r)return null;if(r.some((e=>e.operator===ro.dotDot)))return null;const i=io.get(r[0].name);let n=0;if(i){e=i(e,t);n=1}else e=t||e;for(let t=r.length;ne[Ws]())).join("")}get[co](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,co,e._attributes)}[xs](e){let t=this;for(;t;){if(t===e)return!0;t=t[hs]()}return!1}[hs](){return this[xo]}[ls](){return this[hs]()}[ss](e=null){return e?this[e]:this[lo]}[Gn](){const e=Object.create(null);this[Wn]&&(e.$content=this[Wn]);for(const t of Object.getOwnPropertyNames(this)){const a=this[t];null!==a&&(a instanceof XFAObject?e[t]=a[Gn]():a instanceof XFAObjectArray?a.isEmpty()||(e[t]=a.dump()):e[t]=a)}return e}[Ks](){return null}[Gs](){return HTMLResult.EMPTY}*[os](){for(const e of this[ss]())yield e}*[go](e,t){for(const a of this[os]())if(!e||t===e.has(a[Os])){const e=this[Qn](),t=a[Gs](e);t.success||(this[Vn].failingNode=a);yield t}}[Jn](){return null}[Ln](e,t){this[Vn].children.push(e)}[Qn](){}[_n]({filter:e=null,include:t=!0}){if(this[Vn].generator){const e=this[Qn](),t=this[Vn].failingNode[Gs](e);if(!t.success)return t;t.html&&this[Ln](t.html,t.bbox);delete this[Vn].failingNode}else this[Vn].generator=this[go](e,t);for(;;){const e=this[Vn].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Ln](t.html,t.bbox)}this[Vn].generator=null;return HTMLResult.EMPTY}[qs](e){this[ko]=new Set(Object.keys(e))}[mo](e){const t=this[co],a=this[ko];return[...e].filter((e=>t.has(e)&&!a.has(e)))}[_s](e,t=new Set){for(const a of this[lo])a[So](e,t)}[So](e,t){const a=this[po](e,t);a?this[so](a,e,t):this[_s](e,t)}[po](e,t){const{use:a,usehref:r}=this;if(!a&&!r)return null;let i=null,n=null,s=null,o=a;if(r){o=r;r.startsWith("#som(")&&r.endsWith(")")?n=r.slice(5,-1):r.startsWith(".#som(")&&r.endsWith(")")?n=r.slice(6,-1):r.startsWith("#")?s=r.slice(1):r.startsWith(".#")&&(s=r.slice(2))}else a.startsWith("#")?s=a.slice(1):n=a;this.use=this.usehref="";if(s)i=e.get(s);else{i=searchNode(e.get(js),this,n,!0,!1);i&&(i=i[0])}if(!i){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(i[Os]!==this[Os]){warn(`XFA - Incompatible prototype: ${i[Os]} !== ${this[Os]}.`);return null}if(t.has(i)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(i);const c=i[po](e,t);c&&i[so](c,e,t);i[_s](e,t);t.delete(i);return i}[so](e,t,a){if(a.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Wn]&&e[Wn]&&(this[Wn]=e[Wn]);new Set(a).add(e);for(const t of this[mo](e[ko])){this[t]=e[t];this[ko]&&this[ko].add(t)}for(const r of Object.getOwnPropertyNames(this)){if(this[co].has(r))continue;const i=this[r],n=e[r];if(i instanceof XFAObjectArray){for(const e of i[lo])e[So](t,a);for(let r=i[lo].length,s=n[lo].length;rXFAObject[ho](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Hn](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Js]=`${e[Os]}${Co++}`;e[lo]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[co].has(t)){e[t]=XFAObject[ho](this[t]);continue}const a=this[t];e[t]=a instanceof XFAObjectArray?new XFAObjectArray(a[yo]):null}for(const t of this[lo]){const a=t[Os],r=t[Hn]();e[lo].push(r);r[xo]=e;null===e[a]?e[a]=r:e[a][lo].push(r)}return e}[ss](e=null){return e?this[lo].filter((t=>t[Os]===e)):this[lo]}[es](e){return this[e]}[ts](e,t,a=!0){return Array.from(this[as](e,t,a))}*[as](e,t,a=!0){if("parent"!==e){for(const a of this[lo]){a[Os]===e&&(yield a);a.name===e&&(yield a);(t||a[Cs]())&&(yield*a[as](e,t,!1))}a&&this[co].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[xo]}}class XFAObjectArray{constructor(e=1/0){this[yo]=e;this[lo]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[lo].length<=this[yo]){this[lo].push(e);return!0}warn(`XFA - node "${e[Os]}" accepts no more than ${this[yo]} children`);return!1}isEmpty(){return 0===this[lo].length}dump(){return 1===this[lo].length?this[lo][0][Gn]():this[lo].map((e=>e[Gn]()))}[Hn](){const e=new XFAObjectArray(this[yo]);e[lo]=this[lo].map((e=>e[Hn]()));return e}get children(){return this[lo]}clear(){this[lo].length=0}}class XFAAttribute{constructor(e,t,a){this[xo]=e;this[Os]=t;this[Wn]=a;this[zn]=!1;this[Js]="attribute"+Co++}[hs](){return this[xo]}[ws](){return!0}[rs](){return this[Wn].trim()}[Hs](e){e=e.value||"";this[Wn]=e.toString()}[Ws](){return this[Wn]}[xs](e){return this[xo]===e||this[xo][xs](e)}}class XmlObject extends XFAObject{constructor(e,t,a={}){super(e,t);this[Wn]="";this[uo]=null;if("#text"!==t){const e=new Map;this[oo]=e;for(const[t,r]of Object.entries(a))e.set(t,new XFAAttribute(this,t,r));if(a.hasOwnProperty(Ts)){const e=a[Ts].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[uo]=!1:"dataValue"===e&&(this[uo]=!0))}}this[zn]=!1}[Vs](e){const t=this[Os];if("#text"===t){e.push(encodeToXmlString(this[Wn]));return}const a=utf8StringToString(t),r=this[Is]===vo?"xfa:":"";e.push(`<${r}${a}`);for(const[t,a]of this[oo].entries()){const r=utf8StringToString(t);e.push(` ${r}="${encodeToXmlString(a[Wn])}"`)}null!==this[uo]&&(this[uo]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Wn]||0!==this[lo].length){e.push(">");if(this[Wn])"string"==typeof this[Wn]?e.push(encodeToXmlString(this[Wn])):this[Wn][Vs](e);else for(const t of this[lo])t[Vs](e);e.push(``)}else e.push("/>")}[Ms](e){if(this[Wn]){const e=new XmlObject(this[Is],"#text");this[jn](e);e[Wn]=this[Wn];this[Wn]=""}this[jn](e);return!0}[Bs](e){this[Wn]+=e}[Kn](){if(this[Wn]&&this[lo].length>0){const e=new XmlObject(this[Is],"#text");this[jn](e);e[Wn]=this[Wn];delete this[Wn]}}[Gs](){return"#text"===this[Os]?HTMLResult.success({name:"#text",value:this[Wn]}):HTMLResult.EMPTY}[ss](e=null){return e?this[lo].filter((t=>t[Os]===e)):this[lo]}[Zn](){return this[oo]}[es](e){const t=this[oo].get(e);return void 0!==t?t:this[ss](e)}*[as](e,t){const a=this[oo].get(e);a&&(yield a);for(const a of this[lo]){a[Os]===e&&(yield a);t&&(yield*a[as](e,t))}}*[Yn](e,t){const a=this[oo].get(e);!a||t&&a[zn]||(yield a);for(const a of this[lo])yield*a[Yn](e,t)}*[ns](e,t,a){for(const r of this[lo]){r[Os]!==e||a&&r[zn]||(yield r);t&&(yield*r[ns](e,t,a))}}[ws](){return null===this[uo]?0===this[lo].length||this[lo][0][Is]===Zs.xhtml.id:this[uo]}[rs](){return null===this[uo]?0===this[lo].length?this[Wn].trim():this[lo][0][Is]===Zs.xhtml.id?this[lo][0][Ws]().trim():null:this[Wn].trim()}[Hs](e){e=e.value||"";this[Wn]=e.toString()}[Gn](e=!1){const t=Object.create(null);e&&(t.$ns=this[Is]);this[Wn]&&(t.$content=this[Wn]);t.$name=this[Os];t.children=[];for(const a of this[lo])t.children.push(a[Gn](e));t.attributes=Object.create(null);for(const[e,a]of this[oo])t.attributes[e]=a[Wn];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Wn]=""}[Bs](e){this[Wn]+=e}[Kn](){}}class OptionObject extends ContentObject{constructor(e,t,a){super(e,t);this[wo]=a}[Kn](){this[Wn]=getKeyword({data:this[Wn],defaultValue:this[wo][0],validate:e=>this[wo].includes(e)})}[Un](e){super[Un](e);delete this[wo]}}class StringObject extends ContentObject{[Kn](){this[Wn]=this[Wn].trim()}}class IntegerObject extends ContentObject{constructor(e,t,a,r){super(e,t);this[fo]=a;this[Ao]=r}[Kn](){this[Wn]=getInteger({data:this[Wn],defaultValue:this[fo],validate:this[Ao]})}[Un](e){super[Un](e);delete this[fo];delete this[Ao]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Fo={anchorType(e,t){const a=e[ls]();if(a&&(!a.layout||"position"===a.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const a=e[ls]();let r=e.w;const i=e.h;if(a.layout?.includes("row")){const t=a[Vn],i=e.colSpan;let n;if(-1===i){n=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{n=t.columnWidths.slice(t.currentColumn,t.currentColumn+i).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(n)||(r=e.w=n)}t.width=""!==r?measureToString(r):"auto";t.height=""!==i?measureToString(i):"auto"},position(e,t){const a=e[ls]();if(!a?.layout||"position"===a.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Os])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Ks]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[ls]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,a,r,i,n){const s=new TextMeasure(t,a,r,i);"string"==typeof e?s.addString(e):e[Rs](s);return s.compute(n)}function layoutNode(e,t){let a=null,r=null,i=!1;if((!e.w||!e.h)&&e.value){let n=0,s=0;if(e.margin){n=e.margin.leftInset+e.margin.rightInset;s=e.margin.topInset+e.margin.bottomInset}let o=null,c=null;if(e.para){c=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;c.top=""===e.para.spaceAbove?0:e.para.spaceAbove;c.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;c.left=""===e.para.marginLeft?0:e.para.marginLeft;c.right=""===e.para.marginRight?0:e.para.marginRight}let l=e.font;if(!l){const t=e[us]();let a=e[hs]();for(;a&&a!==t;){if(a.font){l=a.font;break}a=a[hs]()}}const h=(e.w||t.width)-n,u=e[ds].fontFinder;if(e.value.exData&&e.value.exData[Wn]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Wn],l,c,o,u,h);r=t.width;a=t.height;i=t.isBroken}else{const t=e.value[Ws]();if(t){const e=layoutText(t,l,c,o,u,h);r=e.width;a=e.height;i=e.isBroken}}null===r||e.w||(r+=n);null===a||e.h||(a+=s)}return{w:r,h:a,isBroken:i}}function computeBbox(e,t,a){let r;if(""!==e.w&&""!==e.h)r=[e.x,e.y,e.w,e.h];else{if(!a)return null;let i=e.w;if(""===i){if(0===e.maxW){const t=e[ls]();i="position"===t.layout&&""!==t.w?0:e.minW}else i=Math.min(e.maxW,a.width);t.attributes.style.width=measureToString(i)}let n=e.h;if(""===n){if(0===e.maxH){const t=e[ls]();n="position"===t.layout&&""!==t.h?0:e.minH}else n=Math.min(e.maxH,a.height);t.attributes.style.height=measureToString(n)}r=[e.x,e.y,i,n]}return r}function fixDimensions(e){const t=e[ls]();if(t.layout?.includes("row")){const a=t[Vn],r=e.colSpan;let i;i=-1===r?a.columnWidths.slice(a.currentColumn).reduce(((e,t)=>e+t),0):a.columnWidths.slice(a.currentColumn,a.currentColumn+r).reduce(((e,t)=>e+t),0);isNaN(i)||(e.w=i)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const a=Object.create(null);for(const r of t){const t=e[r];if(null!==t)if(Fo.hasOwnProperty(r))Fo[r](e,a);else if(t instanceof XFAObject){const e=t[Ks]();e?Object.assign(a,e):warn(`(DEBUG) - XFA - style for ${r} not implemented yet`)}}return a}function createWrapper(e,t){const{attributes:a}=t,{style:r}=a,i={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};a.class.push("xfaWrapped");if(e.border){const{widths:a,insets:n}=e.border[Vn];let s,o,c=n[0],l=n[3];const h=n[0]+n[2],u=n[1]+n[3];switch(e.border.hand){case"even":c-=a[0]/2;l-=a[3]/2;s=`calc(100% + ${(a[1]+a[3])/2-u}px)`;o=`calc(100% + ${(a[0]+a[2])/2-h}px)`;break;case"left":c-=a[0];l-=a[3];s=`calc(100% + ${a[1]+a[3]-u}px)`;o=`calc(100% + ${a[0]+a[2]-h}px)`;break;case"right":s=u?`calc(100% - ${u}px)`:"100%";o=h?`calc(100% - ${h}px)`:"100%"}const d=["xfaBorder"];isPrintOnly(e.border)&&d.push("xfaPrintOnly");const f={name:"div",attributes:{class:d,style:{top:`${c}px`,left:`${l}px`,width:s,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==r[e]){f.attributes.style[e]=r[e];delete r[e]}i.children.push(f,t)}else i.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==r[e]){i.attributes.style[e]=r[e];delete r[e]}i.attributes.style.position="absolute"===r.position?"absolute":"relative";delete r.position;if(r.alignSelf){i.attributes.style.alignSelf=r.alignSelf;delete r.alignSelf}return i}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const a="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),r=getMeasurement(e[a],"0px");e[a]=r-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[us]()[Vn].paraStack;return t.length?t.at(-1):null}function setPara(e,t,a){if(a.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const r=getCurrentPara(e);if(r){const e=a.attributes.style;e.display="flex";e.flexDirection="column";switch(r.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=r[Ks]();for(const[a,r]of Object.entries(t))a in e||(e[a]=r)}}}function setFontFamily(e,t,a,r){if(!a){delete r.fontFamily;return}const i=stripQuotes(e.typeface);r.fontFamily=`"${i}"`;const n=a.find(i);if(n){const{fontFamily:a}=n.regular.cssFontInfo;a!==i&&(r.fontFamily=`"${a}"`);const s=getCurrentPara(t);if(s&&""!==s.lineHeight)return;if(r.lineHeight)return;const o=selectFont(e,n);o&&(r.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Vn])return null;const t={name:"div",attributes:e[Vn].attributes,children:e[Vn].children};if(e[Vn].failingNode){const a=e[Vn].failingNode[Jn]();a&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[a])):t.children.push(a))}return 0===t.children.length?null:t}function addHTML(e,t,a){const r=e[Vn],i=r.availableSpace,[n,s,o,c]=a;switch(e.layout){case"position":r.width=Math.max(r.width,n+o);r.height=Math.max(r.height,s+c);r.children.push(t);break;case"lr-tb":case"rl-tb":if(!r.line||1===r.attempt){r.line=createLine(e,[]);r.children.push(r.line);r.numberInLine=0}r.numberInLine+=1;r.line.children.push(t);if(0===r.attempt){r.currentWidth+=o;r.height=Math.max(r.height,r.prevHeight+c)}else{r.currentWidth=o;r.prevHeight=r.height;r.height+=c;r.attempt=0}r.width=Math.max(r.width,r.currentWidth);break;case"rl-row":case"row":{r.children.push(t);r.width+=o;r.height=Math.max(r.height,c);const e=measureToString(r.height);for(const t of r.children)t.attributes.style.height=e;break}case"table":case"tb":r.width=Math.min(i.width,Math.max(r.width,o));r.height+=c;r.children.push(t)}}function getAvailableSpace(e){const t=e[Vn].availableSpace,a=e.margin?e.margin.topInset+e.margin.bottomInset:0,r=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Vn].attempt?{width:t.width-r-e[Vn].currentWidth,height:t.height-a-e[Vn].prevHeight}:{width:t.width-r,height:t.height-a-e[Vn].height};case"rl-row":case"row":return{width:e[Vn].columnWidths.slice(e[Vn].currentColumn).reduce(((e,t)=>e+t)),height:t.height-r};case"table":case"tb":return{width:t.width-r,height:t.height-a-e[Vn].height};default:return t}}function checkDimensions(e,t){if(null===e[us]()[Vn].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const a=e[ls](),r=a[Vn]?.attempt||0,[,i,n,s]=function getTransformedBBox(e){let t,a,r=""===e.w?NaN:e.w,i=""===e.h?NaN:e.h,[n,s]=[0,0];switch(e.anchorType||""){case"bottomCenter":[n,s]=[r/2,i];break;case"bottomLeft":[n,s]=[0,i];break;case"bottomRight":[n,s]=[r,i];break;case"middleCenter":[n,s]=[r/2,i/2];break;case"middleLeft":[n,s]=[0,i/2];break;case"middleRight":[n,s]=[r,i/2];break;case"topCenter":[n,s]=[r/2,0];break;case"topRight":[n,s]=[r,0]}switch(e.rotate||0){case 0:[t,a]=[-n,-s];break;case 90:[t,a]=[-s,n];[r,i]=[i,-r];break;case 180:[t,a]=[n,s];[r,i]=[-r,-i];break;case 270:[t,a]=[s,-n];[r,i]=[-i,r]}return[e.x+t+Math.min(0,r),e.y+a+Math.min(0,i),Math.abs(r),Math.abs(i)]}(e);switch(a.layout){case"lr-tb":case"rl-tb":return 0===r?e[us]()[Vn].noLayoutFailure?""!==e.w?Math.round(n-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(s-t.height)>2)&&(""!==e.w?Math.round(n-t.width)<=2||0===a[Vn].numberInLine&&t.height>2:t.width>2):!!e[us]()[Vn].noLayoutFailure||!(""!==e.h&&Math.round(s-t.height)>2)&&((""===e.w||Math.round(n-t.width)<=2||!a[As]())&&t.height>2);case"table":case"tb":return!!e[us]()[Vn].noLayoutFailure||(""===e.h||e[ks]()?(""===e.w||Math.round(n-t.width)<=2||!a[As]())&&t.height>2:Math.round(s-t.height)<=2);case"position":if(e[us]()[Vn].noLayoutFailure)return!0;if(""===e.h||Math.round(s+i-t.height)<=2)return!0;return s+i>e[us]()[Vn].currentContentArea.h;case"rl-row":case"row":return!!e[us]()[Vn].noLayoutFailure||(""===e.h||Math.round(s-t.height)<=2);default:return!0}}const Io=Zs.template.id,Oo="http://www.w3.org/2000/svg",Mo=/^H(\d+)$/,Do=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),Bo=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[is]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[jn](t);e.value=t}e.value[Hs](t)}function*getContainedChildren(e){for(const t of e[ss]())t instanceof SubformSet?yield*t[os]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[zs]=e[hs]()[zs];return}if(e[zs])return;let t=null;for(const a of e.traversal[ss]())if("next"===a.operation){t=a;break}if(!t||!t.ref){e[zs]=e[hs]()[zs];return}const a=e[us]();e[zs]=++a[zs];const r=a[Us](t.ref,e);if(!r)return;e=r[0]}}function applyAssist(e,t){const a=e.assist;if(a){const e=a[Gs]();e&&(t.title=e);const r=a.role.match(Mo);if(r){const e="heading",a=r[1];t.role=e;t["aria-level"]=a}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const a=e[hs]();"row"===a.layout&&(t.role="TH"===a.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Wn]?t.speak[Wn]:t.toolTip?t.toolTip[Wn]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[us]();if(null===t[Vn].firstUnsplittable){t[Vn].firstUnsplittable=e;t[Vn].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[us]();t[Vn].firstUnsplittable===e&&(t[Vn].noLayoutFailure=!1)}function handleBreak(e){if(e[Vn])return!1;e[Vn]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[us]();let a=null;if(e.target){a=t[Us](e.target,e[hs]());if(!a)return!1;a=a[0]}const{currentPageArea:r,currentContentArea:i}=t[Vn];if("pageArea"===e.targetType){a instanceof PageArea||(a=null);if(e.startNew){e[Vn].target=a||r;return!0}if(a&&a!==r){e[Vn].target=a;return!0}return!1}a instanceof ContentArea||(a=null);const n=a&&a[hs]();let s,o=n;if(e.startNew)if(a){const e=n.contentArea.children,t=e.indexOf(i),r=e.indexOf(a);-1!==t&&te;r[Vn].noLayoutFailure=!0;const s=t[Gs](a);e[Ln](s.html,s.bbox);r[Vn].noLayoutFailure=i;t[ls]=n}class AppearanceFilter extends StringObject{constructor(e){super(Io,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Io,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Gs](){const e=this.edge||new Edge({}),t=e[Ks](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ks]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;let r;const i={xmlns:Oo,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)r={name:"ellipse",attributes:{xmlns:Oo,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:a}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,n=this.sweepAngle>180?1:0,[s,o,c,l]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];r={name:"path",attributes:{xmlns:Oo,d:`M ${s} ${o} A 50 50 0 ${n} 0 ${c} ${l}`,vectorEffect:"non-scaling-stroke",style:a}};Object.assign(i,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const n={name:"svg",children:[r],attributes:i};if(hasMargin(this[hs]()[hs]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[n]});n.attributes.style.position="absolute";return HTMLResult.success(n)}}class Area extends XFAObject{constructor(e){super(Io,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[os](){yield*getContainedChildren(this)}[Cs](){return!0}[ys](){return!0}[Ln](e,t){const[a,r,i,n]=t;this[Vn].width=Math.max(this[Vn].width,a+i);this[Vn].height=Math.max(this[Vn].height,r+n);this[Vn].children.push(e)}[Qn](){return this[Vn].availableSpace}[Gs](e){const t=toStyle(this,"position"),a={style:t,id:this[Js],class:["xfaArea"]};isPrintOnly(this)&&a.class.push("xfaPrintOnly");this.name&&(a.xfaName=this.name);const r=[];this[Vn]={children:r,width:0,height:0,availableSpace:e};const i=this[_n]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!i.success){if(i.isBreak())return i;delete this[Vn];return HTMLResult.FAILURE}t.width=measureToString(this[Vn].width);t.height=measureToString(this[Vn].height);const n={name:"div",attributes:a,children:r},s=[this.x,this.y,this[Vn].width,this[Vn].height];delete this[Vn];return HTMLResult.success(n,s)}}class Assist extends XFAObject{constructor(e){super(Io,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Gs](){return this.toolTip?.[Wn]||null}}class Barcode extends XFAObject{constructor(e){super(Io,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Io,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Io,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Io,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Io,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Gs](e){return valueToHtml(1===this[Wn]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Io,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[is](){if(!this[Vn]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let a=e.length;a<4;a++)e.push(t)}const t=e.map((e=>e.thickness)),a=[0,0,0,0];if(this.margin){a[0]=this.margin.topInset;a[1]=this.margin.rightInset;a[2]=this.margin.bottomInset;a[3]=this.margin.leftInset}this[Vn]={widths:t,insets:a,edges:e}}return this[Vn]}[Ks](){const{edges:e}=this[is](),t=e.map((e=>{const t=e[Ks]();t.color||="#000000";return t})),a=Object.create(null);this.margin&&Object.assign(a,this.margin[Ks]());"visible"===this.fill?.presence&&Object.assign(a,this.fill[Ks]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[Ks]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let a=e.length;a<4;a++)e.push(t)}a.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":a.borderStyle="";break;case"inactive":a.borderStyle="none";break;default:a.borderStyle=t.map((e=>e.style)).join(" ")}a.borderWidth=t.map((e=>e.width)).join(" ");a.borderColor=t.map((e=>e.color)).join(" ");return a}}class Break extends XFAObject{constructor(e){super(Io,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Io,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Io,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Gs](e){this[Vn]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Io,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Gs](e){const t=this[hs]()[hs](),a={name:"button",attributes:{id:this[Js],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Wn]);if(!t)continue;const r=fixURL(t.url);r&&a.children.push({name:"a",attributes:{id:"link"+this[Js],href:r,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(a)}}class Calculate extends XFAObject{constructor(e){super(Io,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Io,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[Hs](e){_setValue(this,e)}[is](e){if(!this[Vn]){let{width:t,height:a}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":a=this.reserve<=0?a:this.reserve}this[Vn]=layoutNode(this,{width:t,height:a})}return this[Vn]}[Gs](e){if(!this.value)return HTMLResult.EMPTY;this[Es]();const t=this.value[Gs](e).html;if(!t){this[Ns]();return HTMLResult.EMPTY}const a=this.reserve;if(this.reserve<=0){const{w:t,h:a}=this[is](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=a}}const r=[];"string"==typeof t?r.push({name:"#text",value:t}):r.push(t);const i=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(i.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(i.height=measureToString(this.reserve))}setPara(this,null,t);this[Ns]();this.reserve=a;return HTMLResult.success({name:"div",attributes:{style:i,class:["xfaCaption"]},children:r})}}class Certificate extends StringObject{constructor(e){super(Io,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Io,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Io,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle("margin"),a=measureToString(this.size);t.width=t.height=a;let r,i,n;const s=this[hs]()[hs](),o=s.items.children.length&&s.items.children[0][Gs]().html||[],c={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},l=(s.value?.[Ws]()||"off")===c.on||void 0,h=s[ls](),u=s[Js];let d;if(h instanceof ExclGroup){n=h[Js];r="radio";i="xfaRadio";d=h[$n]?.[Js]||h[Js]}else{r="checkbox";i="xfaCheckbox";d=s[$n]?.[Js]||s[Js]}const f={name:"input",attributes:{class:[i],style:t,fieldId:u,dataId:d,type:r,checked:l,xfaOn:c.on,xfaOff:c.off,"aria-label":ariaLabel(s),"aria-required":!1}};n&&(f.attributes.name=n);if(isRequired(s)){f.attributes["aria-required"]=!0;f.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[f]})}}class ChoiceList extends XFAObject{constructor(e){super(Io,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","margin"),a=this[hs]()[hs](),r={fontSize:`calc(${a.font?.size||10}px * var(--scale-factor))`},i=[];if(a.items.children.length>0){const e=a.items;let t=0,n=0;if(2===e.children.length){t=e.children[0].save;n=1-t}const s=e.children[t][Gs]().html,o=e.children[n][Gs]().html;let c=!1;const l=a.value?.[Ws]()||"";for(let e=0,t=s.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(n.length<3)return{r:a,g:r,b:i};[a,r,i]=n;return{r:a,g:r,b:i}}(e.value):"";this.extras=null}[fs](){return!1}[Ks](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Io,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Io,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Io,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Gs](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},a=["xfaContentarea"];isPrintOnly(this)&&a.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:a,id:this[Js]}})}}class Corner extends XFAObject{constructor(e){super(Io,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Io,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Io,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Io,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin"),a=this[hs]()[hs](),r={name:"input",attributes:{type:"text",fieldId:a[Js],dataId:a[$n]?.[Js]||a[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Decimal extends ContentObject{constructor(e){super(Io,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseFloat(this[Wn].trim());this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Io,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Io,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Io,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Io,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Io,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[Hs](e){_setValue(this,e)}[Gs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Es]();const t=this.w,a=this.h,{w:r,h:i,isBroken:n}=layoutNode(this,e);if(r&&""===this.w){if(n&&this[ls]()[As]()){this[Ns]();return HTMLResult.FAILURE}this.w=r}i&&""===this.h&&(this.h=i);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=a;this[Ns]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const s=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,s);if(s.margin){s.padding=s.margin;delete s.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const c={style:s,id:this[Js],class:o};this.name&&(c.xfaName=this.name);const l={name:"div",attributes:c,children:[]};applyAssist(this,c);const h=computeBbox(this,l,e),u=this.value?this.value[Gs](e).html:null;if(null===u){this.w=t;this.h=a;this[Ns]();return HTMLResult.success(createWrapper(this,l),h)}l.children.push(u);setPara(this,s,u);this.w=t;this.h=a;this[Ns]();return HTMLResult.success(createWrapper(this,l),h)}}class Edge extends XFAObject{constructor(e){super(Io,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Ks]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Io,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Io,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Io,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Io,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Io,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Io,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Io,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Io,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Io,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[bs](){return"text/html"===this.contentType}[Ms](e){if("text/html"===this.contentType&&e[Is]===Zs.xhtml.id){this[Wn]=e;return!0}if("text/xml"===this.contentType){this[Wn]=e;return!0}return!1}[Gs](e){return"text/html"===this.contentType&&this[Wn]?this[Wn][Gs](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Io,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Io,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[ys](){return!0}[fs](){return!0}[Hs](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[jn](e);t.value=e}t.value[Hs](e)}}[As](){return this.layout.endsWith("-tb")&&0===this[Vn].attempt&&this[Vn].numberInLine>0||this[hs]()[As]()}[ks](){const e=this[ls]();if(!e[ks]())return!1;if(void 0!==this[Vn]._isSplittable)return this[Vn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Vn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Vn].numberInLine)return!1;this[Vn]._isSplittable=!0;return!0}[Jn](){return flushHTML(this)}[Ln](e,t){addHTML(this,e,t)}[Qn](){return getAvailableSpace(this)}[Gs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Js],class:[]};setAccess(this,a.class);this[Vn]||(this[Vn]=Object.create(null));Object.assign(this[Vn],{children:t,attributes:a,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[ks]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const i=new Set(["field"]);if(this.layout.includes("row")){const e=this[ls]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Vn].columnWidths=e;this[Vn].currentColumn=0}}const n=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),s=["xfaExclgroup"],o=layoutClass(this);o&&s.push(o);isPrintOnly(this)&&s.push("xfaPrintOnly");a.style=n;a.class=s;this.name&&(a.xfaName=this.name);this[Es]();const c="lr-tb"===this.layout||"rl-tb"===this.layout,l=c?2:1;for(;this[Vn].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[ys](){return!0}[Hs](e){_setValue(this,e)}[Gs](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[ds]=this[ds];this[jn](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[jn](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Vn];this[Es]();const t=this.caption?this.caption[Gs](e).html:null,a=this.w,r=this.h;let i=0,n=0;if(this.margin){i=this.margin.leftInset+this.margin.rightInset;n=this.margin.topInset+this.margin.bottomInset}let s=null;if(""===this.w||""===this.h){let t=null,a=null,r=0,o=0;if(this.ui.checkButton)r=o=this.ui.checkButton.size;else{const{w:t,h:a}=layoutNode(this,e);if(null!==t){r=t;o=a}else o=function fonts_getMetrics(e,t=!1){let a=null;if(e){const t=stripQuotes(e.typeface),r=e[ds].fontFinder.find(t);a=selectFont(e,r)}if(!a)return{lineHeight:12,lineGap:2,lineNoGap:10};const r=e.size||10,i=a.lineHeight?Math.max(t?0:1.2,a.lineHeight):1.2,n=void 0===a.lineGap?.2:a.lineGap;return{lineHeight:i*r,lineGap:n*r,lineNoGap:Math.max(1,i-n)*r}}(this.font,!0).lineNoGap}s=getBorderDims(this.ui[is]());r+=s.w;o+=s.h;if(this.caption){const{w:i,h:n,isBroken:s}=this.caption[is](e);if(s&&this[ls]()[As]()){this[Ns]();return HTMLResult.FAILURE}t=i;a=n;switch(this.caption.placement){case"left":case"right":case"inline":t+=r;break;case"top":case"bottom":a+=o}}else{t=r;a=o}if(t&&""===this.w){t+=i;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Io,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseFloat(this[Wn].trim());this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Io,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Un](e){super[Un](e);this[ds].usedTypefaces.add(this.typeface)}[Ks](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[ds].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Io,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Io,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Io,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Io,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Gs](){if(this.contentType&&!Do.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[ds].images&&this[ds].images.get(this.href);if(!e&&(this.href||!this[Wn]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=stringToBytes(atob(this[Wn])));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,a]of Bo)if(e.length>t.length&&t.every(((t,a)=>t===e[a]))){this.contentType=a;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let a;switch(this.aspect){case"fit":case"actual":break;case"height":a={height:"100%",objectFit:"fill"};break;case"none":a={width:"100%",height:"100%",objectFit:"fill"};break;case"width":a={width:"100%",objectFit:"fill"}}const r=this[hs]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:a,src:URL.createObjectURL(t),alt:r?ariaLabel(r[hs]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Io,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Gs](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Io,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=parseInt(this[Wn].trim(),10);this[Wn]=isNaN(e)?null:e}[Gs](e){return valueToHtml(null!==this[Wn]?this[Wn].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Io,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Io,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Gs](){const e=[];for(const t of this[ss]())e.push(t[Ws]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Io,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Io,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Io,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Gs](){const e=this[hs]()[hs](),t=this.edge||new Edge({}),a=t[Ks](),r=Object.create(null),i="visible"===t.presence?t.thickness:0;r.strokeWidth=measureToString(i);r.stroke=a.color;let n,s,o,c,l="100%",h="100%";if(e.w<=i){[n,s,o,c]=["50%",0,"50%","100%"];l=r.strokeWidth}else if(e.h<=i){[n,s,o,c]=[0,"50%","100%","50%"];h=r.strokeWidth}else"\\"===this.slope?[n,s,o,c]=[0,0,"100%","100%"]:[n,s,o,c]=[0,"100%","100%",0];const u={name:"svg",children:[{name:"line",attributes:{xmlns:Oo,x1:n,y1:s,x2:o,y2:c,style:r}}],attributes:{xmlns:Oo,width:l,height:h,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[u]});u.attributes.style.position="absolute";return HTMLResult.success(u)}}class Linear extends XFAObject{constructor(e){super(Io,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Ks]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Io,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){this[Wn]=getStringOption(this[Wn],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Io,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Io,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Io,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Io,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const a=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(a.length<4||a[2]<0||a[3]<0)return{x:t,y:t,width:t,height:t};const[r,i,n,s]=a;return{x:r,y:i,width:n,height:s}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Io,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Io,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin"),a=this[hs]()[hs](),r={name:"input",attributes:{type:"text",fieldId:a[Js],dataId:a[$n]?.[Js]||a[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Occur extends XFAObject{constructor(e){super(Io,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Un](){const e=this[hs](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[vs](){if(!this[Vn]){this[Vn]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Vn].numberOfUsee.oddOrEven===t&&e.pagePosition===a));if(r)return r;r=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===a));if(r)return r;r=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return r||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Io,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Ks](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Ks]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Io,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Io,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";const t=this.color?this.color[Ks]():"#000000",a="repeating-linear-gradient",r=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${a}(to top,${r}) ${a}(to right,${r})`;case"crossDiagonal":return`${a}(45deg,${r}) ${a}(-45deg,${r})`;case"diagonalLeft":return`${a}(45deg,${r})`;case"diagonalRight":return`${a}(-45deg,${r})`;case"horizontal":return`${a}(to top,${r})`;case"vertical":return`${a}(to right,${r})`}return""}}class Picture extends StringObject{constructor(e){super(Io,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Io,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Io,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){e=e?e[Ks]():"#FFFFFF";const t=this.color?this.color[Ks]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Io,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Io,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Io,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Gs](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Ks](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ks]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;const r=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Ks](),i={name:"svg",children:[{name:"rect",attributes:{xmlns:Oo,width:"100%",height:"100%",x:0,y:0,rx:r.radius,ry:r.radius,style:a}}],attributes:{xmlns:Oo,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[hs]()[hs]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[i]});i.attributes.style.position="absolute";return HTMLResult.success(i)}}class RefElement extends StringObject{constructor(e){super(Io,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Io,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Io,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Io,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Io,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Io,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Io,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](e){return e?e[Ks]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Io,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Io,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ks](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Io,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[ls](){const e=this[hs]();return e instanceof SubformSet?e[ls]():e}[ys](){return!0}[As](){return this.layout.endsWith("-tb")&&0===this[Vn].attempt&&this[Vn].numberInLine>0||this[hs]()[As]()}*[os](){yield*getContainedChildren(this)}[Jn](){return flushHTML(this)}[Ln](e,t){addHTML(this,e,t)}[Qn](){return getAvailableSpace(this)}[ks](){const e=this[ls]();if(!e[ks]())return!1;if(void 0!==this[Vn]._isSplittable)return this[Vn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Vn]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Vn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Vn].numberInLine)return!1;this[Vn]._isSplittable=!0;return!0}[Gs](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[ds]=this[ds];this[jn](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[ds]=this[ds];this[jn](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[ds]=this[ds];this[jn](e);this.overflow.push(e)}this[Ls](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Vn]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Js],class:[]};setAccess(this,a.class);this[Vn]||(this[Vn]=Object.create(null));Object.assign(this[Vn],{children:t,line:null,attributes:a,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[us](),i=r[Vn].noLayoutFailure,n=this[ks]();n||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[ls]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Vn].columnWidths=e;this[Vn].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),c=["xfaSubform"],l=layoutClass(this);l&&c.push(l);a.style=o;a.class=c;this.name&&(a.xfaName=this.name);if(this.overflow){const t=this.overflow[is]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Es]();const h="lr-tb"===this.layout||"rl-tb"===this.layout,u=h?2:1;for(;this[Vn].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Vn].afterBreakAfter=y;return HTMLResult.breakNode(e)}}delete this[Vn];return y}}class SubformSet extends XFAObject{constructor(e){super(Io,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[os](){yield*getContainedChildren(this)}[ls](){let e=this[hs]();for(;!(e instanceof Subform);)e=e[hs]();return e}[ys](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Io,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){this[Wn]=new Map(this[Wn].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Io,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Io,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Io,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Kn](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[zs]=5e3}[ks](){return!0}[Us](e,t){return e.startsWith("#")?[this[gs].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[$s](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Vn]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[Xn]();const t=e.pageSet.pageArea.children,a={name:"div",children:[]};let r=null,i=null,n=null;if(e.breakBefore.children.length>=1){i=e.breakBefore.children[0];n=i.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){i=e.subform.children[0].breakBefore.children[0];n=i.target}else if(e.break?.beforeTarget){i=e.break;n=i.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){i=e.subform.children[0].break;n=i.beforeTarget}if(i){const e=this[Us](n,i[hs]());if(e instanceof PageArea){r=e;i[Vn]={}}}r||(r=t[0]);r[Vn]={numberOfUse:1};const s=r[hs]();s[Vn]={numberOfUse:1,pageIndex:s.pageArea.children.indexOf(r),pageSetIndex:0};let o,c=null,l=null,h=!0,u=0,d=0;for(;;){if(h)u=0;else{a.children.pop();if(3==++u){warn("XFA - Something goes wrong: please file a bug.");return a}}o=null;this[Vn].currentPageArea=r;const t=r[Gs]().html;a.children.push(t);if(c){this[Vn].noLayoutFailure=!0;t.children.push(c[Gs](r[Vn].space).html);c=null}if(l){this[Vn].noLayoutFailure=!0;t.children.push(l[Gs](r[Vn].space).html);l=null}const i=r.contentArea.children,n=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));h=!1;this[Vn].firstUnsplittable=null;this[Vn].noLayoutFailure=!1;const flush=t=>{const a=e[Jn]();if(a){h||=a.children?.length>0;n[t].children.push(a)}};for(let t=d,r=i.length;t0;n[t].children.push(u.html)}else!h&&a.children.length>1&&a.children.pop();return a}if(u.isBreak()){const e=u.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){c=this[Us](e.leader,e[hs]());c=c?c[0]:null}if(e.trailer){l=this[Us](e.trailer,e[hs]());l=l?l[0]:null}if("pageArea"===e.targetType){o=e[Vn].target;t=1/0}else if(e[Vn].target){o=e[Vn].target;d=e[Vn].index+1;t=1/0}else t=e[Vn].index}else if(this[Vn].overflowNode){const e=this[Vn].overflowNode;this[Vn].overflowNode=null;const a=e[is](),r=a.target;a.addLeader=null!==a.leader;a.addTrailer=null!==a.trailer;flush(t);const n=t;t=1/0;if(r instanceof PageArea)o=r;else if(r instanceof ContentArea){const e=i.indexOf(r);if(-1!==e)e>n?t=e-1:d=e;else{o=r[hs]();d=o.contentArea.children.indexOf(r)}}}else flush(t)}this[Vn].pageNumber+=1;o&&(o[vs]()?o[Vn].numberOfUse+=1:o=null);r=o||r[cs]();yield null}}}class Text extends ContentObject{constructor(e){super(Io,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[Pn](){return!0}[Ms](e){if(e[Is]===Zs.xhtml.id){this[Wn]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Os]}.`);return!1}[Bs](e){this[Wn]instanceof XFAObject||super[Bs](e)}[Kn](){"string"==typeof this[Wn]&&(this[Wn]=this[Wn].replaceAll("\r\n","\n"))}[is](){return"string"==typeof this[Wn]?this[Wn].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[Wn][Ws]()}[Gs](e){if("string"==typeof this[Wn]){const e=valueToHtml(this[Wn]).html;if(this[Wn].includes("\u2029")){e.name="div";e.children=[];this[Wn].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[Wn])){e.name="div";e.children=[];this[Wn].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[Wn][Gs](e)}}class TextEdit extends XFAObject{constructor(e){super(Io,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Gs](e){const t=toStyle(this,"border","font","margin");let a;const r=this[hs]()[hs]();""===this.multiLine&&(this.multiLine=r instanceof Draw?1:0);a=1===this.multiLine?{name:"textarea",attributes:{dataId:r[$n]?.[Js]||r[Js],fieldId:r[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:r[$n]?.[Js]||r[Js],fieldId:r[Js],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}};if(isRequired(r)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Time extends StringObject{constructor(e){super(Io,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Kn](){const e=this[Wn].trim();this[Wn]=e?new Date(e):null}[Gs](e){return valueToHtml(this[Wn]?this[Wn].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Io,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Io,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Io,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Io,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Cs](){return!1}}class Ui extends XFAObject{constructor(e){super(Io,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[is](){if(void 0===this[Vn]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Vn]=t;return t}}this[Vn]=null}return this[Vn]}[Gs](e){const t=this[is]();return t?t[Gs](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Io,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Io,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[Hs](e){const t=this[hs]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[jn](this.image)}this.image[Wn]=e[Wn];return}const a=e[Os];if(null===this[a]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Ls](t)}}this[e[Os]]=e;this[jn](e)}else this[a][Wn]=e[Wn]}[Ws](){if(this.exData)return"string"==typeof this.exData[Wn]?this.exData[Wn].trim():this.exData[Wn][Ws]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Wn]||"").toString().trim()}return null}[Gs](e){for(const t of Object.getOwnPropertyNames(this)){const a=this[t];if(a instanceof XFAObject)return a[Gs](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Io,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Cs](){return!0}}class TemplateNamespace{static[Ys](e,t){if(TemplateNamespace.hasOwnProperty(e)){const a=TemplateNamespace[e](t);a[qs](t);return a}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Ro=Zs.datasets.id;function createText(e){const t=new Text({});t[Wn]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(Zs.datasets.id,"data");this.emptyMerge=0===this.data[ss]().length;this.root.form=this.form=e.template[Hn]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,a){e[$n]=t;if(e[fs]())if(t[ws]()){const a=t[rs]();e[Hs](createText(a))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const a=t[ss]().map((e=>e[Wn].trim())).join("\n");e[Hs](createText(a))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[ws]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,a,r){if(!e)return null;let i,n;for(let r=0;r<3;r++){i=a[ns](e,!1,!0);for(;;){n=i.next().value;if(!n)break;if(t===n[ws]())return n}if(a[Is]===Zs.datasets.id&&"data"===a[Os])break;a=a[hs]()}if(!r)return null;i=this.data[ns](e,!0,!1);n=i.next().value;if(n)return n;i=this.data[Yn](e,!0);n=i.next().value;return n?.[ws]()?n:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:a,target:r,connection:i}of e.setProperty.children){if(i)continue;if(!a)continue;const n=searchNode(this.root,t,a,!1,!1);if(!n){warn(`XFA - Invalid reference: ${a}.`);continue}const[s]=n;if(!s[xs](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,r,!1,!1);if(!o){warn(`XFA - Invalid target: ${r}.`);continue}const[c]=o;if(!c[xs](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const l=c[hs]();if(c instanceof SetProperty||l instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(c instanceof BindItems||l instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const h=s[Ws](),u=c[Os];if(c instanceof XFAAttribute){const e=Object.create(null);e[u]=h;const t=Reflect.construct(Object.getPrototypeOf(l).constructor,[e]);l[u]=t[u]}else if(c.hasOwnProperty(Wn)){c[$n]=s;c[Wn]=h;c[Kn]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Ls](t);e.items.clear();const a=new Items({}),r=new Items({});e[jn](a);e.items.push(a);e[jn](r);e.items.push(r);for(const{ref:i,labelRef:n,valueRef:s,connection:o}of e.bindItems.children){if(o)continue;if(!i)continue;const e=searchNode(this.root,t,i,!1,!1);if(e)for(const t of e){if(!t[xs](this.datasets)){warn(`XFA - Invalid ref (${i}): must be a datasets child.`);continue}const e=searchNode(this.root,t,n,!0,!1);if(!e){warn(`XFA - Invalid label: ${n}.`);continue}const[o]=e;if(!o[xs](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const c=searchNode(this.root,t,s,!0,!1);if(!c){warn(`XFA - Invalid value: ${s}.`);continue}const[l]=c;if(!l[xs](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const h=createText(o[Ws]()),u=createText(l[Ws]());a[jn](h);a.text.push(h);r[jn](u);r.text.push(u)}else warn(`XFA - Invalid reference: ${i}.`)}}_bindOccurrences(e,t,a){let r;if(t.length>1){r=e[Hn]();r[Ls](r.occur);r.occur=null}this._bindValue(e,t[0],a);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const i=e[hs](),n=e[Os],s=i[ps](e);for(let e=1,o=t.length;et.name===e.name)).length:a[r].children.length;const n=a[ps](e)+1,s=t.initial-i;if(s){const t=e[Hn]();t[Ls](t.occur);t.occur=null;a[r].push(t);a[ms](n,t);for(let e=1;e0)this._bindOccurrences(r,[e[0]],null);else if(this.emptyMerge){const e=t[Is]===Ro?-1:t[Is],a=r[$n]=new XmlObject(e,r.name||"root");t[jn](a);this._bindElement(r,a)}continue}if(!r[ys]())continue;let e=!1,i=null,n=null,s=null;if(r.bind){switch(r.bind.match){case"none":this._setAndBind(r,t);continue;case"global":e=!0;break;case"dataRef":if(!r.bind.ref){warn(`XFA - ref is empty in node ${r[Os]}.`);this._setAndBind(r,t);continue}n=r.bind.ref}r.bind.picture&&(i=r.bind.picture[Wn])}const[o,c]=this._getOccurInfo(r);if(n){s=searchNode(this.root,t,n,!0,!1);if(null===s){s=createDataNode(this.data,t,n);if(!s)continue;this._isConsumeData()&&(s[zn]=!0);this._setAndBind(r,s);continue}this._isConsumeData()&&(s=s.filter((e=>!e[zn])));s.length>c?s=s.slice(0,c):0===s.length&&(s=null);s&&this._isConsumeData()&&s.forEach((e=>{e[zn]=!0}))}else{if(!r.name){this._setAndBind(r,t);continue}if(this._isConsumeData()){const a=[];for(;a.length0?a:null}else{s=t[ns](r.name,!1,this.emptyMerge).next().value;if(!s){if(0===o){a.push(r);continue}const e=t[Is]===Ro?-1:t[Is];s=r[$n]=new XmlObject(e,r.name);this.emptyMerge&&(s[zn]=!0);t[jn](s);this._setAndBind(r,s);continue}this.emptyMerge&&(s[zn]=!0);s=[s]}}s?this._bindOccurrences(r,s,i):o>0?this._setAndBind(r,t):a.push(r)}a.forEach((e=>e[hs]()[Ls](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[ss]()]];for(;t.length>0;){const a=t.at(-1),[r,i]=a;if(r+1===i.length){t.pop();continue}const n=i[++a[0]],s=e.get(n[Js]);if(s)n[Hs](s);else{const t=n[Zn]();for(const a of t.values()){const t=e.get(a[Js]);if(t){a[Hs](t);break}}}const o=n[ss]();o.length>0&&t.push([-1,o])}const a=[''];if(this.dataset)for(const e of this.dataset[ss]())"data"!==e[Os]&&e[Vs](a);this.data[Vs](a);a.push("");return a.join("")}}const No=Zs.config.id;class Acrobat extends XFAObject{constructor(e){super(No,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(No,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(No,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(No,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(No,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(No,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(No,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(No,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(No,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(No,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(No,"amd")}}class config_Area extends XFAObject{constructor(e){super(No,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(No,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(No,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(No,"base")}}class BatchOutput extends XFAObject{constructor(e){super(No,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(No,"behaviorOverride")}[Kn](){this[Wn]=new Map(this[Wn].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(No,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(No,"change")}}class Common extends XFAObject{constructor(e){super(No,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(No,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(No,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(No,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(No,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(No,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(No,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(No,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(No,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(No,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(No,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(No,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(No,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(No,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(No,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(No,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(No,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(No,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(No,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(No,"embed")}}class config_Encrypt extends Option01{constructor(e){super(No,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(No,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(No,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(No,"enforce")}}class Equate extends XFAObject{constructor(e){super(No,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(No,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,a=this._unicodeRange;for(let r of a.split(",").map((e=>e.trim())).filter((e=>!!e))){r=r.split("-",2).map((e=>{const a=e.match(t);return a?parseInt(a[1],16):0}));1===r.length&&r.push(r[0]);e.push(r)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(No,"exclude")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(No,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(No,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(No,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(No,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(No,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(No,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(No,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(No,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(No,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(No,"interactive")}}class Jog extends OptionObject{constructor(e){super(No,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(No,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(No,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(No,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(No,"linearized")}}class Locale extends StringObject{constructor(e){super(No,"locale")}}class LocaleSet extends StringObject{constructor(e){super(No,"localeSet")}}class Log extends XFAObject{constructor(e){super(No,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(No,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(No,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(No,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(No,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(No,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(No,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(No,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(No,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(No,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(No,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(No,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(No,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(No,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(No,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(No,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(No,"packets")}[Kn](){"*"!==this[Wn]&&(this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(No,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(No,"pageRange")}[Kn](){const e=this[Wn].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let a=0,r=e.length;a!1))}}class Pcl extends XFAObject{constructor(e){super(No,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(No,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(No,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(No,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(No,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(No,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(No,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(No,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(No,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(No,"print")}}class PrintHighQuality extends Option01{constructor(e){super(No,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(No,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(No,"printerName")}}class Producer extends StringObject{constructor(e){super(No,"producer")}}class Ps extends XFAObject{constructor(e){super(No,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(No,"range")}[Kn](){this[Wn]=this[Wn].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(No,"record")}[Kn](){this[Wn]=this[Wn].trim();const e=parseInt(this[Wn],10);!isNaN(e)&&e>=0&&(this[Wn]=e)}}class Relevant extends ContentObject{constructor(e){super(No,"relevant")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(No,"rename")}[Kn](){this[Wn]=this[Wn].trim();(this[Wn].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Wn]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(No,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(No,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(No,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(No,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(No,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(No,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(No,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(No,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(No,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(No,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(No,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(No,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(No,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(No,"tagged")}}class config_Template extends XFAObject{constructor(e){super(No,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(No,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(No,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(No,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(No,"trace",!0);this.area=new XFAObjectArray}}class config_Transform extends XFAObject{constructor(e){super(No,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(No,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(No,"uri")}}class config_Validate extends OptionObject{constructor(e){super(No,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(No,"validateApprovalSignatures")}[Kn](){this[Wn]=this[Wn].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(No,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(No,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(No,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(No,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(No,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(No,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(No,"window")}[Kn](){const e=this[Wn].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[Wn]=[0,0];else{1===e.length&&e.push(e[0]);this[Wn]=e}}}class Xdc extends XFAObject{constructor(e){super(No,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(No,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(No,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(No,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[Ys](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new config_Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Eo=Zs.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Eo,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Eo,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Eo,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Eo,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Eo,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Eo,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Eo,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Eo,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Eo,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Eo,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Eo,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Eo,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[Ys](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Po=Zs.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Po,"data",e)}[Ss](){return!0}}class Datasets extends XFAObject{constructor(e){super(Po,"datasets",!0);this.data=null;this.Signature=null}[Ms](e){const t=e[Os];("data"===t&&e[Is]===Po||"Signature"===t&&e[Is]===Zs.signature.id)&&(this[t]=e);this[jn](e)}}class DatasetsNamespace{static[Ys](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Lo=Zs.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Lo,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Lo,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Lo,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Lo,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Lo,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Lo,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Lo,"day")}}class DayNames extends XFAObject{constructor(e){super(Lo,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Lo,"era")}}class EraNames extends XFAObject{constructor(e){super(Lo,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Lo,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Lo,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Lo,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Lo,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Lo,"month")}}class MonthNames extends XFAObject{constructor(e){super(Lo,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Lo,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Lo,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Lo,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Lo,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Lo,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Lo,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Lo,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Lo,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[Ys](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const jo=Zs.signature.id;class signature_Signature extends XFAObject{constructor(e){super(jo,"signature",!0)}}class SignatureNamespace{static[Ys](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const _o=Zs.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(_o,"stylesheet",!0)}}class StylesheetNamespace{static[Ys](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const Uo=Zs.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(Uo,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Ds](e){const t=Zs[e[Os]];return t&&e[Is]===t.id}}class XdpNamespace{static[Ys](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const Xo=Zs.xhtml.id,qo=Symbol(),Ho=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),zo=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=getMeasurement(e)))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Wo=/\s+/g,$o=/[\r\n]+/g,Go=/\r\n?/g;function mapStyle(e,t,a){const r=Object.create(null);if(!e)return r;const i=Object.create(null);for(const[t,a]of e.split(";").map((e=>e.split(":",2)))){const e=zo.get(t);if(""===e)continue;let n=a;e&&(n="string"==typeof e?e:e(a,i));t.endsWith("scale")?r.transform=r.transform?`${r[t]} ${n}`:n:r[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=n}r.fontFamily&&setFontFamily({typeface:r.fontFamily,weight:r.fontWeight||"normal",posture:r.fontStyle||"normal",size:i.fontSize||0},t,t[ds].fontFinder,r);if(a&&r.verticalAlign&&"0px"!==r.verticalAlign&&r.fontSize){const e=.583,t=.333,a=getMeasurement(r.fontSize);r.fontSize=measureToString(a*e);r.verticalAlign=measureToString(Math.sign(getMeasurement(r.verticalAlign))*a*t)}a&&r.fontSize&&(r.fontSize=`calc(${r.fontSize} * var(--scale-factor))`);fixTextIndent(r);return r}const Vo=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(Xo,t);this[qo]=!1;this.style=e.style||""}[Un](e){super[Un](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,a])=>{"font-family"===t&&e[ds].usedTypefaces.add(a);return Ho.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[Pn](){return!Vo.has(this[Os])}[Bs](e,t=!1){if(t)this[qo]=!0;else{e=e.replaceAll($o,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Wo," "))}e&&(this[Wn]+=e)}[Rs](e,t=!0){const a=Object.create(null),r={top:NaN,bottom:NaN,left:NaN,right:NaN};let i=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":a.typeface=stripQuotes(t);break;case"font-size":a.size=getMeasurement(t);break;case"font-weight":a.weight=t;break;case"font-style":a.posture=t;break;case"letter-spacing":a.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:r.top=r.bottom=r.left=r.right=e[0];break;case 2:r.top=r.bottom=e[0];r.left=r.right=e[1];break;case 3:r.top=e[0];r.bottom=e[2];r.left=r.right=e[1];break;case 4:r.top=e[0];r.left=e[1];r.bottom=e[2];r.right=e[3]}break;case"margin-top":r.top=getMeasurement(t);break;case"margin-bottom":r.bottom=getMeasurement(t);break;case"margin-left":r.left=getMeasurement(t);break;case"margin-right":r.right=getMeasurement(t);break;case"line-height":i=getMeasurement(t)}e.pushData(a,r,i);if(this[Wn])e.addString(this[Wn]);else for(const t of this[ss]())"#text"!==t[Os]?t[Rs](e):e.addString(t[Wn]);t&&e.popFont()}[Gs](e){const t=[];this[Vn]={children:t};this[_n]({});if(0===t.length&&!this[Wn])return HTMLResult.EMPTY;let a;a=this[qo]?this[Wn]?this[Wn].replaceAll(Go,"\n"):void 0:this[Wn]||void 0;return HTMLResult.success({name:this[Os],attributes:{href:this.href,style:mapStyle(this.style,this,this[qo])},children:t,value:a})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Rs](e){e.pushFont({weight:"bold"});super[Rs](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Gs](e){const t=super[Gs](e),{html:a}=t;if(!a)return HTMLResult.EMPTY;a.name="div";a.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Ws](){return"\n"}[Rs](e){e.addString("\n")}[Gs](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Gs](e){const t=[];this[Vn]={children:t};this[_n]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Wn]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Rs](e){e.pushFont({posture:"italic"});super[Rs](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Rs](e){super[Rs](e,!1);e.addString("\n");e.addPara();e.popFont()}[Ws](){return this[hs]()[ss]().at(-1)===this?super[Ws]():super[Ws]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[Ys](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const Ko={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[Ys](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[gs]=e}[Ms](e){this.element=e;return!0}[Kn](){super[Kn]();if(this.element.template instanceof Template){this[gs].set(js,this.element);this.element.template[_s](this[gs]);this.element.template[gs]=this[gs]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Ms](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(Zs).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:a,namespace:r,prefixes:i}){const n=null!==r;if(n){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(r)}i&&this._addNamespacePrefix(i);if(a.hasOwnProperty(Ts)){const e=Ko.datasets,t=a[Ts];let r=null;for(const[a,i]of Object.entries(t)){if(this._getNamespaceToUse(a)===e){r={xfa:i};break}}r?a[Ts]=r:delete a[Ts]}const s=this._getNamespaceToUse(e),o=s?.[Ys](t,a)||new Empty;o[Ss]()&&this._nsAgnosticLevel++;(n||i||o[Ss]())&&(o[qn]={hasNamespace:n,prefixes:i,nsAgnostic:o[Ss]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[a,{check:r}]of Object.entries(Zs))if(r(e)){t=Ko[a];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:a}of e){const e=this._searchNamespace(a);let r=this._namespacePrefixes.get(t);if(!r){r=[];this._namespacePrefixes.set(t,r)}r.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:a,nsAgnostic:r}=e;t&&(this._currentNamespace=this._namespaceStack.pop());a&&a.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));r&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=Sn;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===Sn){this._current[Kn]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[Pn]()?this._current[Bs](e,this._richText):this._whiteRegex.test(e)||this._current[Bs](e.trim())}onCdata(e){this._current[Bs](e)}_mkAttributes(e,t){let a=null,r=null;const i=Object.create({});for(const{name:n,value:s}of e)if("xmlns"===n)a?warn(`XFA - multiple namespace definition in <${t}>`):a=s;else if(n.startsWith("xmlns:")){const e=n.substring(6);r||(r=[]);r.push({prefix:e,value:s})}else{const e=n.indexOf(":");if(-1===e)i[n]=s;else{let t=i[Ts];t||(t=i[Ts]=Object.create(null));const[a,r]=[n.slice(0,e),n.slice(e+1)];(t[a]||=Object.create(null))[r]=s}}return[a,r,i]}_getNameAndPrefix(e,t){const a=e.indexOf(":");return-1===a?[e,null]:[e.substring(a+1),t?"":e.substring(0,a)]}onBeginElement(e,t,a){const[r,i,n]=this._mkAttributes(t,e),[s,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),c=this._builder.build({nsPrefix:o,name:s,attributes:n,namespace:r,prefixes:i});c[ds]=this._globalData;if(a){c[Kn]();this._current[Ms](c)&&c[Xs](this._ids);c[Un](this._builder)}else{this._stack.push(this._current);this._current=c}}onEndElement(e){const t=this._current;if(t[bs]()&&"string"==typeof t[Wn]){const e=new XFAParser;e._globalData=this._globalData;const a=e.parse(t[Wn]);t[Wn]=null;t[Ms](a)}t[Kn]();this._current=this._stack.pop();this._current[Ms](t)&&t[Xs](this._ids);t[Un](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[ds].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[$s]();return new Promise(((t,a)=>{const nextIteration=()=>{try{const a=e.next();a.done?t(a.value):setTimeout(nextIteration,0)}catch(e){a(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:a}=e.attributes.style;return[0,0,parseInt(t),parseInt(a)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[ds].images=e}setFonts(e){this.form[ds].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[ds].usedTypefaces){e=stripQuotes(e);this.form[ds].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[ds].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Os])){const e=XhtmlNamespace.body({});e[jn](t);t=e}const a=t[Gs]();if(!a.success)return null;const{html:r}=a,{attributes:i}=r;if(i){i.class&&(i.class=i.class.filter((e=>!e.startsWith("xfa"))));i.dir="auto"}return{html:r,str:t[Ws]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,a,r,i,n])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:a,structTreeRoot:r,baseUrl:i,attachments:n})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,a,r,i,n){const s=i?await this._getPageIndex(e,t,a.pdfManager):null;return a.pdfManager.ensure(this,"_create",[e,t,a,r,i,s,n])}static _create(e,t,a,r,i=!1,n=null,s=null){const o=e.fetchIfRef(t);if(!(o instanceof Dict))return;const{acroForm:c,pdfManager:l}=a,h=t instanceof Ref?t.toString():`annot_${r.createObjId()}`;let u=o.get("Subtype");u=u instanceof Name?u.name:null;const d={xref:e,ref:t,dict:o,subtype:u,id:h,annotationGlobals:a,collectFields:i,needAppearances:!i&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:l.evaluatorOptions,pageRef:s};switch(u){case"Link":return new LinkAnnotation(d);case"Text":return new TextAnnotation(d);case"Widget":let e=getInheritableProperty({dict:o,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(d);case"Btn":return new ButtonWidgetAnnotation(d);case"Ch":return new ChoiceWidgetAnnotation(d);case"Sig":return new SignatureWidgetAnnotation(d)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(d);case"Popup":return new PopupAnnotation(d);case"FreeText":return new FreeTextAnnotation(d);case"Line":return new LineAnnotation(d);case"Square":return new SquareAnnotation(d);case"Circle":return new CircleAnnotation(d);case"PolyLine":return new PolylineAnnotation(d);case"Polygon":return new PolygonAnnotation(d);case"Caret":return new CaretAnnotation(d);case"Ink":return new InkAnnotation(d);case"Highlight":return new HighlightAnnotation(d);case"Underline":return new UnderlineAnnotation(d);case"Squiggly":return new SquigglyAnnotation(d);case"StrikeOut":return new StrikeOutAnnotation(d);case"Stamp":return new StampAnnotation(d);case"FileAttachment":return new FileAttachmentAnnotation(d);default:i||warn(u?`Unimplemented annotation type "${u}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(d)}}static async _getPageIndex(e,t,a){try{const r=await e.fetchIfRefAsync(t);if(!(r instanceof Dict))return-1;const i=r.getRaw("P");if(i instanceof Ref)try{return await a.ensureCatalog("getPageIndex",[i])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(r.has("Kids"))return-1;const n=await a.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const a=e.getArray("QuadPoints");if(!Array.isArray(a)||0===a.length||a.length%8>0)return null;const r=[];for(let e=0,i=a.length/8;et[2]||st[3]))return null;r.push([{x:i,y:o},{x:n,y:o},{x:i,y:s},{x:n,y:s}])}return r}function getTransformMatrix(e,t,a){const[r,i,n,s]=Util.getAxialAlignedBoundingBox(t,a);if(r===n||i===s)return[1,0,0,1,e[0],e[1]];const o=(e[2]-e[0])/(n-r),c=(e[3]-e[1])/(s-i);return[o,0,0,c,e[0]-r*o,e[1]-i*c]}class Annotation{constructor(e){const{dict:t,xref:a,annotationGlobals:r}=e;this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const i=t.get("MK");this.setBorderAndBackgroundColors(i);this.setRotation(i,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const n=!!(this.flags&ee),s=!!(this.flags&te);if(r.structTreeRoot){let a=t.get("StructParent");a=Number.isInteger(a)&&a>=0?a:-1;r.structTreeRoot.addAnnotationIdToPage(e.pageRef,a)}this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&Z),noHTML:n&&s};if(e.collectFields){const r=t.get("Kids");if(Array.isArray(r)){const e=[];for(const t of r)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(a,t,ye);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_isViewable(e){return!this._hasFlag(e,K)&&!this._hasFlag(e,Q)}_isPrintable(e){return this._hasFlag(e,Y)&&!this._hasFlag(e,J)&&!this._hasFlag(e,K)}mustBeViewed(e,t){const a=e?.get(this.data.id)?.noView;return void 0!==a?!a:this.viewable&&!this._hasFlag(this.flags,J)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:a}=e,r=getInheritableProperty({dict:t,key:"DA"})||a.acroForm.get("DA");this._defaultAppearance="string"==typeof r?r:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&K&&"Annotation"!==this.constructor.name&&(this.flags^=K)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=Array.isArray(e)&&4===e.length?Util.normalizeRect(e):[0,0,0,0]}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const a=e[t];if(a instanceof Name)switch(a.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=a.name;continue}warn(`Ignoring invalid lineEnding: ${a}`)}}setRotation(e,t){this.rotation=0;let a=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(a)&&0!==a){a%=360;a<0&&(a+=360);a%90==0&&(this.rotation=a)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(a instanceof BaseStream){this.appearance=a;return}if(!(a instanceof Dict))return;const r=e.get("AS");if(!(r instanceof Name&&a.has(r.name)))return;const i=a.get(r.name);i instanceof BaseStream&&(this.appearance=i)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,a,r,i){const{hasOwnCanvas:n,id:s,rect:o}=this.data;let l=this.appearance;const h=!!(n&&a&c);if(h&&(o[0]===o[2]||o[1]===o[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!l){if(!h)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};l=new StringStream("");l.dict=new Dict}const u=l.dict,d=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],l),f=u.getArray("BBox")||[0,0,1,1],g=u.getArray("Matrix")||[1,0,0,1,0,0],p=getTransformMatrix(o,f,g),m=new OperatorList;let b;this.oc&&(b=await e.parseMarkedContentProps(this.oc,null));void 0!==b&&m.addOp(jt,["OC",b]);m.addOp($t,[s,o,p,g,h]);await e.getOperatorList({stream:l,task:t,resources:d,operatorList:m,fallbackFontDict:this._fallbackFontDict});m.addOp(Gt,[]);void 0!==b&&m.addOp(_t,[]);this.reset();return{opList:m,separateForm:!1,separateCanvas:h}}async save(e,t,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,a){if(!this.appearance)return;const r=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),i=[],n=[];let s=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){s||=t.transform.slice(-2);n.push(t.str);if(t.hasEOL){i.push(n.join("").trimEnd());n.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:r,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:a});this.reset();n.length&&i.push(n.join("").trimEnd());if(i.length>1||i[0]){const e=this.appearance.dict;this.data.textPosition=this._transformPoint(s,e.getArray("BBox"),e.getArray("Matrix"));this.data.textContent=i}}_transformPoint(e,t,a){const{rect:r}=this.data;t||=[0,0,1,1];a||=[1,0,0,1,0,0];const i=getTransformMatrix(r,t,a);i[4]-=r[0];i[5]-=r[1];e=Util.applyTransform(e,i);return Util.applyTransform(e,a)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let a=e;const r=new RefSet;e.objId&&r.put(e.objId);for(;a.has("Parent");){a=a.get("Parent");if(!(a instanceof Dict)||a.objId&&r.has(a.objId))break;a.objId&&r.put(a.objId);a.has("T")&&t.unshift(stringToPDFString(a.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.style=fe;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){const a=(t[2]-t[0])/2,r=(t[3]-t[1])/2;if(a>0&&r>0&&(e>a||e>r)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=fe;break;case"D":this.style=ge;break;case"B":this.style=pe;break;case"I":this.style=me;break;case"U":this.style=be}}setDashArray(e,t=!1){if(Array.isArray(e)){let a=!0,r=!0;for(const t of e){if(!(+t>=0)){a=!1;break}t>0&&(r=!1)}if(0===e.length||a&&!r){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const a=t.get("RT");this.data.replyType=a instanceof Name?a.name:V}let a=null;if(this.data.replyType===G){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;a=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;a=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=a instanceof Ref?a.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:a,fillColor:r,blendMode:i,strokeAlpha:n,fillAlpha:s,pointsCallback:o}){let c=Number.MAX_VALUE,l=Number.MAX_VALUE,h=Number.MIN_VALUE,u=Number.MIN_VALUE;const d=["q"];t&&d.push(t);a&&d.push(`${a[0]} ${a[1]} ${a[2]} RG`);r&&d.push(`${r[0]} ${r[1]} ${r[2]} rg`);let f=this.data.quadPoints;f||(f=[[{x:this.rectangle[0],y:this.rectangle[3]},{x:this.rectangle[2],y:this.rectangle[3]},{x:this.rectangle[0],y:this.rectangle[1]},{x:this.rectangle[2],y:this.rectangle[1]}]]);for(const e of f){const[t,a,r,i]=o(d,e);c=Math.min(c,t);h=Math.max(h,a);l=Math.min(l,r);u=Math.max(u,i)}d.push("Q");const g=new Dict(e),p=new Dict(e);p.set("Subtype",Name.get("Form"));const m=new StringStream(d.join(" "));m.dict=p;g.set("Fm0",m);const b=new Dict(e);i&&b.set("BM",Name.get(i));"number"==typeof n&&b.set("CA",n);"number"==typeof s&&b.set("ca",s);const y=new Dict(e);y.set("GS0",b);const w=new Dict(e);w.set("ExtGState",y);w.set("XObject",g);const x=new Dict(e);x.set("Resources",w);const S=this.data.rect=[c,l,h,u];x.set("BBox",S);this.appearance=new StringStream("/GS0 gs /Fm0 Do");this.appearance.dict=x;this._streams.push(this.appearance,m)}static async createNewAnnotation(e,t,a,r){const i=t.ref||=e.getNewTemporaryRef(),n=await this.createNewAppearanceStream(t,e,r),s=[];let o;if(n){const r=e.getNewTemporaryRef();o=this.createNewDict(t,e,{apRef:r});await writeObject(r,n,s,e);a.push({ref:r,data:s.join("")})}else o=this.createNewDict(t,e,{});Number.isInteger(t.parentTreeId)&&o.set("StructParent",t.parentTreeId);s.length=0;await writeObject(i,o,s,e);return{ref:i,data:s.join("")}}static async createNewPrintAnnotation(e,t,a,r){const i=await this.createNewAppearanceStream(a,t,r),n=this.createNewDict(a,t,{ap:i}),s=new this.prototype.constructor({dict:n,xref:t,annotationGlobals:e,evaluatorOptions:r.evaluatorOptions});a.ref&&(s.ref=s.refToReplace=a.ref);return s}}class WidgetAnnotation extends Annotation{constructor(e){super(e);const{dict:t,xref:a,annotationGlobals:r}=e,i=this.data;this._needAppearances=e.needAppearances;i.annotationType=$;void 0===i.fieldName&&(i.fieldName=this._constructFieldName(t));void 0===i.actions&&(i.actions=collectActions(a,t,ye));let n=getInheritableProperty({dict:t,key:"V",getArray:!0});i.fieldValue=this._decodeFormValue(n);const s=getInheritableProperty({dict:t,key:"DV",getArray:!0});i.defaultFieldValue=this._decodeFormValue(s);if(void 0===n&&r.xfaDatasets){const e=this._title.str;if(e){this._hasValueFromXFA=!0;i.fieldValue=n=r.xfaDatasets.getValue(e)}}void 0===n&&null!==i.defaultFieldValue&&(i.fieldValue=i.defaultFieldValue);i.alternativeText=stringToPDFString(t.get("TU")||"");this.setDefaultAppearance(e);i.hasAppearance||=this._needAppearances&&void 0!==i.fieldValue&&null!==i.fieldValue;const o=getInheritableProperty({dict:t,key:"FT"});i.fieldType=o instanceof Name?o.name:null;const c=getInheritableProperty({dict:t,key:"DR"}),l=r.acroForm.get("DR"),h=this.appearance?.dict.get("Resources");this._fieldResources={localResources:c,acroFormResources:l,appearanceResources:h,mergedResources:Dict.merge({xref:a,dictArray:[c,h,l],mergeSubDicts:!0})};i.fieldFlags=getInheritableProperty({dict:t,key:"Ff"});(!Number.isInteger(i.fieldFlags)||i.fieldFlags<0)&&(i.fieldFlags=0);i.readOnly=this.hasFieldFlag(ae);i.required=this.hasFieldFlag(re);i.hidden=this._hasFlag(i.annotationFlags,J)||this._hasFlag(i.annotationFlags,Q)}_decodeFormValue(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,Q)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return a;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const a=this.data.rect[2]-this.data.rect[0],r=this.data.rect[3]-this.data.rect[1],i=0===t||180===t?`0 0 ${a} ${r} re`:`0 0 ${r} ${a} re`;let n="";this.backgroundColor&&(n=`${getPdfColor(this.backgroundColor,!0)} ${i} f `);if(this.borderColor){n+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${i} S `}return n}async getOperatorList(e,t,a,r,i){if(r&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,a,r,i);const n=await this._getAppearance(e,t,a,i);if(this.appearance&&null===n)return super.getOperatorList(e,t,a,r,i);const s=new OperatorList;if(!this._defaultAppearance||null===n)return{opList:s,separateForm:!1,separateCanvas:!1};const o=!!(this.data.hasOwnCanvas&&a&c),l=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],h=getTransformMatrix(this.data.rect,l,[1,0,0,1,0,0]);let u;this.oc&&(u=await e.parseMarkedContentProps(this.oc,null));void 0!==u&&s.addOp(jt,["OC",u]);s.addOp($t,[this.data.id,this.data.rect,h,this.getRotationMatrix(i),o]);const d=new StringStream(n);await e.getOperatorList({stream:d,task:t,resources:this._fieldResources.mergedResources,operatorList:s});s.addOp(Gt,[]);void 0!==u&&s.addOp(_t,[]);return{opList:s,separateForm:!1,separateCanvas:o}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}async save(e,t,r){const i=r?.get(this.data.id);let n=i?.value,s=i?.rotation;if(n===this.data.fieldValue||void 0===n){if(!this._hasValueFromXFA&&void 0===s)return null;n||=this.data.fieldValue}if(void 0===s&&!this._hasValueFromXFA&&Array.isArray(n)&&Array.isArray(this.data.fieldValue)&&n.length===this.data.fieldValue.length&&n.every(((e,t)=>e===this.data.fieldValue[t])))return null;void 0===s&&(s=this.rotation);let o=null;if(!this._needAppearances){o=await this._getAppearance(e,t,h,r);if(null===o)return null}let c=!1;if(o?.needAppearances){c=!0;o=null}const{xref:l}=e,u=l.fetchIfRef(this.ref);if(!(u instanceof Dict))return null;const d=new Dict(l);for(const e of u.getKeys())"AP"!==e&&d.set(e,u.getRaw(e));const f={path:this.data.fieldName,value:n},encoder=e=>isAscii(e)?e:stringToUTF16String(e,!0);d.set("V",Array.isArray(n)?n.map(encoder):encoder(n));this.amendSavedDict(r,d);const g=this._getMKDict(s);g&&d.set("MK",g);const p=[],m=[{ref:this.ref,data:"",xfa:f,needAppearances:c}];if(null!==o){const e=l.getNewTemporaryRef(),t=new Dict(l);d.set("AP",t);t.set("N",e);const i=this._getSaveFieldResources(l),n=new StringStream(o),s=n.dict=new Dict(l);s.set("Subtype",Name.get("Form"));s.set("Resources",i);s.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const c=this.getRotationMatrix(r);c!==a&&s.set("Matrix",c);await writeObject(e,n,p,l);m.push({ref:e,data:p.join(""),xfa:null,needAppearances:!1});p.length=0}d.set("M",`D:${getModificationDate()}`);await writeObject(this.ref,d,p,l);m[0].data=p.join("");return m}async _getAppearance(e,t,a,r){if(this.hasFieldFlag(ne))return null;const i=r?.get(this.data.id);let n,o;if(i){n=i.formattedValue||i.value;o=i.rotation}if(void 0===o&&void 0===n&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const c=this.getBorderAndBackgroundAppearances(r);if(void 0===n){n=this.data.fieldValue;if(!n)return`/Tx BMC q ${c}Q EMC`}Array.isArray(n)&&1===n.length&&(n=n[0]);assert("string"==typeof n,"Expected `value` to be a string.");n=n.trim();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>n===e));n=e?.displayValue||n}if(""===n)return`/Tx BMC q ${c}Q EMC`;void 0===o&&(o=this.rotation);let l,u=-1;if(this.data.multiLine){l=n.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));u=l.length}else l=[n.replace(/\r\n?|\n/,"").normalize("NFC")];let d=this.data.rect[3]-this.data.rect[1],f=this.data.rect[2]-this.data.rect[0];90!==o&&270!==o||([f,d]=[d,f]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let g,p,m,b=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const y=[];let w=!1;for(const e of l){const t=b.encodeString(e);t.length>1&&(w=!0);y.push(t.join(""))}if(w&&a&h)return{needAppearances:!0};if(w&&this._isOffscreenCanvasSupported){const a=this.data.comb?"monospace":"sans-serif",r=new FakeUnicodeFont(e.xref,a),i=r.createFontResources(l.join("")),s=i.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of s.getKeys())e.set(t,s.getRaw(t))}else this._fieldResources.mergedResources.set("Font",s);const o=r.fontName.name;b=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},i);for(let e=0,t=y.length;e2)return`/Tx BMC q ${c}BT `+g+` 1 0 0 1 ${numberToString(2)} ${numberToString(C)} Tm (${escapeString(y[0])}) Tj ET Q EMC`;return`/Tx BMC q ${c}BT `+g+` 1 0 0 1 0 0 Tm ${this._renderText(y[0],b,p,f,k,{shift:0},2,C)} ET Q EMC`}static async _getFontData(e,t,a,r){const i=new OperatorList,n={font:null,clone(){return this}},{fontName:s,fontSize:o}=a;await e.handleSetFont(r,[s&&Name.get(s),o],null,i,t,n,null);return n.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,a,r,n){let{fontSize:s}=this.data.defaultAppearanceData,o=(s||12)*i,c=Math.round(e/o);if(!s){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===n){const n=this._getTextWidth(a,r);s=roundWithTwoDigits(Math.min(e/i,n>t?t/n:1/0));c=1}else{const l=a.split(/\r\n?|\n/),h=[];for(const e of l){const t=r.encodeString(e).join(""),a=r.charsToGlyphs(t),i=r.getCharPositions(t);h.push({line:t,glyphs:a,positions:i})}const isTooBig=a=>{let i=0;for(const n of h){i+=this._splitLine(null,r,a,t,n).length*a;if(i>e)return!0}return!1};c=Math.max(c,n);for(;;){o=e/c;s=roundWithTwoDigits(o/i);if(!isTooBig(s))break;c++}}const{fontName:l,fontColor:h}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:a}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(a,!0)}`}({fontSize:s,fontName:l,fontColor:h})}return[this._defaultAppearance,s,e/c]}_renderText(e,t,a,r,i,n,s,o){let c;if(1===i){c=(r-this._getTextWidth(e,t)*a)/2}else if(2===i){c=r-this._getTextWidth(e,t)*a-s}else c=s;const l=numberToString(c-n.shift);n.shift=c;return`${l} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:a,acroFormResources:r}=this._fieldResources,i=this.data.defaultAppearanceData?.fontName;if(!i)return t||Dict.empty;for(const e of[t,a])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(i))return e}if(r instanceof Dict){const a=r.get("Font");if(a instanceof Dict&&a.has(i)){const r=new Dict(e);r.set(i,a.getRaw(i));const n=new Dict(e);n.set("Font",r);return Dict.merge({xref:e,dictArray:[n,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;const t=e.dict;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let a=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(a)||a<0||a>2)&&(a=null);this.data.textAlignment=a;let r=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(r)||r<0)&&(r=0);this.data.maxLen=r;this.data.multiLine=this.hasFieldFlag(ie);this.data.comb=this.hasFieldFlag(de)&&!this.hasFieldFlag(ie)&&!this.hasFieldFlag(ne)&&!this.hasFieldFlag(le)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(ue)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,a,r,i,n,s,o,c,l,h){const u=i/this.data.maxLen,d=this.getBorderAndBackgroundAppearances(h),f=[],g=t.getCharPositions(a);for(const[e,t]of g)f.push(`(${escapeString(a.substring(e,t))}) Tj`);const p=f.join(` ${numberToString(u)} 0 Td `);return`/Tx BMC q ${d}BT `+e+` 1 0 0 1 ${numberToString(s)} ${numberToString(o+c)} Tm ${p} ET Q EMC`}_getMultilineAppearance(e,t,a,r,i,n,s,o,c,l,h,u){const d=[],f=i-2*o,g={shift:0};for(let e=0,n=t.length;er){c.push(e.substring(d,a));d=a;f=p;l=-1;u=-1}else{f+=p;l=a;h=i;u=t}else if(f+p>r)if(-1!==l){c.push(e.substring(d,h));d=h;t=u+1;l=-1;f=0}else{c.push(e.substring(d,a));d=a;f=p}else f+=p}d"Off"!==e));n.length=0;n.push("Off",e)}n.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=n[1];const s=a.get(this.data.exportValue);this.checkedAppearance=s instanceof BaseStream?s:null;const o=a.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const a=t.get("V");a instanceof Name&&(this.data.fieldValue=this._decodeFormValue(a))}const a=e.dict.get("AP");if(!(a instanceof Dict))return;const r=a.get("N");if(!(r instanceof Dict))return;for(const e of r.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const i=r.get(this.data.buttonValue);this.checkedAppearance=i instanceof BaseStream?i:null;const n=r.get("Off");this.uncheckedAppearance=n instanceof BaseStream?n:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:a}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:a.baseUrl,docAttachments:a.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const r=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(r))for(let e=0,t=r.length;e=0&&t0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let a=e?.get(this.data.id)?.value;Array.isArray(a)||(a=[a]);const r=[],{options:i}=this.data;for(let e=0,t=0,n=i.length;ea){a=r;t=e}}[f,g]=this._computeFontSize(e,l-4,t,d,-1)}const p=g*i,m=(p-g)/2,b=Math.floor(c/p);let y=0;if(u.length>0){const e=Math.min(...u),t=Math.max(...u);y=Math.max(0,t-b+1);y>e&&(y=e)}const w=Math.min(y+b+1,h),x=["/Tx BMC q",`1 1 ${l} ${c} re W n`];if(u.length){x.push("0.600006 0.756866 0.854904 rg");for(const e of u)y<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:a}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,r);this.data.textPosition=this._transformPoint(e,t,a)}if(this._isOffscreenCanvasSupported){const i=e.dict.get("CA"),n=new FakeUnicodeFont(a,"sans-serif");this.appearance=n.createAppearance(this._contents.str,this.rectangle,this.rotation,r,t,i);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,fontSize:n,rect:s,rotation:o,user:c,value:l}=e,h=new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",s);const u=`/Helv ${n} Tf ${getPdfColor(i,!0)}`;h.set("DA",u);h.set("Contents",isAscii(l)?l:stringToUTF16String(l,!0));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);c&&h.set("T",isAscii(c)?c:stringToUTF16String(c,!0));if(a||r){const e=new Dict(t);h.set("AP",e);a?e.set("N",a):e.set("N",r)}return h}static async createNewAppearanceStream(e,t,a){const{baseFontRef:r,evaluator:n,task:s}=a,{color:o,fontSize:c,rect:l,rotation:h,value:u}=e,d=new Dict(t),f=new Dict(t);if(r)f.set("Helv",r);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));f.set("Helv",e)}d.set("Font",f);const g=await WidgetAnnotation._getFontData(n,s,{fontName:"Helv",fontSize:c},d),[p,m,b,y]=l;let w=b-p,x=y-m;h%180!=0&&([w,x]=[x,w]);const S=u.split("\n"),k=c/1e3;let C=-1/0;const v=[];for(let e of S){const t=g.encodeString(e);if(t.length>1)return null;e=t.join("");v.push(e);let a=0;const r=g.charsToGlyphs(e);for(const e of r)a+=e.width*k;C=Math.max(C,a)}let F=1;C>w&&(F=w/C);let O=1;const T=i*c,M=1*c,D=T*S.length;D>x&&(O=x/D);const R=c*Math.min(F,O);let N,E,L;switch(h){case 0:L=[1,0,0,1];E=[l[0],l[1],w,x];N=[l[0],l[3]-M];break;case 90:L=[0,1,-1,0];E=[l[1],-l[2],w,x];N=[l[1],-l[0]-M];break;case 180:L=[-1,0,0,-1];E=[-l[2],-l[3],w,x];N=[-l[2],-l[1]-M];break;case 270:L=[0,-1,1,0];E=[-l[3],l[0],w,x];N=[-l[3],l[2]-M]}const j=["q",`${L.join(" ")} 0 0 cm`,`${E.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(R)} Tf`];j.push(`${N.join(" ")} Td (${escapeString(v[0])}) Tj`);const _=numberToString(T);for(let e=1,t=v.length;e{e.push(`${r[0]} ${r[1]} m`,`${r[2]} ${r[3]} l`,"S");return[t[0].x-c,t[1].x+c,t[3].y-c,t[1].y+c]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA"),i=getRgbColor(t.getArray("IC"),null),n=i?getPdfColorArray(i):null,s=n?r:null;if(0===this.borderStyle.width&&!n)return;this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:n,strokeAlpha:r,fillAlpha:s,pointsCallback:(e,t)=>{const a=t[2].x+this.borderStyle.width/2,r=t[2].y+this.borderStyle.width/2,i=t[3].x-t[2].x-this.borderStyle.width,s=t[1].y-t[3].y-this.borderStyle.width;e.push(`${a} ${r} ${i} ${s} re`);n?e.push("B"):e.push("S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=R;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA"),i=getRgbColor(t.getArray("IC"),null),n=i?getPdfColorArray(i):null,s=n?r:null;if(0===this.borderStyle.width&&!n)return;const o=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:n,strokeAlpha:r,fillAlpha:s,pointsCallback:(e,t)=>{const a=t[0].x+this.borderStyle.width/2,r=t[0].y-this.borderStyle.width/2,i=t[3].x-this.borderStyle.width/2,s=t[3].y+this.borderStyle.width/2,c=a+(i-a)/2,l=r+(s-r)/2,h=(i-a)/2*o,u=(s-r)/2*o;e.push(`${c} ${s} m`,`${c+h} ${s} ${i} ${l+u} ${i} ${l} c`,`${i} ${l-u} ${c+h} ${r} ${c} ${r} c`,`${c-h} ${r} ${a} ${l-u} ${a} ${l} c`,`${a} ${l+u} ${c-h} ${s} ${c} ${s} c`,"h");n?e.push("B"):e.push("S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=E;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=[];if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const r=t.getArray("Vertices");if(Array.isArray(r)){for(let e=0,t=r.length;e{const a=this.data.vertices;for(let t=0,r=a.length;t{for(const t of this.data.inkLists){for(let a=0,r=t.length;ae.points)));u.set("F",4);u.set("Rotate",l);o&&u.set("IT",Name.get("InkHighlight"));const d=new Dict(t);u.set("BS",d);d.set("W",h);u.set("C",Array.from(i,(e=>e/255)));u.set("CA",n);const f=new Dict(t);u.set("AP",f);a?f.set("N",a):f.set("N",r);return u}static async createNewAppearanceStream(e,t,a){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,a);const{color:r,rect:i,paths:n,thickness:s,opacity:o}=e,c=[`${s} w 1 J 1 j`,`${getPdfColor(r,!1)}`];1!==o&&c.push("/R0 gs");const l=[];for(const{bezier:e}of n){l.length=0;l.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);if(2===e.length)l.push(`${numberToString(e[0])} ${numberToString(e[1])} l S`);else{for(let t=2,a=e.length;t{e.push(`${t[0].x} ${t[0].y} m`,`${t[1].x} ${t[1].y} l`,`${t[3].x} ${t[3].y} l`,`${t[2].x} ${t[2].y} l`,"f");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,opacity:n,rect:s,rotation:o,user:c,quadPoints:l}=e,h=new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",s);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",o);h.set("QuadPoints",l);h.set("C",Array.from(i,(e=>e/255)));h.set("CA",n);c&&h.set("T",isAscii(c)?c:stringToUTF16String(c,!0));if(a||r){const e=new Dict(t);h.set("AP",e);e.set("N",a||r)}return h}static async createNewAppearanceStream(e,t,a){const{color:r,rect:i,outlines:n,opacity:s}=e,o=[`${getPdfColor(r,!0)}`,"/R0 gs"],c=[];for(const e of n){c.length=0;c.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,a=e.length;t{e.push(`${t[2].x} ${t[2].y+1.3} m`,`${t[3].x} ${t[3].y+1.3} l`,"S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=_;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],r=t.get("CA");this._setDefaultAppearance({xref:a,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:r,pointsCallback:(e,t)=>{const a=(t[0].y-t[2].y)/6;let r=a,i=t[2].x;const n=t[2].y,s=t[3].x;e.push(`${i} ${n+r} m`);do{i+=2;r=0===r?a:0;e.push(`${i} ${n+r} l`)}while(i{e.push((t[0].x+t[2].x)/2+" "+(t[0].y+t[2].y)/2+" m",(t[1].x+t[3].x)/2+" "+(t[1].y+t[3].y)/2+" l","S");return[t[0].x,t[1].x,t[3].y,t[1].y]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{constructor(e){super(e);this.data.annotationType=X;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1}static async createImage(e,t){const{width:a,height:r}=e,i=new OffscreenCanvas(a,r),n=i.getContext("2d",{alpha:!0});n.drawImage(e,0,0);const s=n.getImageData(0,0,a,r).data,o=new Uint32Array(s.buffer),c=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>255!=(255&e));if(c){n.fillStyle="white";n.fillRect(0,0,a,r);n.drawImage(e,0,0)}const l=i.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),h=Name.get("XObject"),u=Name.get("Image"),d=new Dict(t);d.set("Type",h);d.set("Subtype",u);d.set("BitsPerComponent",8);d.set("ColorSpace",Name.get("DeviceRGB"));d.set("Filter",Name.get("DCTDecode"));d.set("BBox",[0,0,a,r]);d.set("Width",a);d.set("Height",r);let f=null;if(c){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,a=o.length;t>>24;else for(let t=0,a=o.length;t=0&&n<=1?n:null}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const a=t.firstChild;return"value"===a?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#P=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[s,o]=n;if(!Number.isInteger(s)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${s}, ${o}`);if(!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(i))throw new FormatError(`Invalid XRef entry fields length: ${s}, ${o}`);for(let n=t.entryNum;n=e.length);){a+=String.fromCharCode(r);r=e[t]}return a}function skipUntil(e,t,a){const r=a.length,i=e.length;let n=0;for(;t=r)break;t++;n++}return n}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,r=new Uint8Array([116,114,97,105,108,101,114]),i=new Uint8Array([115,116,97,114,116,120,114,101,102]),n=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const s=this.stream;s.pos=0;const o=s.getBytes(),c=bytesToString(o),l=o.length;let h=s.start;const u=[],d=[];for(;h=l)break;f=o[h]}while(10!==f&&13!==f);continue}const g=readToken(o,h);let p;if(g.startsWith("xref")&&(4===g.length||/\s/.test(g[4]))){h+=skipUntil(o,h,r);u.push(h);h+=skipUntil(o,h,i)}else if(p=a.exec(g)){const t=0|p[1],a=0|p[2],r=h+g.length;let i,u=!1;if(this.entries[t]){if(this.entries[t].gen===a)try{new Parser({lexer:new Lexer(s.makeSubStream(r))}).getObj();u=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${g}): "${e}".`):u=!0}}else u=!0;u&&(this.entries[t]={offset:h-s.start,gen:a,uncompressed:!0});e.lastIndex=r;const f=e.exec(c);if(f){i=e.lastIndex+1-h;if("endobj"!==f[1]){warn(`indexObjects: Found "${f[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);i-=f[1].length+1}}else i=l-h;const m=o.subarray(h,h+i),b=skipUntil(m,0,n);if(b0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const a=e.num,r=this._cacheMap.get(a);if(void 0!==r){r instanceof Dict&&!r.objId&&(r.objId=e.toString());return r}let i=this.getEntry(a);if(null===i){this._cacheMap.set(a,i);return i}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return ua}this._pendingRefs.put(e);try{i=i.uncompressed?this.fetchUncompressed(e,i,t):this.fetchCompressed(e,i,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}i instanceof Dict?i.objId=e.toString():i instanceof BaseStream&&(i.dict.objId=e.toString());return i}fetchUncompressed(e,t,a=!1){const r=e.gen;let i=e.num;if(t.gen!==r){const n=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||Jo)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){let e=this.pageDict.get("UserUnit");("number"!=typeof e||e<=0)&&(e=1);return shadow(this,"userUnit",e)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const a=Util.intersect(e,t);if(a&&a[2]-a[0]>0&&a[3]-a[1]>0)return shadow(this,"view",a);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}#L(e,t,a){for(const r of e)if(r.id){const e=Ref.fromString(r.id);if(!e){warn(`A non-linked annotation cannot be modified: ${r.id}`);continue}if(r.deleted){t.put(e);continue}a?.put(e);r.ref=e;delete r.id}}async saveNewAnnotations(e,t,a,r){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const i=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSet,s=new RefSet;this.#L(a,n,s);const o=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),l=await AnnotationFactory.saveNewAnnotations(i,t,a,r);for(const{ref:e}of l.annotations)e instanceof Ref&&!s.has(e)&&c.push(e);const h=o.get("Annots");o.set("Annots",c);const u=[];await writeObject(this.ref,o,u,this.xref);h&&o.set("Annots",h);const d=l.dependencies;d.push({ref:this.ref,data:u.join("")},...l.annotations);return d}save(e,t,a){const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const i=[];for(const n of e)n.mustBePrinted(a)&&i.push(n.save(r,t,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(i).then((function(e){return e.filter((e=>!!e))}))}))}loadResources(e){this.resourcesPromise||(this.resourcesPromise=this.pdfManager.ensure(this,"resources"));return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:a,intent:r,cacheKey:i,annotationStorage:n=null}){const s=this.getContentStream(),h=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),f=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),p=this.xfaFactory?null:getNewAnnotationsMap(n);let m=null,b=Promise.resolve(null);if(p){const e=p.get(this.pageIndex);if(e){const t=this.pdfManager.ensureDoc("annotationGlobals");let r;const i=new Set;for(const{bitmapId:t,bitmap:a}of e)!t||a||i.has(t)||i.add(t);const{isOffscreenCanvasSupported:s}=this.evaluatorOptions;if(i.size>0){const t=e.slice();for(const[e,a]of n)e.startsWith(g)&&a.bitmap&&i.has(a.bitmapId)&&t.push(a);r=AnnotationFactory.generateImages(t,this.xref,s)}else r=AnnotationFactory.generateImages(e,this.xref,s);m=new RefSet;this.#L(e,m,null);b=t.then((t=>t?AnnotationFactory.printNewAnnotations(t,f,a,e,r):null))}}const y=Promise.all([s,h]).then((([n])=>{const s=new OperatorList(r,t);e.send("StartRenderPage",{transparency:f.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:i});return f.getOperatorList({stream:n,task:a,resources:this.resources,operatorList:s}).then((function(){return s}))}));return Promise.all([y,this._parsedAnnotations,b]).then((function([e,t,i]){if(i){t=t.filter((e=>!(e.ref&&m.has(e.ref))));for(let e=0,a=i.length;ee.ref&&isRefsEqual(e.ref,r.refToReplace)));if(n>=0){t.splice(n,1,r);i.splice(e--,1);a--}}}t=t.concat(i)}if(0===t.length||r&d){e.flush(!0);return{length:e.totalLength}}const s=!!(r&u),h=!!(r&o),g=!!(r&c),p=!!(r&l),b=[];for(const e of t)(h||g&&e.mustBeViewed(n,s)||p&&e.mustBePrinted(n))&&b.push(e.getOperatorList(f,a,r,s,n).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${a.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(b).then((function(t){let a=!1,r=!1;for(const{opList:i,separateForm:n,separateCanvas:s}of t){e.addOpList(i);a||=n;r||=s}e.flush(!0,{form:a,canvas:r});return{length:e.totalLength}}))}))}extractTextContent({handler:e,task:t,includeMarkedContent:a,disableNormalization:r,sink:i}){const n=this.getContentStream(),s=this.loadResources(["ExtGState","Font","Properties","XObject"]);return Promise.all([n,s]).then((([n])=>new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:n,task:t,resources:this.resources,includeMarkedContent:a,disableNormalization:r,sink:i,viewBox:this.view})))}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;return(await this.pdfManager.ensure(this,"_parseStructTree",[e])).serializable}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,a){const r=await this._parsedAnnotations;if(0===r.length)return r;const i=[],n=[];let s;const h=!!(a&o),u=!!(a&c),d=!!(a&l);for(const a of r){const r=h||u&&a.viewable;(r||d&&a.printable)&&i.push(a.data);if(a.hasTextContent&&r){s||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});n.push(a.extractTextContent(s,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(n);return i}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const t=await this.pdfManager.ensureDoc("annotationGlobals");if(!t)return[];const a=[];for(const r of e)a.push(AnnotationFactory.create(this.xref,r,t,this._localIdFactory,!1,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const r=[];let i,n;for(const e of await Promise.all(a))e&&(e instanceof WidgetAnnotation?(n||=[]).push(e):e instanceof PopupAnnotation?(i||=[]).push(e):r.push(e));n&&r.push(...n);i&&r.push(...i);return r})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,xe))}}const Yo=new Uint8Array([37,80,68,70,45]),Zo=new Uint8Array([115,116,97,114,116,120,114,101,102]),Qo=new Uint8Array([101,110,100,111,98,106]);function find(e,t,a=1024,r=!1){const i=t.length,n=e.peekBytes(a),s=n.length-i;if(s<=0)return!1;if(r){const a=i-1;let r=n.length-1;for(;r>=a;){let s=0;for(;s=i){e.pos+=r-a;return!0}r--}}else{let a=0;for(;a<=s;){let r=0;for(;r=i){e.pos+=a;return!0}a++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const a={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++a.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,Qo)){e.skip(6);let a=e.peekByte();for(;isWhiteSpace(a);){e.pos++;a=e.peekByte()}t=e.pos-e.start}}else{const a=1024,r=Zo.length;let i=!1,n=e.end;for(;!i&&n>0;){n-=a-r;n<0&&(n=0);e.pos=n;i=find(e,Zo,a,!0)}if(i){e.skip(9);let a;do{a=e.getByte()}while(isWhiteSpace(a));let r="";for(;a>=32&&a<=57;){r+=String.fromCharCode(a);a=e.getByte()}t=parseInt(r,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,Yo))return;e.moveStart();e.skip(Yo.length);let t,a="";for(;(t=e.getByte())>32&&a.length<7;)a+=String.fromCharCode(t);ba.test(a)?this._version=a:warn(`Invalid PDF header version: ${a}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const a=isName(e.get("FT"),"Sig"),r=e.get("Rect"),i=Array.isArray(r)&&r.every((e=>0===e));return a&&i}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),a={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){a["xdp:xdp"]=t;return a}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,r=t.length;e{u.set(e,t)}));const d=[];for(const[e,a]of u){const i=a.get("FontDescriptor");if(!(i instanceof Dict))continue;let n=i.get("FontFamily");n=n.replaceAll(/[ ]+(\d)/g,"$1");const s={fontFamily:n,fontWeight:i.get("FontWeight"),italicAngle:-i.get("ItalicAngle")};validateCSSFont(s)&&d.push(o.handleSetFont(r,[Name.get(e),1],null,c,t,h,null,s).catch((function(e){warn(`loadXfaFonts: "${e}".`);return null})))}await Promise.all(d);const f=this.xfaFactory.setFonts(l);if(!f)return;s.ignoreErrors=!0;d.length=0;l.length=0;const g=new Set;for(const e of f)getXfaFontName(`${e}-Regular`)||g.add(e);g.size&&f.push("PdfJS-Fallback");for(const e of f)if(!g.has(e))for(const a of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const i=`${e}-${a.name}`,n=getXfaFontDict(i);d.push(o.handleSetFont(r,[Name.get(i),1],null,c,t,h,n,{fontFamily:e,fontWeight:a.fontWeight,italicAngle:a.italicAngle}).catch((function(e){warn(`loadXfaFonts: "${e}".`);return null})))}await Promise.all(d);this.xfaFactory.appendFonts(l,g)}async serializeXfaData(e){return this.xfaFactory?this.xfaFactory.serializeData(e):null}get version(){return this.catalog.version||this._version}get formInfo(){const e={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},t=this.catalog.acroForm;if(!t)return shadow(this,"formInfo",e);try{const a=t.get("Fields"),r=Array.isArray(a)&&a.length>0;e.hasFields=r;const i=t.get("XFA");e.hasXfa=Array.isArray(i)&&i.length>0||i instanceof BaseStream&&!i.isEmpty;const n=!!(1&t.get("SigFlags")),s=n&&this._hasOnlyDocumentSignatures(a);e.hasAcroForm=r&&!s;e.hasSignatures=n}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const a of t.getKeys()){const r=t.get(a);switch(a){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof r){e[a]=stringToPDFString(r);continue}break;case"Trapped":if(r instanceof Name){e[a]=r;continue}break;default:let t;switch(typeof r){case"string":t=stringToPDFString(r);break;case"number":case"boolean":t=r;break;default:r instanceof Name&&(t=r)}if(void 0===t){warn(`Bad value, for custom key "${a}", in Info: ${r}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[a]=t;continue}warn(`Bad value, for key "${a}", in Info: ${r}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){function validate(e){return"string"==typeof e&&e.length>0&&"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"!==e}function hexString(e){const t=[];for(const a of e){const e=a.toString(16);t.push(e.padStart(2,"0"))}return t.join("")}const e=this.xref.trailer.get("ID");let t,a;if(Array.isArray(e)&&validate(e[0])){t=stringToBytes(e[0]);e[1]!==e[0]&&validate(e[1])&&(a=stringToBytes(e[1]))}else t=On(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[hexString(t),a?hexString(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:a,xref:r}=this,i=Ref.get(a.objectNumberFirst,0);try{const e=await r.fetchAsync(i);if(e instanceof Dict){let a=e.getRaw("Type");a instanceof Ref&&(a=await r.fetchAsync(a));if(isName(a,"Page")||!e.has("Type")&&!e.has("Kids")){t.pageKidsCountCache.has(i)||t.pageKidsCountCache.put(i,1);t.pageIndexCache.has(i)||t.pageIndexCache.put(i,0);return[e,i]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(a){warn(`_getLinearizationPage: "${a.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:a,linearization:r,xfaFactory:i}=this;let n;n=i?Promise.resolve([Dict.empty,null]):r?.pageFirst===e?this._getLinearizationPage(e):a.getPageDict(e);n=n.then((([t,r])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:r,globalIdFactory:this._globalIdFactory,fontCache:a.fontCache,builtInCMapCache:a.builtInCMapCache,standardFontDataCache:a.standardFontDataCache,globalImageCache:a.globalImageCache,systemFontCache:a.systemFontCache,nonBlendModesSet:a.nonBlendModesSet,xfaFactory:i})));this._pagePromises.set(e,n);return n}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:a}=this;t.setActualNumPages();let r;try{await Promise.all([a.ensureDoc("xfaFactory"),a.ensureDoc("linearization"),a.ensureCatalog("numPages")]);if(this.xfaFactory)return;r=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(r))throw new FormatError("Page count is not an integer.");if(r<=1)return;await this.getPage(r-1)}catch(i){this._pagePromises.delete(r-1);await this.cleanup();if(i instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${r}.`);let n;try{n=await t.getAllPageDicts(e)}catch(a){if(a instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[r,i]]of n){let n;if(r instanceof Error){n=Promise.reject(r);n.catch((()=>{}))}else n=Promise.resolve(new Page({pdfManager:a,xref:this.xref,pageIndex:e,pageDict:r,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,n)}t.setActualNumPages(n.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#j(e,t,a,r,i){const{xref:n}=this;if(!(t instanceof Ref)||i.has(t))return;i.put(t);const s=await n.fetchAsync(t);if(!(s instanceof Dict))return;if(s.has("T")){const t=stringToPDFString(await s.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let t=s;for(;;){t=t.getRaw("Parent");if(t instanceof Ref){if(i.has(t))break;t=await n.fetchAsync(t)}if(!(t instanceof Dict))break;if(t.has("T")){const a=stringToPDFString(await t.getAsync("T"));e=""===e?a:`${e}.${a}`;break}}}a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(n,t,r,null,!0,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!s.has("Kids"))return;const o=await s.getAsync("Kids");if(Array.isArray(o))for(const t of o)await this.#j(e,t,a,r,i)}get fieldObjects(){if(!this.formInfo.hasFields)return shadow(this,"fieldObjects",Promise.resolve(null));return shadow(this,"fieldObjects",Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]).then((async([e,t])=>{if(!e)return null;const a=new RefSet,r=Object.create(null),i=new Map;for(const r of await t.getAsync("Fields"))await this.#j("",r,i,e,a);const n=[];for(const[e,t]of i)n.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(r[e]=t)})));await Promise.all(n);return r})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm;if(!e?.has("CO"))return shadow(this,"calculationOrderIds",null);const t=e.get("CO");if(!Array.isArray(t)||0===t.length)return shadow(this,"calculationOrderIds",null);const a=[];for(const e of t)e instanceof Ref&&a.push(e.toString());return 0===a.length?shadow(this,"calculationOrderIds",null):shadow(this,"calculationOrderIds",a)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this.constructor===BasePdfManager&&unreachable("Cannot initialize BasePdfManager.");this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;this.evaluatorOptions=e.evaluatorOptions}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,a){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,a){const r=e[t];return"function"==typeof r?r.apply(e,a):r}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,a){try{const r=e[t];return"function"==typeof r?r.apply(e,a):r}catch(r){if(!(r instanceof MissingDataException))throw r;await this.requestRange(r.begin,r.end);return this.ensure(e,t,a)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const ec=1,tc=2,ac=1,rc=2,ic=3,nc=4,sc=5,oc=6,cc=7,lc=8;function wrapReason(e){e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details);default:return new UnknownErrorException(e.message,e.toString())}}class MessageHandler{constructor(e,t,a){this.sourceName=e;this.targetName=t;this.comObj=a;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);this._onComObjOnMessage=e=>{const t=e.data;if(t.targetName!==this.sourceName)return;if(t.stream){this.#_(t);return}if(t.callback){const e=t.callbackId,a=this.callbackCapabilities[e];if(!a)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ec)a.resolve(t.data);else{if(t.callback!==tc)throw new Error("Unexpected callback case");a.reject(wrapReason(t.reason))}return}const r=this.actionHandler[t.action];if(!r)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const e=this.sourceName,i=t.sourceName;new Promise((function(e){e(r(t.data))})).then((function(r){a.postMessage({sourceName:e,targetName:i,callback:ec,callbackId:t.callbackId,data:r})}),(function(r){a.postMessage({sourceName:e,targetName:i,callback:tc,callbackId:t.callbackId,reason:wrapReason(r)})}))}else t.streamId?this.#U(t):r(t.data)};a.addEventListener("message",this._onComObjOnMessage)}on(e,t){const a=this.actionHandler;if(a[e])throw new Error(`There is already an actionName called "${e}"`);a[e]=t}send(e,t,a){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},a)}sendWithPromise(e,t,a){const r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},a)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,a,r){const i=this.streamId++,n=this.sourceName,s=this.targetName,o=this.comObj;return new ReadableStream({start:a=>{const c=Promise.withResolvers();this.streamControllers[i]={controller:a,startCall:c,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:n,targetName:s,action:e,streamId:i,data:t,desiredSize:a.desiredSize},r);return c.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[i].pullCall=t;o.postMessage({sourceName:n,targetName:s,stream:oc,streamId:i,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[i].cancelCall=t;this.streamControllers[i].isClosed=!0;o.postMessage({sourceName:n,targetName:s,stream:ac,streamId:i,reason:wrapReason(e)});return t.promise}},a)}#U(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this,s=this.actionHandler[e.action],o={enqueue(e,n=1,s){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=n;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}i.postMessage({sourceName:a,targetName:r,stream:nc,streamId:t,chunk:e},s)},close(){if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:ic,streamId:t});delete n.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:sc,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;new Promise((function(t){t(s(e.data,o))})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:lc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:lc,streamId:t,reason:wrapReason(e)})}))}#_(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this.streamControllers[t],s=this.streamSinks[t];switch(e.stream){case lc:e.success?n.startCall.resolve():n.startCall.reject(wrapReason(e.reason));break;case cc:e.success?n.pullCall.resolve():n.pullCall.reject(wrapReason(e.reason));break;case oc:if(!s){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,success:!0});break}s.desiredSize<=0&&e.desiredSize>0&&s.sinkCapability.resolve();s.desiredSize=e.desiredSize;new Promise((function(e){e(s.onPull?.())})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:cc,streamId:t,reason:wrapReason(e)})}));break;case nc:assert(n,"enqueue should have stream controller");if(n.isClosed)break;n.controller.enqueue(e.chunk);break;case ic:assert(n,"close should have stream controller");if(n.isClosed)break;n.isClosed=!0;n.controller.close();this.#X(n,t);break;case sc:assert(n,"error should have stream controller");n.controller.error(wrapReason(e.reason));this.#X(n,t);break;case rc:e.success?n.cancelCall.resolve():n.cancelCall.reject(wrapReason(e.reason));this.#X(n,t);break;case ac:if(!s)break;new Promise((function(t){t(s.onCancel?.(wrapReason(e.reason)))})).then((function(){i.postMessage({sourceName:a,targetName:r,stream:rc,streamId:t,success:!0})}),(function(e){i.postMessage({sourceName:a,targetName:r,stream:rc,streamId:t,reason:wrapReason(e)})}));s.sinkCapability.reject(wrapReason(e.reason));s.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#X(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const a=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(a);return a}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,a){this._msgHandler=a;this.onProgress=null;const r=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=r.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static setup(e,t){let a=!1;e.on("test",(function(t){if(!a){a=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(function(e){!function setVerbosityLevel(e){Number.isInteger(e)&&(na=e)}(e.verbosity)}));e.on("GetDocRequest",(function(e){return WorkerMessageHandler.createDocumentHandler(e,t)}))}static createDocumentHandler(e,t){let a,r=!1,i=null;const n=new Set,s=getVerbosityLevel(),{docId:o,apiVersion:c}=e,l="4.1.392";if(c!==l)throw new Error(`The API version "${c}" does not match the Worker version "${l}".`);const h=[];for(const e in[])h.push(e);if(h.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+h.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const u=o+"_worker";let d=new MessageHandler(u,o,t);function ensureNotTerminated(){if(r)throw new Error("Worker was terminated")}function startWorkerTask(e){n.add(e)}function finishWorkerTask(e){e.finish();n.delete(e)}async function loadDocument(e){await a.ensureDoc("checkHeader");await a.ensureDoc("parseStartXRef");await a.ensureDoc("parse",[e]);await a.ensureDoc("checkFirstPage",[e]);await a.ensureDoc("checkLastPage",[e]);const t=await a.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([a.loadXfaFonts(d,e).catch((e=>{})).then((()=>finishWorkerTask(e))),a.loadXfaImages()])}const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("fingerprints")]);return{numPages:r,fingerprints:i,htmlForXfa:t?await a.ensureDoc("htmlForXfa"):null}}function getPdfManager({data:e,password:t,disableAutoFetch:a,rangeChunkSize:r,length:n,docBaseUrl:s,enableXfa:c,evaluatorOptions:l}){const h={source:null,disableAutoFetch:a,docBaseUrl:s,docId:o,enableXfa:c,evaluatorOptions:l,handler:d,length:n,password:t,rangeChunkSize:r},u=Promise.withResolvers();let f;if(e){try{h.source=e;f=new LocalPdfManager(h);u.resolve(f)}catch(e){u.reject(e)}return u.promise}let g,p=[];try{g=new PDFWorkerStream(d)}catch(e){u.reject(e);return u.promise}const m=g.getFullReader();m.headersReady.then((function(){if(m.isRangeSupported){h.source=g;h.length=m.contentLength;h.disableAutoFetch||=m.isStreamingSupported;f=new NetworkPdfManager(h);for(const e of p)f.sendProgressiveData(e);p=[];u.resolve(f);i=null}})).catch((function(e){u.reject(e);i=null}));let b=0;new Promise((function(e,t){const readChunk=function({value:e,done:a}){try{ensureNotTerminated();if(a){f||function(){const e=arrayBuffersToBytes(p);n&&e.length!==n&&warn("reported HTTP length is different from actual");try{h.source=e;f=new LocalPdfManager(h);u.resolve(f)}catch(e){u.reject(e)}p=[]}();i=null;return}b+=e.byteLength;m.isStreamingSupported||d.send("DocProgress",{loaded:b,total:Math.max(b,m.contentLength||0)});f?f.sendProgressiveData(e):p.push(e);m.read().then(readChunk,t)}catch(e){t(e)}};m.read().then(readChunk,t)})).catch((function(e){u.reject(e);i=null}));i=function(e){g.cancelAllRequests(e)};return u.promise}d.on("GetPage",(function(e){return a.getPage(e.pageIndex).then((function(e){return Promise.all([a.ensure(e,"rotate"),a.ensure(e,"ref"),a.ensure(e,"userUnit"),a.ensure(e,"view")]).then((function([e,t,a,r]){return{rotate:e,ref:t,userUnit:a,view:r}}))}))}));d.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return a.ensureCatalog("getPageIndex",[t])}));d.on("GetDestinations",(function(e){return a.ensureCatalog("destinations")}));d.on("GetDestination",(function(e){return a.ensureCatalog("getDestination",[e.id])}));d.on("GetPageLabels",(function(e){return a.ensureCatalog("pageLabels")}));d.on("GetPageLayout",(function(e){return a.ensureCatalog("pageLayout")}));d.on("GetPageMode",(function(e){return a.ensureCatalog("pageMode")}));d.on("GetViewerPreferences",(function(e){return a.ensureCatalog("viewerPreferences")}));d.on("GetOpenAction",(function(e){return a.ensureCatalog("openAction")}));d.on("GetAttachments",(function(e){return a.ensureCatalog("attachments")}));d.on("GetDocJSActions",(function(e){return a.ensureCatalog("jsActions")}));d.on("GetPageJSActions",(function({pageIndex:e}){return a.getPage(e).then((function(e){return a.ensure(e,"jsActions")}))}));d.on("GetOutline",(function(e){return a.ensureCatalog("documentOutline")}));d.on("GetOptionalContentConfig",(function(e){return a.ensureCatalog("optionalContentConfig")}));d.on("GetPermissions",(function(e){return a.ensureCatalog("permissions")}));d.on("GetMetadata",(function(e){return Promise.all([a.ensureDoc("documentInfo"),a.ensureCatalog("metadata")])}));d.on("GetMarkInfo",(function(e){return a.ensureCatalog("markInfo")}));d.on("GetData",(function(e){return a.requestLoadedStream().then((function(e){return e.bytes}))}));d.on("GetAnnotations",(function({pageIndex:e,intent:t}){return a.getPage(e).then((function(a){const r=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(r);return a.getAnnotationsData(d,r,t).then((e=>{finishWorkerTask(r);return e}),(e=>{finishWorkerTask(r);throw e}))}))}));d.on("GetFieldObjects",(function(e){return a.ensureDoc("fieldObjects")}));d.on("HasJSActions",(function(e){return a.ensureDoc("hasJSActions")}));d.on("GetCalculationOrderIds",(function(e){return a.ensureDoc("calculationOrderIds")}));d.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:r,filename:i}){const n=[a.requestLoadedStream(),a.ensureCatalog("acroForm"),a.ensureCatalog("acroFormRef"),a.ensureDoc("startXRef"),a.ensureDoc("xref"),a.ensureDoc("linearization"),a.ensureCatalog("structTreeRoot")],s=[],o=e?null:getNewAnnotationsMap(r),[c,l,h,u,f,g,p]=await Promise.all(n),m=f.trailer.getRaw("Root")||null;let b;if(o){p?await p.canUpdateStructTree({pdfManager:a,xref:f,newAnnotationsByPage:o})&&(b=p):await StructTreeRoot.canCreateStructureTree({catalogRef:m,pdfManager:a,newAnnotationsByPage:o})&&(b=null);const e=AnnotationFactory.generateImages(r.values(),f,a.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===b?s:[];for(const[r,i]of o)t.push(a.getPage(r).then((t=>{const a=new WorkerTask(`Save (editor): page ${r}`);return t.saveNewAnnotations(d,a,i,e).finally((function(){finishWorkerTask(a)}))})));null===b?s.push(Promise.all(t).then((async e=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:o,xref:f,catalogRef:m,pdfManager:a,newRefs:e});return e}))):b&&s.push(Promise.all(t).then((async e=>{await b.updateStructureTree({newAnnotationsByPage:o,pdfManager:a,newRefs:e});return e})))}if(e)s.push(a.serializeXfaData(r));else for(let e=0;ee.needAppearances)),k=l instanceof Dict&&l.get("XFA")||null;let C=null,v=!1;if(Array.isArray(k)){for(let e=0,t=k.length;e{"string"==typeof a&&(e[t]=stringToPDFString(a))}));F={rootRef:m,encryptRef:f.trailer.getRaw("Encrypt")||null,newRef:f.getNewTemporaryRef(),infoRef:f.trailer.getRaw("Info")||null,info:e,fileIds:f.trailer.get("ID")||null,startXRef:g?u:f.lastXRefStreamPos??u,filename:i}}return incrementalUpdate({originalData:c.bytes,xrefInfo:F,newRefs:w,xref:f,hasXfa:!!k,xfaDatasetsRef:C,hasXfaDatasetsEntry:v,needAppearances:S,acroFormRef:h,acroForm:l,xfaData:x,useXrefStream:isDict(f.topDict,"XRef")}).finally((()=>{f.resetNewTemporaryRef()}))}));d.on("GetOperatorList",(function(e,t){const r=e.pageIndex;a.getPage(r).then((function(a){const i=new WorkerTask(`GetOperatorList: page ${r}`);startWorkerTask(i);const n=s>=Se.INFOS?Date.now():0;a.getOperatorList({handler:d,sink:t,task:i,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage}).then((function(e){finishWorkerTask(i);n&&info(`page=${r+1} - getOperatorList: time=${Date.now()-n}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));d.on("GetTextContent",(function(e,t){const{pageIndex:r,includeMarkedContent:i,disableNormalization:n}=e;a.getPage(r).then((function(e){const a=new WorkerTask("GetTextContent: page "+r);startWorkerTask(a);const o=s>=Se.INFOS?Date.now():0;e.extractTextContent({handler:d,task:a,sink:t,includeMarkedContent:i,disableNormalization:n}).then((function(){finishWorkerTask(a);o&&info(`page=${r+1} - getTextContent: time=`+(Date.now()-o)+"ms");t.close()}),(function(e){finishWorkerTask(a);a.terminated||t.error(e)}))}))}));d.on("GetStructTree",(function(e){return a.getPage(e.pageIndex).then((function(e){return a.ensure(e,"getStructTree")}))}));d.on("FontFallback",(function(e){return a.fontFallback(e.id,d)}));d.on("Cleanup",(function(e){return a.cleanup(!0)}));d.on("Terminate",(function(e){r=!0;const t=[];if(a){a.terminate(new AbortException("Worker was terminated."));const e=a.cleanup();t.push(e);a=null}else clearGlobalCaches();i&&i(new AbortException("Worker was terminated."));for(const e of n){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){d.destroy();d=null}))}));d.on("Ready",(function(t){!function setupDoc(e){function onSuccess(e){ensureNotTerminated();d.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);d.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);a.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);d.send("DocException",e)}))}else e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException?d.send("DocException",e):d.send("DocException",new UnknownErrorException(e.message,e.toString()))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?a.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();getPdfManager(e).then((function(e){if(r){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}a=e;a.requestLoadedStream(!0).then((e=>{d.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}(e);e=null}));return u}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);WorkerMessageHandler.setup(t,e);t.send("ready",null)}}"undefined"==typeof window&&!t&&"undefined"!=typeof self&&function isMessagePort(e){return"function"==typeof e.postMessage&&"onmessage"in e}(self)&&WorkerMessageHandler.initializeFromPort(self);var hc=__webpack_exports__.WorkerMessageHandler;export{hc as WorkerMessageHandler}; \ No newline at end of file diff --git a/src/App.svelte b/src/App.svelte index 9cb2388..5934735 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -8,6 +8,7 @@ import Help from "./lib/Help.svelte"; import SvelteMarkdown from "svelte-markdown"; import CodeRenderer from "./renderers/Code.svelte"; + import UserCodeRenderer from "./renderers/userCode.svelte"; import EmRenderer from "./renderers/Em.svelte"; import ListRenderer from "./renderers/ListRenderer.svelte"; import ListItemRenderer from "./renderers/ListItem.svelte"; @@ -23,8 +24,10 @@ import SendIcon from "./assets/send.svg"; import WaitIcon from "./assets/wait.svg"; import UploadIcon from "./assets/upload-icon.svg"; + import PDFIcon from "./assets/pdf-icon.svg"; import { afterUpdate } from "svelte"; - import { conversations, chosenConversationId, settingsVisible, helpVisible, clearFileInputSignal } from "./stores/stores"; + import { processPDF } from './managers/pdfManager'; + import { conversations, chosenConversationId, settingsVisible, helpVisible, clearFileInputSignal, clearPDFInputSignal } from "./stores/stores"; import { isAudioMessage, formatMessageForMarkdown } from "./utils/generalUtils"; import { routeMessage, newChat, deleteMessageFromConversation } from "./managers/conversationManager"; import { copyTextToClipboard } from './utils/generalUtils'; @@ -34,10 +37,14 @@ import { base64Images } from './stores/stores'; import { closeStream } from './services/openaiService'; - let fileInputElement; // This will hold the reference to your file input element + let fileInputElement; + let pdfInputElement; let input: string = ""; - let textAreaElement; // Reference to the textarea element - let editTextArea; // Reference to the editing textarea element + let textAreaElement; + let editTextArea; + + let pdfFile; + let pdfOutput = ''; let chatContainer: HTMLElement; let moreButtonsToggle: boolean = false; @@ -51,6 +58,11 @@ clearFileInputSignal.set(false); // Reset the signal } + $: if ($clearPDFInputSignal && pdfInputElement) { + pdfInputElement.value = ''; + clearPDFInputSignal.set(false); // Reset the signal + } + $: { const currentConversationId = $chosenConversationId; const currentConversations = $conversations; @@ -66,6 +78,22 @@ } } + + async function uploadPDF(event) { + pdfFile = event.target.files[0]; // Get the first file (assuming single file upload) + if (pdfFile) { + pdfOutput = await processPDF(pdfFile); + console.log(pdfOutput); + } +} + +function clearFiles() { + base64Images.set([]); // Assuming this is a writable store tracking uploaded images + pdfFile = null; // Clear the file variable + pdfOutput = ''; // Reset the output + pdfInputElement.value = ''; + + } let chatContainerObserver: MutationObserver | null = null; @@ -109,6 +137,7 @@ } } } + const textMaxHeight = 300; // Maximum height in pixels function autoExpand(event) { @@ -124,8 +153,9 @@ function autoExpand(event) { function processMessage() { let convId = $chosenConversationId; - routeMessage(input, convId); + routeMessage(input, convId, pdfOutput); input = ""; + clearFiles (); textAreaElement.style.height = '96px'; // Reset the height after sending } function scrollChat() { @@ -142,13 +172,19 @@ function autoExpand(event) { }); $: isVisionMode = $selectedMode.includes('Vision'); + $: isGPTMode = $selectedMode.includes('GPT'); $: conversationTitle = $conversations[$chosenConversationId] ? $conversations[$chosenConversationId].title : "ChatGPT"; -let uploadedFileCount: number = 0; // New variable to track the number of files uploaded +let uploadedFileCount: number = 0; $: uploadedFileCount = $base64Images.length; +let uploadedPDFCount: number = 0; +$: if (pdfOutput) { + uploadedPDFCount = 1; } else { uploadedPDFCount = 0; +} + function startEditMessage(i: number) { editingMessageId = i; editingMessageContent = $conversations[$chosenConversationId].history[i].content; @@ -170,10 +206,16 @@ function startEditMessage(i: number) { } // Process the edited message as new input let convId = $chosenConversationId; - routeMessage(editedContent, convId); + routeMessage(editedContent, convId, pdfOutput); cancelEdit(); // Reset editing state } + function isImageUrl(url) { + // Ensure the URL has no spaces and matches the domain and specific content type for images + return !/\s/.test(url) && + url.includes('blob.core.windows.net') && + /rsct=image\/(jpeg|jpg|gif|png|bmp)/i.test(url); + } @@ -211,6 +253,9 @@ SmoothGPT <div> {#each $conversations[$chosenConversationId].history as message, i} + + {#if message.role !=='system'} + <div class="message relative inline-block bg-primary px-2 pb-5 flex flex-col"> <div class="profile-picture flex"> <div> @@ -245,25 +290,46 @@ SmoothGPT <div class="message-display px-20 text-[1rem]"> - {#if isAudioMessage(message)} - <div class="pb-3"> - <AudioPlayer audioUrl={message.audioUrl} /> - </div> - {:else} + {#if isImageUrl(message.content)} + <img src={message.content} alt="Generated" class="max-w-full h-auto my-3"/> + <div class="text-sm text-gray-500"> + This image will be available for 60 minutes. Right click + save as! + </div> + {:else if isAudioMessage(message)} + <div class="pb-3"> + <AudioPlayer audioUrl={message.audioUrl} /> + </div> + {:else} + + {#if message.role === 'assistant'} <SvelteMarkdown renderers={{ code: CodeRenderer, em: EmRenderer, list: ListRenderer, listitem: ListItemRenderer, - codespan: CodeSpanRenderer, paragraph: ParagraphRenderer, html: HtmlRenderer, }} source={formatMessageForMarkdown(message.content.toString())} /> +{:else} + + <SvelteMarkdown renderers={{ + code: UserCodeRenderer, + codespan: CodeSpanRenderer, + em: EmRenderer, + list: ListRenderer, + listitem: ListItemRenderer, + paragraph: ParagraphRenderer, + html: HtmlRenderer, + }} source={formatMessageForMarkdown(message.content.toString())} /> + + +{/if} + {/if} </div> <div class="toolbelt flex space-x-2 pl-20 mb-2 tools"> {#if message.role === 'assistant'} - {#if !isAudioMessage(message)} + {#if !isAudioMessage(message) && !isImageUrl(message.content)} <button class="copyButton w-5" on:click={() => copyTextToClipboard(message.content)}> <img class="copy-icon" alt="Copy" src={CopyIcon} /> </button> @@ -284,7 +350,9 @@ SmoothGPT </div> - {/each} +{/if} + + {/each} </div> </div> {:else} @@ -298,15 +366,37 @@ SmoothGPT <div class="inputbox-container w-full flex justify-center items-center bg-primary"> <div class="inputbox flex flex-1 bg-primary mt-auto mx-auto max-w-3xl mb-3"> - {#if isVisionMode} - <input type="file" id="imageUpload" multiple accept="image/*" on:change="{handleImageUpload}" bind:this={fileInputElement} class="file-input"> - <label for="imageUpload" class="file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors"> - {#if uploadedFileCount === 0} - <img src={UploadIcon} alt="Upload" class="upload-icon icon-white"> - {:else} - <span class="fileCount">{uploadedFileCount}</span> - {/if} - </label> + {#if isVisionMode} + <input type="file" id="imageUpload" multiple accept="image/*" on:change="{handleImageUpload}" bind:this={fileInputElement} class="file-input"> + <label for="imageUpload" class="file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors"> + {#if uploadedFileCount > 0} + <span class="fileCount">{uploadedFileCount}</span> + {:else} + <img src={UploadIcon} alt="Upload" class="upload-icon icon-white"> + {/if} + </label> + + {#if uploadedFileCount > 0} + <button on:click={clearFiles} class="clear-btn">X</button> + {/if} + + +{:else if isGPTMode} +<input type="file" id="pdfUpload" accept="application/pdf" +on:change="{event => uploadPDF(event)}" bind:this={pdfInputElement} class="file-input"> + +<label for="pdfUpload" class="file-label bg-chat rounded py-2 px-4 mx-1 cursor-pointer hover:bg-hover2 transition-colors"> + {#if uploadedPDFCount === 0} + <img src={PDFIcon} alt="PDF" class="pdf-icon icon-white"> + {:else} + <span class="fileCount">{uploadedPDFCount}</span> + {/if} +</label> + +{#if uploadedPDFCount > 0} + <button on:click={clearFiles} class="clear-btn px-4 rounded-lg bg-red-700 mx-2 hover:bg-red-500">X</button> + {/if} + {/if} <textarea bind:this={textAreaElement} @@ -314,7 +404,7 @@ SmoothGPT placeholder="Type your message..." bind:value={input} on:input={autoExpand} - style="height: 96px; overflow-y: auto;" + style="height: 96px; overflow-y: auto; overflow:visible !important;" on:keydown={(event) => { const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); if (!$isStreaming && event.key === "Enter" && !event.shiftKey && !event.ctrlKey && !event.metaKey && !isMobile) { diff --git a/src/assets/pdf-icon.svg b/src/assets/pdf-icon.svg new file mode 100644 index 0000000..d64a80f --- /dev/null +++ b/src/assets/pdf-icon.svg @@ -0,0 +1 @@ +<svg viewBox="0 0 512 512" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#000000"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <title>pdf-document \ No newline at end of file diff --git a/src/lib/Help.svelte b/src/lib/Help.svelte index a451c9b..5afa428 100644 --- a/src/lib/Help.svelte +++ b/src/lib/Help.svelte @@ -26,7 +26,8 @@

    Key Features:

    • Your API calls are safely made directly in the browser, not server-side. All data is stored in your browser cache or session.
    • -
    • Switch between GPT, Vision, and TTS models with shared conversation context.
    • +
    • Switch between GPT, Vision, Dall-E, and TTS models with shared conversation context.
    • +
    • Upload PDFs or images and ask the AI questions about their contents.
    • Copy or delete messages easily.
    • Edit messages to change the conversation.
    • Safely stop incoming messages.
    • @@ -44,7 +45,7 @@ Check out other API frontends -

      Note on data storage: If you browse away while a response is streaming in, you will miss that data. If you refresh your page, TTS MP3 files are lost, but conversations are maintained. If you wipe your browser cache, ALL content is lost. You can download your session locally and restore it anytime.

      +

      Note on data storage: If you browse away while a response is streaming in, you will miss that data. If you refresh your page, TTS MP3 files are lost, but conversations are maintained. Images generated by Dall-E are only available for 60 minutes. If you wipe your browser cache, ALL content is lost. You can download your session locally and restore it anytime.

      diff --git a/src/lib/Settings.svelte b/src/lib/Settings.svelte index cf50eb0..ff4e1aa 100644 --- a/src/lib/Settings.svelte +++ b/src/lib/Settings.svelte @@ -1,5 +1,5 @@ + +
      + {text} +
      + + diff --git a/src/services/openaiService.ts b/src/services/openaiService.ts index 98e360a..39cec6e 100644 --- a/src/services/openaiService.ts +++ b/src/services/openaiService.ts @@ -3,7 +3,7 @@ import { Configuration, OpenAIApi } from "openai"; import type { ChatCompletionRequestMessage, } from "openai"; import type { ChatCompletionRequestMessageRoleEnum } from "openai"; import { apiKey} from "../stores/stores"; -import { selectedModel, selectedVoice, audioUrls, defaultAssistantRole, isStreaming, streamContext } from '../stores/stores'; +import { selectedModel, selectedVoice, audioUrls, selectedSize, selectedQuality, defaultAssistantRole, isStreaming, streamContext } from '../stores/stores'; import { conversations, chosenConversationId, combinedTokens, userRequestedStreamClosure } from "../stores/stores"; import { setHistory, countTokens, estimateTokens, displayAudioMessage, cleanseMessage } from '../managers/conversationManager'; import { SSE } from 'sse.js'; // Assuming SSE library is used @@ -411,6 +411,136 @@ let finalMessages = [...cleansedMessages, currentMessage]; }) ); + source.addEventListener("message", async (e) => { // Note: Adding async here makes the callback function async + let payload; + if (e.data !== "[DONE]") { + try { + if (!hasEncounteredError) { + let parsedChunks = parseJSONChunks(e.data); + // Process each parsed JSON object + parsedChunks.forEach((payload) => { + // Your logic to handle each JSON object goes here + // Example: Extracting text and updating history or stream context + let text = payload.choices[0]?.delta?.content; + if (text) { + let msgTicks = countTicks(text); + tickCounter += msgTicks; + if (msgTicks === 0) tickCounter = 0; + if (tickCounter === 3) { + ticks = !ticks; + tickCounter = 0; + } + streamText += text; + streamContext.set({ streamText, convId }); // Update the store + + // Here, we await setHistory within the async IIFE + setHistory([...currentHistory, { + role: "assistant", + content: streamText + "█" + (ticks ? "\n```" : ""), + }], convId); + } + }); + } + } catch (error) { + console.error("Error parsing JSON:", error); + hasEncounteredError = true; + source.close(); + console.log("Stream closed due to parsing error."); + isStreaming.set(false); + + return; + } + + } else { + done = true; + if (get(userRequestedStreamClosure)) { + streamText = streamText.replace(/█+$/, ''); // Removes the block character(s) if present at the end + userRequestedStreamClosure.set(false); // Reset the flag after handling + } + + await setHistory([...currentHistory, { + role: "assistant", + content: streamText, + }], convId); + + + + + estimateTokens(msg, convId); + streamText = ""; + done = true; + console.log("Stream closed"); + source.close(); + // Stream is complete, so set isStreaming back to false. + isStreaming.set(false); + } + }); + + source.addEventListener("error", (e) => { + try { + if (done) return; // If the stream is already marked as done, no further action required. + console.error("Stream error:", e); + } finally { + source.close(); + // Regardless of the cause of the error, the stream is closing, so set isStreaming back to false. + isStreaming.set(false); + } + }); + + source.stream(); + globalSource = source; + } + + export async function sendPDFMessage(msg: ChatCompletionRequestMessage[], convId, pdfOutput) { + userRequestedStreamClosure.set(false); + let hasEncounteredError = false; + + let tickCounter = 0; + let ticks = false; + let currentHistory = get(conversations)[convId].history; + + let roleMsg: ChatCompletionRequestMessage = { + role: get(defaultAssistantRole).type as ChatCompletionRequestMessageRoleEnum, + content: get(conversations)[convId].assistantRole, + }; + + let systemMessage: ChatCompletionRequestMessage = { + role: 'system', // Assuming 'system' is an acceptable value for your backend/API + content: pdfOutput, + }; + + currentHistory.push(systemMessage); + + + msg = [roleMsg, systemMessage, ...msg]; +console.log(msg); + const cleansedMessages = msg.map(cleanseMessage); + + let done = false; + let streamText = ""; + + currentHistory = [...currentHistory]; + isStreaming.set(true); + + let source = new SSE("https://api.openai.com/v1/chat/completions", { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${get(apiKey)}`, + }, + method: "POST", + payload: JSON.stringify({ + model: get(selectedModel), + messages: cleansedMessages, + stream: true, + }), + }); + + console.log("payload", JSON.stringify({ + model: get(selectedModel), + messages: cleansedMessages, + stream: true, + }) + ); source.addEventListener("message", async (e) => { // Note: Adding async here makes the callback function async let payload; @@ -494,4 +624,58 @@ let finalMessages = [...cleansedMessages, currentMessage]; + export async function sendDalleMessage(msg: ChatCompletionRequestMessage[], convId) { + isStreaming.set(true); + let hasEncounteredError = false; + let currentHistory = get(conversations)[convId].history; + + let roleMsg: ChatCompletionRequestMessage = { + role: get(defaultAssistantRole).type as ChatCompletionRequestMessageRoleEnum, + content: get(conversations)[convId].assistantRole, + }; + + msg = [roleMsg, ...msg]; + + const cleansedMessages = msg.map(cleanseMessage); + + const prompt = cleansedMessages[cleansedMessages.length - 1].content; + + try { + let response = await fetch("https://api.openai.com/v1/images/generations", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${get(apiKey)}`, + }, + body: JSON.stringify({ + model: get(selectedModel), + prompt: prompt, + size: get(selectedSize), + quality: get(selectedQuality), + n: 1 + }), + }); + + if (!response.ok) throw new Error('HTTP error, status = ' + response.status); + + let data = await response.json(); + let imageUrl = data.data[0].url; + + // Update the conversation history with the generated image URL + setHistory([...currentHistory, { + role: "assistant", + content: imageUrl, + type: "image" // Adding a type property to distinguish image messages + }], convId); + + } catch (error) { + console.error("Error generating image:", error); + hasEncounteredError = true; + } finally { + isStreaming.set(false); // Notify that the image generation is complete + } + } + + + \ No newline at end of file diff --git a/src/stores/stores.ts b/src/stores/stores.ts index dee301c..ff85054 100644 --- a/src/stores/stores.ts +++ b/src/stores/stores.ts @@ -56,19 +56,44 @@ conversations.subscribe((value) => { export const selectedModel = writable(localStorage.getItem('selectedModel') || 'gpt-3.5-turbo'); export const selectedVoice = writable(localStorage.getItem('selectedVoice') || 'alloy'); export const selectedMode = writable(localStorage.getItem('selectedMode') || 'GPT'); + +export const selectedSize = writable(localStorage.getItem('selectedSize') || '1024x1024'); +export const selectedQuality = writable(localStorage.getItem('selectedQuality') || 'standard'); + + selectedModel.subscribe(value => { localStorage.setItem("selectedModel", value); }); selectedVoice.subscribe(value => { localStorage.setItem("selectedVoice", value); }); + selectedSize.subscribe(value => { + localStorage.setItem("selectedSize", value); + }); + selectedQuality.subscribe(value => { + localStorage.setItem("selectedQuality", value); + }); + selectedMode.subscribe(value => { + localStorage.setItem("selectedMode", value); + }); export const audioUrls = writable([]); - export const showTokens = writable(false); export const base64Images = writable([]); export const clearFileInputSignal = writable(false); + export const clearPDFInputSignal = writable(false); export const isStreaming = writable(false); export const userRequestedStreamClosure = writable(false); - export const streamContext = writable({ streamText: '', convId: null }); \ No newline at end of file + export const streamContext = writable({ streamText: '', convId: null }); + + let storedShowTokens = localStorage.getItem('show_tokens'); +let parsedShowTokens = storedShowTokens !== null ? JSON.parse(storedShowTokens) : false; + +// Create the writable store with the initial value, either from localStorage or default +export const showTokens = writable(parsedShowTokens); + +// Subscribe to changes and update localStorage +showTokens.subscribe(value => { + localStorage.setItem('show_tokens', JSON.stringify(value)); +}); \ No newline at end of file diff --git a/src/styles/styles.css b/src/styles/styles.css index f8267e7..6ca801f 100644 --- a/src/styles/styles.css +++ b/src/styles/styles.css @@ -51,8 +51,9 @@ } .upload-icon { - width: 24px; /* Adjust based on your icon's size */ + width: 36px; /* Adjust based on your icon's size */ height: auto; } + .fileCount { display: inline-flex; align-items: center; @@ -66,6 +67,11 @@ font-size: 16px; /* Adjust based on your design */ } + .pdf-icon { + width: 36px; /* Adjust based on your icon's size */ + height: auto; } + + .copy-icon { filter: invert(60%); } diff --git a/vite.config.ts b/vite.config.ts index 75a0f3d..377e153 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -7,4 +7,27 @@ export default defineConfig({ base: '/', logLevel: 'info', // Options are 'info', 'warn', 'error', and 'silent' + build: { + target: "es2022", + rollupOptions: { + output: { + // PDF.js might benefit from this for handling assets like workers + manualChunks(id) { + if (id.includes('pdf.worker.min.js')) { + return 'pdf.worker.min'; + } + } + } + } + }, + esbuild: { + target: "es2022" + }, + optimizeDeps:{ + esbuildOptions: { + target: "es2022", + } + } + + })